CS U111 · Mid-sem · Practice
Every past-paper program, built step by step
All nine "write a C program" questions from the three past mid-sems, each taken through the five moves of the how-to-start lesson. Each has a skeleton marked against the published marking scheme, and a full solution compiled with clang -Wall and run on the question's sample plus an edge case.
Don't read the solutions first. You already follow model answers well; what needs practice is the start. For each card: read the question, then on paper do moves 1–3 (input → output line, the skeleton, the pattern names) before opening the green box. Then compare. Open the full solution only after you've written your own loop, even a wrong one.
Suggested order (easiest patterns first, not paper order): cricket stats → insert with shift → coin change → characters until Enter → quadratic → largest of three → big-number +1 → smallest from digits. About 20–25 minutes each the first time; aim for 12–15 by the second pass, which is roughly the exam pace.
Cards tagged Lab-exam practice are also good rehearsal for the end-semester lab exam (25%, open book): type them into the compiler and test them on the edge cases shown.
- Characters until Enter
- Big number +1
- Smallest from digits
- Insert with shift
- Largest of three
- Missing break
- Coin change
- Cricket stats
- Quadratic via switch
1 · Characters until Enter 2024 Sem 1 · Part 2 Q11 · 10 marks
Develop a program that reads a sequence of characters (comprising of digits and lowercase alphabets) from the console terminated by an enter character. The program displays the sum of the digits. The program saves only the alphabets in a character array. The program displays the highest alphabet present in the array. (Hint: ASCI values of digits range from 48 to 57 and enter character is 10)
Usecase1: Input Sequence: ab12cd34 · Output: Sum of digits: 10 · Highest alphabet: d
Usecase2: Input Sequence: a1z2g3f9 · Output: Sum of digits: 15 · Highest alphabet: z
Before opening: do moves 1–3 on paper
1 in: a b 1 2 c d 3 4 [Enter], one char at a time → out: 10 and d. 2 A char for the current character, a char array for letters plus a count of how many are stored, an int sum starting at 0. 3 Sentinel loop (stop at Enter) containing accumulate (digits) and store (letters), then find-max over the stored letters.
The routine, applied
- RestateInput arrives one character per read, ending with the Enter key's character (10, written
'\n'in C). Output: the digit sum and the largest letter. - Skeleton
char c; char letters[100]; int count = 0, sum = 0;, a prompt, the firstscanf("%c", &c);, and twoprintfs. The array size is your choice: say so as an assumption. - Pattern"terminated by an enter character" → a sentinel loop:
while (c != '\n'). Inside it: a digit → accumulate; otherwise → store in the array. After it: find the max of the stored letters. - Hand table → loopRows for
ab12cd34: c = 'a' → store (count 1); 'b' → store (2); '1' → sum 1; '2' → sum 3; 'c' → store; 'd' → store; '3' → sum 6; '4' → sum 10; '\n' → stop. Every row is "look at c, do one of two things, read the next c". That last part is what keeps the loop moving. - Dry run & assumptionsSample gives 10 and d ✓. Assumptions: at most 100 letters; input really is only digits and lowercase letters, as stated; if there are no letters at all, print a message instead of reading
letters[0](which would hold garbage).
Skeleton, marked against the scheme
#include <stdio.h>
int main(void) {
char c, letters[100]; /* declarations 1 */
int count = 0, sum = 0, i;
char highest;
printf("Enter digits and lowercase letters: ");
scanf("%c", &c); /* reading characters 1 */
while (c != '\n') { /* exit condition 1 */
/* digit: sum += c - '0' char → digit 2 */
/* else: letters[count++] = c letters into array 2 */
scanf("%c", &c); /* reading characters 1 */
}
/* max over letters[0..count-1] largest letter 2 */
printf("Sum of digits: %d\n", sum);
return 0;
}
Full solution (compiled, no warnings)
#include <stdio.h>
int main(void) {
char c;
char letters[100]; /* only the alphabets go here */
int count = 0; /* how many letters stored */
int sum = 0; /* sum of the digits */
int i;
char highest;
printf("Enter digits and lowercase letters: ");
scanf("%c", &c);
while (c != '\n') { /* Enter is character 10 = '\n' */
if (c >= '0' && c <= '9')
sum = sum + (c - '0'); /* '7' - '0' = 7 */
else
letters[count++] = c;
scanf("%c", &c);
}
printf("Sum of digits: %d\n", sum);
if (count == 0) {
printf("No alphabets entered\n");
} else {
highest = letters[0];
for (i = 1; i < count; i++)
if (letters[i] > highest)
highest = letters[i];
printf("Highest alphabet: %c\n", highest);
}
return 0;
}
Runs, including an input with no letters:
Enter digits and lowercase letters: ab12cd34
Sum of digits: 10
Highest alphabet: d
Enter digits and lowercase letters: a1z2g3f9
Sum of digits: 15
Highest alphabet: z
Enter digits and lowercase letters: 2025
Sum of digits: 9
No alphabets entered
sum += c;adds the character code: '1' is 49, so the sample would give 49 + 50 + 51 + 52 = 202. You needc - '0'(2 of the 10 marks).- Forgetting the second
scanfinside the loop:cnever changes, so the loop never ends. - Losing track of how many letters were stored. The scheme's notes stress it: "Finding the size of this array is important."
countis that size. - Reading with
%dor%s. Only%chands you one character, Enter included.
2 · Big account number + 1 2025 Sem 1 · Q5 · 14 marks
In a banking system, each customer has an account number that can be extremely large, and the system stores account numbers as an array of digits for efficient processing. Each digit of the account number is stored in a list, with the most significant digit at the beginning of the list and the least significant at the end.
Now, when a new customer joins, the system increments the last account number by one. However, the challenge is that the account number is stored in an array, and due to its large size, performing the increment operation requires handling potential carries. You are given an array digits representing a large integer, where each digits[i] is the ith digit of the integer. The digits are ordered from the most significant to the least significant, and there are no leading zeros in the integer. Your task is to increment the large integer by one and print the resulting array of digits. The result must reflect the correct account number after the increment. Assume that second most significant digit is not 9.
Sample Input: {1,0,9,9} · Sample Output: {1,1,0,0}
#include <stdio.h>
int main(){
int n; //Size of account number
scanf("%d",&n);
int last_accno[n]; //Scan last account number
for(int i=0;i<n;i++)
scanf("%d",&last_accno[i]);
int new_accno[n];
//Write logic for new account no.Before opening: do moves 1–3 on paper
1 1 0 9 9 → 1 1 0 0 because 1099 + 1 = 1100. 2 The template already declares and reads everything; you add the logic and the print loop (the template doesn't print). 3 Copy the array, then walk from the right end while the digit is 9 (a carry), then add 1 once.
The routine, applied
- RestateIt's column addition of +1, done on an array of digits: the last digit gets the 1, and a 9 turns into 0 and passes the 1 left.
- SkeletonGiven by the template. Yours to add: a copy loop into
new_accno, and a finalforthat printsnew_accno[0..n-1]. - PatternCopy, then a walk from the right that stops at the first digit that isn't 9 (a search, going backwards).
- Hand table → loopThe table from the lesson: index 3 (9 → 0, carry), index 2 (9 → 0, carry), index 1 (0 → 1, stop). The repeating rows give
while (d[i] == 9) { d[i] = 0; i--; }; the last row givesd[i]++once. - Dry run & assumptionsSample ✓. The question's own assumption ("second most significant digit is not 9") guarantees the carry stops by index 1, so the answer never needs an extra digit. Say so: that's why no bigger array is needed.
Skeleton, marked
No marking scheme was published for this paper. Its model answer is a 20-line version with a flag variable; the one below does the same in 8 lines of logic.
Full solution (template + logic, compiled, no warnings)
#include <stdio.h>
int main(){
int n; //Size of account number
scanf("%d",&n);
int last_accno[n]; //Scan last account number
for(int i=0;i<n;i++)
scanf("%d",&last_accno[i]);
int new_accno[n];
//Write logic for new account no.
int i;
for (i = 0; i < n; i++) /* step 1: copy */
new_accno[i] = last_accno[i];
i = n - 1; /* step 2: start at the last digit */
while (i >= 0 && new_accno[i] == 9) {
new_accno[i] = 0; /* 9 + 1 = 10: write 0, carry 1 */
i--;
}
if (i >= 0)
new_accno[i] = new_accno[i] + 1; /* the carry lands here */
for (i = 0; i < n; i++)
printf("%d", new_accno[i]);
printf("\n");
return 0;
}
4 1 0 9 9
1100
3 1 2 3
124
5 3 0 9 9 9
31000
Unpack: why write i >= 0 first in the while condition?
&& stops as soon as its left side is false. If the walk ever went past index 0, i >= 0 fails first and new_accno[-1] is never read. Under this question's assumption it can't happen, but the order is the safe habit.
- Starting the walk at index 0: addition starts at the least significant digit, which is the last index.
- Forgetting to copy first:
new_accnostarts as garbage, so any digit you don't touch prints nonsense. - Adding 1 to every digit, or carrying past a digit that wasn't 9.
- Not printing: the template stops at "Write logic", but the question says "print the resulting array".
3 · Smallest number from the digits, no arrays 2025 Sem 1 · Q6 · 14 marks
Write a C program that will read a 5-digit positive integer N and output the smallest integer possible by shuffling the digits of N. For example if N = 62371 then the output should be 12367. Assume all the digits of N are distinct from each other. You are not allowed to use arrays.
Before opening: do moves 1–3 on paper
1 62371 → 12367: the same digits, smallest first. 2 int n, m;, scanf, printf("Output = %d\n", m);. 3 Try the digits 0, 1, 2, … 9 in order; for each, peel n to see whether it's there; if it is, append it to m.
The routine, applied
- Restate"Smallest integer by shuffling" = the digits in increasing order. Without arrays you can't store and sort them. But you don't need to: just ask, in order, whether each digit 0–9 is present.
- SkeletonInputs:
n. Output:m, starting at 0. Helpers: a loop digitdand a working copyt(so peeling doesn't destroyn). - PatternDigit peel (
t % 10is the last digit,t / 10drops it) inside a search overd = 0..9. Appending digitdtomism = m * 10 + d. - Hand table → loopFor 62371: d = 0 no; d = 1 yes → m = 1; d = 2 → 12; d = 3 → 123; d = 4, 5 no; d = 6 → 1236; d = 7 → 12367; d = 8, 9 no. Outer loop over
d, inner loop peeling a fresh copy ofn. - Dry run & assumptionsSample ✓. The 0 question: for 50314 the digits in order give 01345, which as an integer is 1345, a 4-digit number. The question doesn't say whether that's allowed. Choose and state it: "Assumption: the result must stay 5 digits, so the smallest non-zero digit goes first" gives 10345. The opposite reading gives 1345 (which is what the published model answer outputs).
Unpack: why does m = m * 10 + d attach d on the right?
Multiplying by 10 shifts every digit one place left and leaves a 0 at the end; adding d fills that 0. So 12 → 120 → 123. It's the digit peel run backwards.
Solution A: the core idea, 10 lines (compiled, no warnings)
#include <stdio.h>
int main(void) {
int n, t, d, m = 0;
scanf("%d", &n);
for (d = 0; d <= 9; d++) /* try digits smallest first */
for (t = n; t > 0; t = t / 10) /* peel n's digits one by one */
if (t % 10 == d)
m = m * 10 + d; /* found d: append it */
printf("Output = %d\n", m);
return 0;
}
62371
Output = 12367
50314
Output = 1345
Note the second run: a 0 digit ends up first and disappears, giving 1345.
Solution B: with the 5-digit assumption (compiled, no warnings)
#include <stdio.h>
int main(void) {
int n, t, d, m, small;
scanf("%d", &n); /* a 5-digit number, digits distinct */
small = 10; /* smallest NONZERO digit goes first */
for (t = n; t > 0; t = t / 10)
if (t % 10 != 0 && t % 10 < small)
small = t % 10;
m = small;
for (d = 0; d <= 9; d++) { /* then every other digit, smallest up */
if (d == small)
continue;
for (t = n; t > 0; t = t / 10)
if (t % 10 == d)
m = m * 10 + d; /* append d on the right */
}
printf("Output = %d\n", m);
return 0;
}
62371
Output = 12367
50314
Output = 10345
98765
Output = 56789
The published model answer is about 30 lines (find the minimum, remove it, rebuild the number, repeat five times). It's correct for the sample, and outputs 1345 for 50314. Both readings are defensible if stated; an unstated choice is what risks marks.
- Peeling
nitself: after the first pass it's 0 and every later digit search fails. Peel a copyt = n, fresh for eachd. - Reaching for an array to sort the digits: explicitly forbidden, so the logic marks go.
- Not saying what happens to a 0 digit.
4 · Insert into an array, shifting right 2026 Sem 2 · Part B Q1 · 16 marks
Write a program to insert a new element it to an array of integers at a given position (index), while doing so, all the elements from that position(index) must be moved to right by one position, and the original last element is lost as it moves beyond the boundary. Then print the resultant array. We assume that the initial array has n elements. You are permitted to declare and use only one array, not more than one. [16]
You are expected to do the following. Declare an array of integers of size n, where n is given as input through scanf(). Similarly, accept an integer to be inserted and the position (index) where it is to be inserted. Also scan all n initial values for elements of the original array.
Ex: Assume that the Original array where n=5, is {2 5 6 4 9}; the new element to be inserted is 10, at insert position (index)=2. After the execution of the program, the resulting array should be :{ 2 5 10 6 4}. Write code to achieve this. Note: the last original element , that is 9 is lost.
Before opening: do moves 1–3 on paper
1 n=5, 2 5 6 4 9, val 10, pos 2 → 2 5 10 6 4. 2 int n read first, then int a[n], a loop of scanfs, val, pos, and a print loop. 3 Shift right, starting from the last index; then one assignment.
The routine, applied
- RestateFour inputs (n, the n values, the value, the position), one output (the whole array). The 9 falls off the end.
- SkeletonRead
nbefore declaringint a[n](the size must be known at that line), then the values, thenvalandpos. Finish with a print loop. - PatternShift: elements move one place to the right, so start at the right end.
- Hand table → loopa[4] = a[3], a[3] = a[2], then a[2] = 10 (the lesson's table and figure). Loop:
for (i = n - 1; i > pos; i--) a[i] = a[i - 1];thena[pos] = val;. - Dry run & assumptionsi = 4, 3 then stops at 2 → 2 5 10 6 4 ✓. Assumption: 0 ≤ pos ≤ n − 1. Check the edges: pos = n − 1 just replaces the last element; pos = 0 shifts everything.
Skeleton, marked against the scheme
#include <stdio.h> /* program, syntax, variables 3 */
int main(void) {
int n, i, val, pos;
scanf("%d", &n); /* array declaration, */
int a[n]; /* scanf and printf 5 */
for (i = 0; i < n; i++) scanf("%d", &a[i]);
scanf("%d %d", &val, &pos);
/* shift right from the end, then a[pos] = val core logic 8 */
for (i = 0; i < n; i++) printf(" %d", a[i]);
return 0;
}
Full solution (compiled, no warnings)
#include <stdio.h>
int main(void) {
int n, i, val, pos;
printf("Number of elements: ");
scanf("%d", &n);
int a[n]; /* the only array */
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Element to insert: ");
scanf("%d", &val);
printf("Position (index 0 to %d): ", n - 1);
scanf("%d", &pos);
for (i = n - 1; i > pos; i--) /* shift RIGHT-TO-LEFT; old a[n-1] is lost */
a[i] = a[i - 1];
a[pos] = val;
printf("Resultant array:");
for (i = 0; i < n; i++)
printf(" %d", a[i]);
printf("\n");
return 0;
}
Number of elements: 5
Enter 5 elements: 2 5 6 4 9
Element to insert: 10
Position (index 0 to 4): 2
Resultant array: 2 5 10 6 4
Number of elements: 5
Enter 5 elements: 2 5 6 4 9
Element to insert: 10
Position (index 0 to 4): 4
Resultant array: 2 5 6 4 10
Number of elements: 5
Enter 5 elements: 2 5 6 4 9
Element to insert: 10
Position (index 0 to 4): 0
Resultant array: 10 2 5 6 4
And the classic wrong version, shifting left-to-right (for (i = pos + 1; i < n; i++) a[i] = a[i - 1];), compiled on the same sample:
2 5 10 6 6
- Shifting left-to-right: every cell after
posbecomes a copy of the same value (2 5 10 6 6above). - Declaring a second array to copy into: the question allows only one.
int a[n];written beforescanf("%d", &n);: the array gets whatever garbagenheld.- Loop bound
i <= nin the read or print loop: writes or readsa[n], one past the end.
5 · Largest of three, and a switch that falls through 2026 Sem 2 · Part B Q2 · 10 + 6 marks
(a) Largest of three distinct integers
Write a C program that takes 3 distinct integers as input and determines which is the largest. Your program should not use the logical AND operator (i.e. &&) and should use at most three if-else statements and no temporary variables (i.e. other than the variables storing the three values). [10]
Before opening: which restriction rules out the "obvious" answer?
The obvious answer is if (a > b && a > c) — banned (no &&). The other obvious one, max = a; if (b > max) max = b; …, uses a temporary variable — also banned. What's left is nesting: compare two, then compare the winner with the third.
- Restate
3 7 5 → 7. Three restrictions, underlined: no&&, at most three if-else, no extra variables. - Skeleton
int a, b, c;, prompt,scanf("%d %d %d", …). Each branch prints (no variable to hold the answer). That's the scheme's 2 marks. - PatternA two-round tournament:
avsb, then the winner vsc. - Hand table → loopNo loop here; the "table" is a tree: a > b? → yes: a vs c; no: b vs c. Three if-elses exactly (one outer, two inner).
- Dry run3 7 5: a > b false → b > c true → 7 ✓. Try the largest in each position, and negatives.
Full solution (compiled, no warnings)
#include <stdio.h>
int main(void) {
int a, b, c;
printf("Enter three distinct integers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b) { /* a beat b: now only a and c can win */
if (a > c)
printf("Largest = %d\n", a);
else
printf("Largest = %d\n", c);
} else { /* b beat a: now only b and c can win */
if (b > c)
printf("Largest = %d\n", b);
else
printf("Largest = %d\n", c);
}
return 0;
}
Enter three distinct integers: 3 7 5
Largest = 7
Enter three distinct integers: 9 2 4
Largest = 9
Enter three distinct integers: -1 -5 -3
Largest = -1
(b) Prof. Cursor's switch
Prof. Cursor gives the following program to determine if a given number is positive, negative or zero. Determine why the program does not work correctly, and provide a modified program that will work correctly without adding additional cases. [6]
#include <stdio.h>
int main() {
int n = 6;
switch(n > 0 ? 1 : n < 0 ? -1 : 2) {
case -1:
printf("Negative");
case 1:
printf("Positive");
default:
printf("Zero");
}
return 0;
}Why it fails (3 marks): for n = 6 the ternary gives 1, so execution jumps to case 1, prints "Positive", and then, with no break, falls through into default and prints "Zero" too. Compiled, it prints:
PositiveZero
The fix (3 marks): a break; at the end of each case. The default already handles zero (the ternary gives 2 for it), so no new case is needed.
Fixed program (compiled; tested with n = 6, −4 and 0)
#include <stdio.h>
int main() {
int n = 6;
switch(n > 0 ? 1 : n < 0 ? -1 : 2) {
case -1:
printf("Negative");
break; /* added */
case 1:
printf("Positive");
break; /* added */
default:
printf("Zero");
}
return 0;
}
Positive
Changing the 6 to −4 prints Negative; to 0 prints Zero.
- (a) Using
&&, amaxvariable, or a four-branch else-if chain: each breaks a stated restriction. - (b) Saying "it's wrong" without saying what it prints and why (fall-through). The identification is half the marks.
- (b) Adding
case 0:: the question forbids new cases.
6 · All ways to give change 2026 Sem 2 · Part B Q3 · 16 marks
Consider the problem to find change of a given currency note having value as “price”, where the available denominations are “deno1”, “deno2” and “deno3”. Assume that “deno1” > “deno2” > “deno3”. You need to write a C program to solve this problem. Your program must take as input the value of “price”, and the values of denomination for “deno1”, “deno2” and “deno3”. The program produces as output the all possible combinations of the number of denominations of the form <d11, d12, d13> <d21, d22, d23> <d31, d32, d33> <d41, d42, d43> … where <di1, di2, and di3> indicates the number of denominations of “deno1”, “deno2” and “deno3” respectively, that results in a valid change for “price”. The program also produces as output the total number of ways, i.e., the count of the tuples of <di1, di2, di3>, using which the given “price” can be changed. The following partial code snippet is provided as a template to write your program. Note: You are required to write the full program as your answer.
#include<stdio.h>
int main(){
int price = 0; //for the currency note
int deno1 = 0, deno2 = 0, deno3 = 0; // for the denominations
int ways = 0; // for the number of ways the change possible
//here you may declare any additional variables, if needed
//write code in the following to print the appropriate prompt and take the corresponding inputs
//write your logic in the following using only for(; ;) loop
//display in the following the number of ways; display “Not Possible” if there is no way to change.
return 0;
}
Finally, show the result of executing (using dry run) your program for “price” = 110, deno1 = 100, deno2 = 20, deno3 = 10. [16]
Before opening: do moves 1–3 on paper
1 110 with 100/20/10 → every (d1, d2, d3) with 100·d1 + 20·d2 + 10·d3 = 110, and how many. 2 The template declares most of it; add d1, d2, d3, the prompts and scanfs, and the final "ways or Not Possible". 3 Try everything: one for per denomination, test in the innermost, count the hits.
The routine, applied
- RestateAn unknown count of each note (d1, d2, d3). Output: every combination that adds to the price, then how many.
- SkeletonThe template's comments are the rubric: prompts + inputs (2 marks), the loops (7), "#ways" or "Not Possible" (2), and the written dry run (3 + 2).
- PatternTry everything + count: three unknowns → three nested loops;
ways++on each hit. "Using only for(; ;) loop" is a restriction: nowhile. - Hand table → loopHow far can each count go? At most
price / denonotes of that kind: 110/100 = 1, 110/20 = 5, 110/10 = 11. Sod1 = 0..1,d2 = 0..5,d3 = 0..11, inclusive. - Dry runThe seven rows below, then "#ways: 7". Assumption: all denominations are positive (we divide by them).
| d1 (100s) | d2 (20s) | d3 (10s) | Total |
|---|---|---|---|
| 0 | 0 | 11 | 110 |
| 0 | 1 | 9 | 110 |
| 0 | 2 | 7 | 110 |
| 0 | 3 | 5 | 110 |
| 0 | 4 | 3 | 110 |
| 0 | 5 | 1 | 110 |
| 1 | 0 | 1 | 110 |
Full solution (compiled, no warnings)
#include<stdio.h>
int main(){
int price = 0; //for the currency note
int deno1 = 0, deno2 = 0, deno3 = 0; // for the denominations
int ways = 0; // for the number of ways the change possible
int d1, d2, d3;
printf("Enter price: ");
scanf("%d", &price);
printf("Enter deno1 deno2 deno3 (largest first): ");
scanf("%d %d %d", &deno1, &deno2, &deno3);
for (d1 = 0; d1 <= price / deno1; d1++)
for (d2 = 0; d2 <= price / deno2; d2++)
for (d3 = 0; d3 <= price / deno3; d3++)
if (d1 * deno1 + d2 * deno2 + d3 * deno3 == price) {
printf("<%d, %d, %d>\n", d1, d2, d3);
ways++;
}
if (ways > 0)
printf("Number of ways = %d\n", ways);
else
printf("Not Possible\n");
return 0;
}
Enter price: 110
Enter deno1 deno2 deno3 (largest first): 100 20 10
<0, 0, 11>
<0, 1, 9>
<0, 2, 7>
<0, 3, 5>
<0, 4, 3>
<0, 5, 1>
<1, 0, 1>
Number of ways = 7
Enter price: 25
Enter deno1 deno2 deno3 (largest first): 20 10 4
Not Possible
The second run: every note is even and 25 is odd, so no combination works.
d3 < price / deno3instead of<=: misses 0-0-11, where the bound is reached exactly. Count: 6 instead of 7.- Using
while: the template says "only for". - Forgetting the "Not Possible" branch, or printing the count inside the loop.
- Skipping the written dry run: 5 of the 16 marks.
7 · Cricket statistics with validation 2026 Sem 2 · Part B Q4 · 16 marks
Assume that in the recently concluded cricket tournament, player X has played 10 matches. Write a C program that accepts the runs scored in all 10 matches into a 1-d array, where each score must be an integer between 0 and 200. The program should validate the input and display an error message and terminate if any score falls outside the valid range. After successfully storing the scores, the program must calculate and display the total runs scored, the average runs (printed with two decimal places), the highest score, and the lowest score. It should also count and display the number of centuries scored (100 or more runs). Additionally, the program should determine the player’s consistency by checking the difference between the highest and the lowest scores: if the difference is less than or equal to 50, the player is a “Consistent Performer”; else he is an “Inconsistent Performer”. The program must not use any user-defined functions or sorting techniques, and all logic should be written inside the main function. A valid test case is as below: [16]
Input: Enter runs in 10 matches: 120 35 0 88 150 60 45 100 10 75
Output: Total Runs = 683 Average Runs = 68.30 Highest Score = 150 Lowest Score = 0 Number of Centuries = 3
Performer Status = Inconsistent Performer
Before opening: do moves 1–3 on paper
1 Ten scores → total 683, average 68.30, high 150, low 0, 3 centuries, Inconsistent (150 − 0 > 50). 2 The shell on the lesson page. 3 Validate each score as it's read; then one loop that accumulates, tracks max and min, and counts; then one comparison.
The routine, applied
- RestateSix outputs, one per sentence of the question. List them; each becomes one
printf. - Skeleton
int runs[10];,total = 0andcenturies = 0(they add up),highest,lowest,float average, a reading loop, sixprintfs. - PatternValidate-then-process (check each score in the reading loop,
return 0;on a bad one) + accumulate + max + min + count, all in one pass. - Hand table → loopStart
highestandlowestatruns[0]. Row per score: add to total; bigger than highest? replace; smaller than lowest? replace; ≥ 100? count. After the loop:average = total / 10.0. - Dry run & assumptionsSample ✓ (683, 68.30, 150, 0, 3, Inconsistent). Also run an invalid score and an all-close set, as below.
Skeleton, marked against the scheme
The scheme marks line ranges of the model answer; mapped to what those lines do:
| Part | Marks |
|---|---|
Declarations (runs[10], counters, float average) | 3 |
Reading loop with scanf | 2 |
| Validation: error message and terminate | 3 |
Initialising highest and lowest from runs[0] | 2 |
| The one loop: total, max, min, centuries | 3 |
| Final block: average, output, consistency verdict | 3 |
Full solution (compiled, no warnings)
#include <stdio.h>
int main(void) {
int runs[10];
int i, total = 0, highest, lowest, centuries = 0;
float average;
printf("Enter runs in 10 matches: ");
for (i = 0; i < 10; i++) {
scanf("%d", &runs[i]);
if (runs[i] < 0 || runs[i] > 200) {
printf("Error: runs must be between 0 and 200\n");
return 0; /* terminate */
}
}
highest = runs[0];
lowest = runs[0];
for (i = 0; i < 10; i++) {
total = total + runs[i];
if (runs[i] > highest) highest = runs[i];
if (runs[i] < lowest) lowest = runs[i];
if (runs[i] >= 100) centuries++;
}
average = total / 10.0; /* 10.0, not 10 */
printf("Total Runs = %d\n", total);
printf("Average Runs = %.2f\n", average);
printf("Highest Score = %d\n", highest);
printf("Lowest Score = %d\n", lowest);
printf("Number of Centuries = %d\n", centuries);
if (highest - lowest <= 50)
printf("Performer Status = Consistent Performer\n");
else
printf("Performer Status = Inconsistent Performer\n");
return 0;
}
Enter runs in 10 matches: 120 35 0 88 150 60 45 100 10 75
Total Runs = 683
Average Runs = 68.30
Highest Score = 150
Lowest Score = 0
Number of Centuries = 3
Performer Status = Inconsistent Performer
Enter runs in 10 matches: 120 35 250 88 150 60 45 100 10 75
Error: runs must be between 0 and 200
Enter runs in 10 matches: 60 70 55 90 80 75 65 85 88 95
Total Runs = 763
Average Runs = 76.30
Highest Score = 95
Lowest Score = 55
Number of Centuries = 0
Performer Status = Consistent Performer
average = total / 10;is integer division and prints 68.00, not 68.30. Use10.0.- Starting
lowestat 0: it never goes up, so the third run above would report 0 instead of 55. Start both atruns[0]. - Validating after the loop (or not terminating): the question says error and terminate.
- "Less than or equal to 50" is
<= 50;< 50gets the boundary wrong. - Sorting to find max/min: forbidden.
8 · Quadratic roots with a switch and no if 2026 Sem 2 · Part B Q5 · 16 marks
Write a program to determine the roots of a quadratic polynomial ax2+bx+c where a, b, and c, are integers. The program should work for both real and complex roots. For example, for the polynomial x2+4x+5, it should print the roots as -2.000000+1.000000i and -2.000000-1.000000i. The program should use a switch statement to deal with the different cases (real roots and complex roots) and should not use if conditions. [16]
Before opening: with no if allowed, what value can the switch switch on?
A comparison. In C, (disc >= 0) is an int: 1 when true, 0 when false. So switch (disc >= 0) has exactly two cases, case 1 (real) and case 0 (complex).
The routine, applied
- Restate
1 4 5 → −2 ± 1i; also make a real example by hand:1 3 2 → −1 and −2(x² + 3x + 2 = (x+1)(x+2)). - Skeleton
#include <math.h>forsqrt,int a, b, c,doublefor the roots,scanf, aprintfper case: 6 + 2 of the 16 marks. - PatternSelection without
if: computedisc = b*b − 4*a*c, thenswitch (disc >= 0). - Hand table → formulasReal:
(−b ± √disc) / (2a). Complex: real part−b / (2a), imaginary part√(−disc) / (2a). Write2.0 * aso the division is done in decimals. - Dry run & assumptions1 4 5: disc = 16 − 20 = −4 → case 0 → re = −4/2 = −2, im = √4/2 = 1 ✓. Assumption: a ≠ 0.
Unpack: why does 2.0 * a fix the division?
If both sides of / are integers, C throws away the fraction: -3 / 2 is −1, not −1.5. Making one side a double (2.0 * a) makes the whole division decimal. Assigning the result to a double afterwards is too late: the fraction is already gone.
Full solution (compiled, no warnings)
#include <stdio.h>
#include <math.h>
int main(void) {
int a, b, c, disc, real;
double r1, r2, re, im;
printf("Enter a b c (a not 0): ");
scanf("%d %d %d", &a, &b, &c);
disc = b * b - 4 * a * c;
real = (disc >= 0); /* 1 if real roots, 0 if complex */
switch (real) {
case 1:
r1 = (-b + sqrt(disc)) / (2.0 * a);
r2 = (-b - sqrt(disc)) / (2.0 * a);
printf("Roots are %f and %f\n", r1, r2);
break;
case 0:
re = -b / (2.0 * a);
im = sqrt(-disc) / (2.0 * a);
printf("Roots are %f+%fi and %f-%fi\n", re, im, re, im);
break;
}
return 0;
}
Enter a b c (a not 0): 1 4 5
Roots are -2.000000+1.000000i and -2.000000-1.000000i
Enter a b c (a not 0): 1 3 2
Roots are -1.000000 and -2.000000
Enter a b c (a not 0): 1 1 1
Roots are -0.500000+0.866025i and -0.500000-0.866025i
Enter a b c (a not 0): 2 3 1
Roots are -0.500000 and -1.000000
It computes r1 = -b/(2*a) + d/(2*a); with int a, b, so -b/(2*a) is integer division. It works on the question's example only because −4/2 happens to be whole. Compiled and run:
Enter coefficients of the polynomial1 3 2
Roots are -0.500000 and -1.500000
Enter coefficients of the polynomial1 1 1
Roots are 0.000000 + 0.866025 i and 0.000000 - 0.866025 i
The first should be −1 and −2; the second should have real part −0.5. If you learned from the model answer, this is the line to unlearn.
- Integer division in the root formulas (above).
sqrt(disc)in the complex case: the square root of a negative is "nan". Usesqrt(-disc).- Any
if, including hiding one in a helper: forbidden. - Forgetting
#include <math.h>. With gcc on Linux (very likely what the lab machines run), also compile with-lm, which links the maths library.
"Here's a C mid-sem question: [paste]. I've written move 1 (input → output) and my skeleton: [paste]. Don't give me the solution. Tell me which inputs or outputs my skeleton is missing, and which restriction in the question I haven't underlined."
"Make me a new question in the same pattern as [e.g. insert with shift] but with a twist (delete instead of insert; shift left; two positions). Give only the question and one sample input/output."
Compile anything an AI claims about output: the published keys for these past papers had output errors, and an AI can too.