C Review Problems & Final Exam Prep (with Fill-in-the-Blank)

Once you have worked through the problems for each topic, finish up here. The first half asks you to write whole programs that combine several topics; the second half is fill-in-the-blank problems in the style of a final exam. In both, press "Check" to run your code with real gcc on several inputs and see whether the output is correct.

How to use these problems
  1. Read the problem and the sample run, then write your code in the box
  2. Press "▶ Run" to try it with your own input
  3. Press "✔ Check" to test the output against several prepared inputs
  4. Stuck? Open "Hint". Solved it? Compare with "Solution & explanation"
Checking rules
  • Print output exactly as in the sample run. Do not print input prompts such as "Enter a number"
  • Trailing spaces at line ends and trailing blank lines are ignored
  • Your code is saved automatically in this browser

Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.

30 problems (Beginner 9 · Intermediate 12 · Advanced 9)

Mixed Problems (combining several topics) (21 problems)

G01 Beginner

Problem 1. Assign a class

Read a student number (an integer from 1 to 9999), decide the class by the rules below, and print it in the form "Student 25 is in class B".
• Numbers 1–20 → class A
• 21 or more and even → class A
• 21 or more and odd → class B
Sample run (input is underlined)
25 Student 25 is in class B
Your code
"Run" executes your code with the input above. "Check" tests it against 6 prepared inputs.
"1–20" can be tested with num >= 1 && num <= 20, and evenness with num % 2 == 0. There are two conditions that lead to class A, so you can combine them with || (or).
#include <stdio.h>

int main(void) {
    int num;
    scanf("%d", &num);

    if (num <= 20 || num % 2 == 0) {
        printf("Student %d is in class A\n", num);
    } else {
        printf("Student %d is in class B\n", num);
    }
    return 0;
}
Explanation: A student is in class A when the number is "20 or less" or "even", so the two can be combined into one condition with ||. Writing it step by step with else if ("20 or less → A, otherwise even → A, everything else → B") is also correct. A good testing habit is to try both sides of the boundary, 20 and 21.
G02 Beginner

Problem 2. Even/odd, quotient and remainder

Read two integers a and b (a from 0 to 10000, b from 1 to 100), print whether each one is even or odd, and then print the quotient and remainder of a ÷ b.
Sample run (input is underlined)
17 5 a is odd b is odd 17 / 5 = quotient 3, remainder 2
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Check even/odd with the remainder of % 2. The quotient is a / b (both are int, so the fractional part is truncated) and the remainder is a % b.
#include <stdio.h>

int main(void) {
    int a, b;
    scanf("%d %d", &a, &b);

    printf("a is %s\n", a % 2 == 0 ? "even" : "odd");
    printf("b is %s\n", b % 2 == 0 ? "even" : "odd");
    printf("%d / %d = quotient %d, remainder %d\n", a, b, a / b, a % b);
    return 0;
}
Explanation: condition ? value1 : value2 is the conditional (ternary) operator: it gives value1 if the condition is true and value2 if it is false. It is handy when printing a string with %s. Of course, writing two printf calls with if-else is fine too. Note that 0 is even.
G03 Beginner

Problem 3. Print weights in aligned columns

Read two weights w1 and w2 (kg, real numbers from 0 to 999) and print each weight, their total and their difference (the larger minus the smaller), right-aligned with a total width of 5 and 1 digit after the decimal point.
Sample run (input is underlined)
3.5 7.24 Weight 1 = 3.5 kg Weight 2 = 7.2 kg Total = 10.7 kg Diff = 3.7 kg
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
%5.1f means "a width of 5 characters in total, with 1 digit after the decimal point". Any missing width is filled with spaces on the left. The scanf format for reading a double is %lf.
#include <stdio.h>

int main(void) {
    double w1, w2;
    scanf("%lf %lf", &w1, &w2);

    printf("Weight 1 = %5.1f kg\n", w1);
    printf("Weight 2 = %5.1f kg\n", w2);
    printf("Total    = %5.1f kg\n", w1 + w2);
    printf("Diff     = %5.1f kg\n", w1 > w2 ? w1 - w2 : w2 - w1);
    return 0;
}
Explanation: The width (the 5 in %5.1f) counts the decimal point as one character. The difference is "larger − smaller", so the conditional operator switches the direction of the subtraction (fabs(w1 - w2) also works). Note that %.1f rounds the value as it is stored in binary, so a value exactly halfway, such as 7.25, may become 7.2 rather than 7.3.
G04 Beginner

Problem 4. Evaluate a formula with three variables

Read real numbers x, y and z (each from −100 to 100) and print the value of f(x, y, z) = x² + 2xy + y²z with %f.
Sample run (input is underlined)
1.2 2.2 1.5 f(x,y,z) = 13.980000
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
C has no "square" operator, so write x² as x * x. Write 2xy as 2 * x * y, without leaving out any *.
#include <stdio.h>

int main(void) {
    double x, y, z;
    scanf("%lf %lf %lf", &x, &y, &z);

    double f = x * x + 2 * x * y + y * y * z;
    printf("f(x,y,z) = %f\n", f);
    return 0;
}
Explanation: When copying a math formula, it is easy to leave out the multiplication sign as in 2xy, but C always needs *. pow(x, 2) also computes a square, but for squaring, x * x is simpler and faster and does not need math.h. %f prints 6 digits after the decimal point.
G05 Beginner

Problem 5. A function that prints a smiley

Write a function void disp_face(void) that prints (^_^) each time it is called. The main function reads an integer n (from 0 to 20), calls disp_face n times, and then prints a newline.
Sample run (input is underlined)
3 (^_^)(^_^)(^_^)
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
A function with no parameters and no return value is written as void name(void) { ... }. If you define it before main, you can call it without a prototype.
#include <stdio.h>

void disp_face(void) {
    printf("(^_^)");
}

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        disp_face();
    }

    printf("\n");
    return 0;
}
Explanation: Turning work you use repeatedly into a function lets you do it with a one-line call. The function does not print a newline, so calling it several times puts the faces on the same line. When n is 0 the loop never runs and only the newline is printed.
G06 Beginner

Problem 6. Area of a rectangle (prototype)

Define a function int area_rectangle(int h, int w) that returns the area of a rectangle after the main function (write a prototype before main). main reads the height h and width w (from 1 to 1000) and prints the area using the function's return value.
Sample run (input is underlined)
5 8 The area is 40
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
A prototype is the first line of the function (return type, name and parameters) followed by ;: int area_rectangle(int h, int w);
#include <stdio.h>

int area_rectangle(int h, int w); // prototype

int main(void) {
    int h, w;
    scanf("%d %d", &h, &w);

    printf("The area is %d\n", area_rectangle(h, w));
    return 0;
}

int area_rectangle(int h, int w) {
    return h * w;
}
Explanation: The compiler reads the file from top to bottom, so to call a function defined after main from main, you must first announce "this function exists" with a prototype. If the function only computes the area and returns it, leaving the printing to main, it becomes a function you can reuse in other situations.
G07 Beginner

Problem 7. Function-like macros and parentheses

Correctly define a macro SQUARE(x) that computes a square and a macro MAX(a, b) that gives the larger value. The SQUARE in the template gives a wrong result as it is, so fix it. For MAX, rewrite the part that is 0. main reads integers a and b (from −100 to 100) and prints the values of SQUARE(a + 1) and MAX(a, b).
Sample run (input is underlined)
3 5 SQUARE(a + 1) = 16 MAX(a, b) = 5
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
A macro is text replacement. With #define SQUARE(x) x * x, SQUARE(a + 1) is replaced by a + 1 * a + 1. Put parentheses around each parameter and around the whole expression.
#include <stdio.h>

#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main(void) {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("SQUARE(a + 1) = %d\n", SQUARE(a + 1));
    printf("MAX(a, b) = %d\n", MAX(a, b));
    return 0;
}
Explanation: A #define macro is replaced as plain text before compilation. Without parentheses, SQUARE(a + 1) becomes a + 1 * a + 1 (7 when a = 3), not the expected 16. The golden rule for function-like macros is to parenthesize "each parameter" and "the whole expression".
G08 Beginner

Problem 8. An int function and a double function

Write the following two functions.
• void add(int a, int b): prints the sum in the form "12 + 25 = 37"
• void max3(double a, double b, double c): prints the maximum in the form "max(23.5, 69.2, 10.3) = 69.2" (1 digit after the decimal point)
main reads two integers and three real numbers and calls each function.
Sample run (input is underlined)
12 25 23.5 69.2 10.3 12 + 25 = 37 max(23.5, 69.2, 10.3) = 69.2
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
In max3, start with double m = a; and replace m whenever b or c is larger. Print a double with %.1f.
#include <stdio.h>

void add(int a, int b) {
    printf("%d + %d = %d\n", a, b, a + b);
}

void max3(double a, double b, double c) {
    double m = a;
    if (b > m) m = b;
    if (c > m) m = c;
    printf("max(%.1f, %.1f, %.1f) = %.1f\n", a, b, c, m);
}

int main(void) {
    int x, y;
    double a, b, c;
    scanf("%d %d", &x, &y);
    scanf("%lf %lf %lf", &a, &b, &c);

    add(x, y);
    max3(a, b, c);
    return 0;
}
Explanation: Choose the parameter types to match the values you pass. The pattern "pick a provisional maximum and replace it when something larger comes along" works the same way however many values there are. Naming the function max can clash with a standard library or macro name in some environments, so a specific name like max3 is safer.
G09 Intermediate

Problem 9. Draw a frame with diagonals

Read a width w and height h (both from 3 to 20). Draw the border with *; inside it, print + on the two diagonals (where row i and column j satisfy i == j or i + j == w - 1, both counted from 0) and a space everywhere else.
Sample run (input is underlined)
7 5 ******* *+ +* * + + * * + * *******
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Use a double loop to visit every cell, row i (0 to h−1) and column j (0 to w−1). First check "is it on the border?" (i == 0 || i == h - 1 || j == 0 || j == w - 1), and if not, check "is it on a diagonal?". The order of the ifs matters.
#include <stdio.h>

int main(void) {
    int w, h;
    scanf("%d %d", &w, &h);

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            if (i == 0 || i == h - 1 || j == 0 || j == w - 1)
                printf("*");
            else if (i == j || i + j == w - 1)
                printf("+");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}
Explanation: The basic approach to drawing shapes is to decide, with conditions, what to print in each cell (i, j). Because the border check comes first, cells where a diagonal meets the border become *. Trailing spaces are ignored when checking, but in this program every line ends with * anyway, so you do not need to worry about them.
G10 Intermediate

Problem 10. Draw a grid (global variables and functions)

Read a width w, height h, horizontal interval hi and vertical interval vi (w and h from 3 to 30, hi and vi from 1 to 10). Draw the border with #; inside it, print + in cells whose "row number is a multiple of vi and column number is a multiple of hi", and - everywhere else. Store the intervals in global variables and draw with a function void grid(int w, int h) (use a prototype).
Sample run (input is underlined)
10 7 3 2 ########## #--------# #--+--+--# #--------# #--+--+--# #--------# ##########
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
As in G09, check the border first. For an inner cell, print + when i % v_interval == 0 && j % h_interval == 0. The global variables are declared outside any function, so grid can use them directly.
#include <stdio.h>

void grid(int w, int h);
int h_interval, v_interval;  // horizontal and vertical intervals

int main(void) {
    int w, h;
    scanf("%d %d %d %d", &w, &h, &h_interval, &v_interval);
    grid(w, h);
    return 0;
}

void grid(int w, int h) {
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            if (i == 0 || i == h - 1 || j == 0 || j == w - 1)
                printf("#");
            else if (i % v_interval == 0 && j % h_interval == 0)
                printf("+");
            else
                printf("-");
        }
        printf("\n");
    }
}
Explanation: Global variables can be read and written from any function, so grid can use the intervals without receiving them as arguments. However, it becomes harder to track where a value was changed, so in real programs passing values as arguments is often clearer. Here the goal is to practice using global variables and prototypes.
G11 Intermediate

Problem 11. A function that draws a bar chart

Read the number of items n (from 1 to 10) and the sales of each item (from 0 to 40), and draw a bar for each item with a function void draw_graph(int id, int sales). Print as many symbols as the sales count, using = for every 5th one (the tick interval is the global variable interval) and * otherwise. Print the sales count with a width of 2.
Sample run (input is underlined)
3 12 8 20 Item 1 (12): ****=****=** Item 2 ( 8): ****=*** Item 3 (20): ****=****=****=****=
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
If you count j from 1, as in for (int j = 1; j <= sales; j++), then "every 5th" is simply j % interval == 0. Use %2d to print the sales count with a width of 2.
#include <stdio.h>

void draw_graph(int id, int sales);
int interval = 5;  // tick interval

int main(void) {
    int n, data[10];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &data[i]);

    for (int i = 0; i < n; i++)
        draw_graph(i + 1, data[i]);
    return 0;
}

void draw_graph(int id, int sales) {
    printf("Item %d (%2d): ", id, sales);
    for (int j = 1; j <= sales; j++) {
        if (j % interval == 0)
            printf("=");
        else
            printf("*");
    }
    printf("\n");
}
Explanation: If the loop variable starts at 0, the "5th" symbol is j == 4, and the condition becomes the less obvious (j + 1) % interval == 0. Starting at 1 to match what you are counting is a perfectly good technique. When the sales count is 0, the loop does not run and only the label is printed.
G12 Intermediate

Problem 12. A menu-driven calculator (global variables)

Using global variables val (initially 0) and n, write the following menu-driven calculator.
• Read a menu number. If it is 1, read one integer into n and add n to val. If it is 2, likewise multiply val by n. In both cases, print "val is now 10" after the calculation
• If it is -1, print "Exiting (val = 30)" and finish
• For any other number, do nothing and read the next menu number
The input values and results fit in an int.
Sample run (input is underlined)
1 10 2 3 -1 val is now 10 val is now 30 Exiting (val = 30)
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
Repeat with while (1), and after reading the menu number, branch with switch. For -1 you need to leave the loop, not just break out of the switch, so either use while (sw != -1) or check for -1 with an if first and break.
#include <stdio.h>

int val = 0;
int n;

void input(void)    { scanf("%d", &n); }
void display(void)  { printf("val is now %d\n", val); }
void addition(void) { val += n; }
void product(void)  { val *= n; }

int main(void) {
    int sw = 0;

    while (1) {
        scanf("%d", &sw);
        if (sw == -1) break;
        switch (sw) {
        case 1: input(); addition(); display(); break;
        case 2: input(); product();  display(); break;
        }
    }
    printf("Exiting (val = %d)\n", val);
    return 0;
}
Explanation: A break inside a switch only "leaves the switch"; it does not leave the enclosing while. That is why the exit check is done outside the switch. Splitting the work into small functions such as input, addition and display means main only has to describe the flow of the menu, which makes it easier to read.
G13 Intermediate

Problem 13. Return the sum and average through pointers

Write a function void calc(int *arr, int n, int *sum, double *avg) that computes both the sum and the average of an array. main reads a count n (from 1 to 100) and n integers (from −1000 to 1000), calls calc, and prints the sum and the average (1 digit after the decimal point).
Sample run (input is underlined)
5 10 20 30 40 50 Sum: 150 Average: 30.0
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
return can send back only one value, so the other results are written to the locations received as pointers. Initialize the sum with *sum = 0; and add with *sum += arr[i];. The average is (double)*sum / n.
#include <stdio.h>

void calc(int *arr, int n, int *sum, double *avg) {
    *sum = 0;
    for (int i = 0; i < n; i++) {
        *sum += arr[i];
    }
    *avg = (double)*sum / n;
}

int main(void) {
    int n, data[100];
    int sum;
    double avg;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &data[i]);

    calc(data, n, &sum, &avg);
    printf("Sum: %d\n", sum);
    printf("Average: %.1f\n", avg);
    return 0;
}
Explanation: By passing the addresses of variables, as in calc(data, n, &sum, &avg), the function can modify main's variables. This is the standard way to "return several results". Without (double), *sum / n is an integer division and the fractional part is truncated.
G14 Intermediate

Problem 14. Distance between two points (struct and function)

Using a structure struct Point for coordinates (members double x, y), write a function double distance(struct Point p1, struct Point p2) that returns the distance between two points. main reads the coordinates of two points x1 y1 x2 y2 (each from −1000 to 1000) and prints the distance with 3 digits after the decimal point.
Sample run (input is underlined)
0 0 3 4 Distance: 5.000
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
The distance is √((x2−x1)² + (y2−y1)²). Compute the square root with sqrt from math.h. Access members with a dot, as in p1.x.
#include <stdio.h>
#include <math.h>

struct Point {
    double x, y;
};

double distance(struct Point p1, struct Point p2) {
    double dx = p2.x - p1.x;
    double dy = p2.y - p1.y;
    return sqrt(dx * dx + dy * dy);
}

int main(void) {
    struct Point p1, p2;
    scanf("%lf %lf %lf %lf", &p1.x, &p1.y, &p2.x, &p2.y);
    printf("Distance: %.3f\n", distance(p1, p2));
    return 0;
}
Explanation: A structure lets you pass "a pair of x and y" to a function as a single value. The arguments are passed by value, so changing p1 inside the function does not change main's p1. Storing the differences in dx and dy before squaring makes the expression shorter and less error-prone. When compiling on your own machine, you may need the -lm option.
G15 Intermediate

Problem 15. Capitalize the first letter of each word

Read one line (up to 100 characters) consisting of lowercase letters and spaces, and print it with the first letter of each word capitalized. Then print the number of words on the next line. Words are separated by one or more spaces (there may be spaces at the start or end of the line). Do the conversion in a function int capitalize(char *s) that returns the number of words.
Sample run (input is underlined)
the quick brown fox The Quick Brown Fox Words: 4
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
A word starts where "the previous character is a space (or it is the start of the string) and the current character is not a space". Go through the string one character at a time while remembering whether the previous character was a space in a variable int prev_space = 1;. To turn a lowercase letter into uppercase, use c - 'a' + 'A' (or toupper from ctype.h).
#include <stdio.h>
#include <string.h>

int capitalize(char *s) {
    int count = 0;
    int prev_space = 1;  // was the previous char a space (or the start)?
    for (char *p = s; *p != '\0'; p++) {
        if (*p == ' ') {
            prev_space = 1;
        } else {
            if (prev_space) {
                if (*p >= 'a' && *p <= 'z') *p = *p - 'a' + 'A';
                count++;
            }
            prev_space = 0;
        }
    }
    return count;
}

int main(void) {
    char s[128];
    if (fgets(s, sizeof s, stdin) == NULL) s[0] = '\0';
    s[strcspn(s, "\n")] = '\0';

    int words = capitalize(s);
    printf("%s\n", s);
    printf("Words: %d\n", words);
    return 0;
}
Explanation: A variable (a flag) that "remembers the state of the previous character" lets you correctly handle consecutive spaces and spaces at the start or end of the line all at once. The function receives the address of the first element of the array, so changes made with *p = ... show up directly in main's s. The conversion (rewriting characters) and the counting (the return value) are done together in a single loop.
G16 Advanced

Problem 16. Decide the result of tic-tac-toe

Read a tic-tac-toe board as 3 lines and decide the result. Each line has 3 characters, each o, x or . (empty). If the same symbol appears three in a row vertically, horizontally or diagonally, print "o wins" or "x wins"; if there is no line of three and no empty cell, print "Draw"; if there are empty cells, print "In progress". Boards where both players have three in a row are not given. Decide the winner with a function char winner(char b[3][4]) (returns the winner's symbol, or '.' if there is none).
Sample run (input is underlined)
oxo xoo xxo o wins
Your code
"Run" executes your code with the input above. "Check" tests it against 7 prepared inputs.
Check the 8 lines (3 rows, 3 columns, 2 diagonals). For each line, if "all 3 cells are the same" and "not empty", that symbol is the winner. Inside for (int i = 0; i < 3; i++) you can check b[i][0], b[i][1], b[i][2] (row) and b[0][i], b[1][i], b[2][i] (column) at the same time.
#include <stdio.h>

char winner(char b[3][4]) {
    for (int i = 0; i < 3; i++) {
        if (b[i][0] != '.' && b[i][0] == b[i][1] && b[i][1] == b[i][2]) return b[i][0];  // row
        if (b[0][i] != '.' && b[0][i] == b[1][i] && b[1][i] == b[2][i]) return b[0][i];  // column
    }
    if (b[1][1] != '.' && b[0][0] == b[1][1] && b[1][1] == b[2][2]) return b[1][1];  // diagonals
    if (b[1][1] != '.' && b[0][2] == b[1][1] && b[1][1] == b[2][0]) return b[1][1];
    return '.';
}

int main(void) {
    char b[3][4];  // 3 chars per row + '\0'
    for (int i = 0; i < 3; i++) scanf("%3s", b[i]);

    char w = winner(b);
    if (w != '.') {
        printf("%c wins\n", w);
    } else {
        int empty = 0;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                if (b[i][j] == '.') empty++;
        printf("%s\n", empty > 0 ? "In progress" : "Draw");
    }
    return 0;
}
Explanation: When passing a 2D array to a function, you must write the number of columns (the second size), as in char b[3][4]. Each row is read as a string, so the column size is the 3 characters plus one for '\0', i.e. 4. Checking only "all 3 cells are the same" would also count a line of three empty cells as a win, so do not forget the != '.' check.
G17 Advanced

Problem 17. Difference from the average (malloc)

Read a count n (from 1 to 100000) and n integers (from −10000 to 10000) into an array allocated with malloc. Print the average with 2 digits after the decimal point, then print each value and its difference from the average, one per line, in the form "value (difference)". Print the difference with a sign and 2 digits after the decimal point (%+.2f). Call free at the end.
Sample run (input is underlined)
4 10 20 30 41 Average: 25.25 10 (-15.25) 20 (-5.25) 30 (+4.75) 41 (+15.75)
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
int *data = malloc(sizeof(int) * n); allocates room for n ints, which you can then use just like an ordinary array with data[i]. The average is not known until everything has been read, so split the work into two loops (read and sum / print).
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n;
    scanf("%d", &n);

    int *data = malloc(sizeof(int) * n);
    if (data == NULL) {
        printf("Cannot allocate memory\n");
        return 1;
    }

    long long sum = 0;
    for (int i = 0; i < n; i++) {
        scanf("%d", &data[i]);
        sum += data[i];
    }
    double avg = (double)sum / n;

    printf("Average: %.2f\n", avg);
    for (int i = 0; i < n; i++) {
        printf("%d (%+.2f)\n", data[i], data[i] - avg);
    }

    free(data);
    return 0;
}
Explanation: When the number of elements is not known until the program runs, allocate exactly as much memory as you need with malloc. It returns NULL if the allocation fails, so check for that, and give the memory back with free when you are done. The sum can be as large as 10000 × 100000 = 1 billion, which just fits in an int, but long long is used here to leave some margin. The + in %+.2f means "show a + sign on positive numbers too".
G18 Advanced

Problem 18. Write scores to a file and read them back

Read the number of people n (from 1 to 20) and, for each person, "a name (letters only, up to 19 characters) and a score (from 0 to 100)", and write them to the file scores.txt, one person per line as "name score". After writing, close the file once, open it again, read it, and print its contents along with the total and the average (1 digit after the decimal point).
Sample run (input is underlined)
3 Taro 80 Hanako 95 Jiro 70 --- scores.txt --- Taro 80 Hanako 95 Jiro 70 Total: 245 Average: 81.7
Your code
"Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
To write, use fopen("scores.txt", "w") and fprintf(fp, "%s %d\n", ...); to read, use fopen("scores.txt", "r") and fscanf. while (fscanf(fp, "%19s %d", name, &score) == 2) repeats "only while both items were read". Also check that fopen did not return NULL.
#include <stdio.h>

int main(void) {
    int n;
    char name[20];
    int score;
    scanf("%d", &n);

    FILE *fp = fopen("scores.txt", "w");
    if (fp == NULL) {
        printf("Cannot open the file\n");
        return 1;
    }
    for (int i = 0; i < n; i++) {
        scanf("%19s %d", name, &score);
        fprintf(fp, "%s %d\n", name, score);
    }
    fclose(fp);

    fp = fopen("scores.txt", "r");
    if (fp == NULL) {
        printf("Cannot open the file\n");
        return 1;
    }
    printf("--- scores.txt ---\n");
    int sum = 0, count = 0;
    while (fscanf(fp, "%19s %d", name, &score) == 2) {
        printf("%s %d\n", name, score);
        sum += score;
        count++;
    }
    fclose(fp);

    printf("Total: %d\n", sum);
    printf("Average: %.1f\n", (double)sum / count);
    return 0;
}
Explanation: Data you write may stay buffered in memory until you call fclose. Closing and reopening the file guarantees that you read what was actually written to it. The return value of fscanf is "the number of items read", so comparing it with == 2 stops at the end of the file (EOF) or at a badly formatted line. The 19 in %19s is the maximum number of characters: the array size 20 minus one for '\0'.
G19 Advanced

Problem 19. Sort in ascending or descending order

Read a count n (from 1 to 100), n integers, and a letter for the order, A (ascending) or D (descending), and print the sorted result separated by commas. Implement the sorting in a function void sort(int a[], int n, int ascending) using selection sort: ascending order if ascending is 1, descending order if it is 0.
Sample run (input is underlined)
5 10 32 8 42 13 D Descending: 42, 32, 13, 10, 8
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Selection sort repeats "find the smallest (the largest, for descending) element from position i onward and swap it with position i". If you switch the comparison as in ascending ? (a[j] < a[best]) : (a[j] > a[best]), one function handles both orders.
#include <stdio.h>

void sort(int a[], int n, int ascending) {
    for (int i = 0; i < n - 1; i++) {
        int best = i;
        for (int j = i + 1; j < n; j++) {
            if (ascending ? (a[j] < a[best]) : (a[j] > a[best])) best = j;
        }
        int tmp = a[i];
        a[i] = a[best];
        a[best] = tmp;
    }
}

int main(void) {
    int n, a[100];
    char order;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    scanf(" %c", &order);

    int asc = (order == 'A');
    sort(a, n, asc);
    printf("%s: ", asc ? "Ascending" : "Descending");
    for (int i = 0; i < n; i++) {
        printf("%d", a[i]);
        if (i < n - 1) printf(", ");
    }
    printf("\n");
    return 0;
}
Explanation: Passing an array to a function passes the address of its first element, so the result sorted inside the function stays in main's array. The space at the start of the scanf(" %c", ...) format skips the newline left over after the previous number. Without it, order would receive the newline character. The comma is printed only "after every element except the last".
G20 Advanced

Problem 20. A Reverse Polish Notation calculator

Evaluate an expression in Reverse Polish Notation (a notation where operators are written after the numbers). The expression is a sequence of space-separated tokens; each token is an integer from 0 to 1000 or one of the operators + - * / (/ is integer division). There are at most 50 tokens. Print the result. If the expression is invalid (too few or too many numbers) or it tries to divide by 0, print "Error". Example: 3 4 + 2 * is (3 + 4) × 2 = 14. All intermediate values and the result fit in an int.
Sample run (input is underlined)
3 4 + 2 * 14
Your code
"Run" executes your code with the input above. "Check" tests it against 8 prepared inputs.
Build a stack (a container where the last item pushed is the first taken out) from an array and an index top. For a number, push it (stack[top++] = atoi(tok);); for an operator, pop two values (the one popped first is the right operand), compute, and push the result. If exactly one value remains on the stack at the end, that is the answer.
#include <stdio.h>
#include <stdlib.h>

int stack[50];
int top = 0;  // number of items on the stack

int main(void) {
    char tok[16];
    while (scanf("%15s", tok) == 1) {
        char c = tok[0];
        if (tok[1] == '\0' && (c == '+' || c == '-' || c == '*' || c == '/')) {
            if (top < 2) { printf("Error\n"); return 0; }
            int b = stack[--top];  // right operand
            int a = stack[--top];  // left operand
            int r;
            switch (c) {
            case '+': r = a + b; break;
            case '-': r = a - b; break;
            case '*': r = a * b; break;
            default:
                if (b == 0) { printf("Error\n"); return 0; }
                r = a / b;
                break;
            }
            stack[top++] = r;
        } else {
            stack[top++] = atoi(tok);
        }
    }

    if (top != 1) printf("Error\n");
    else printf("%d\n", stack[0]);
    return 0;
}
Explanation: Reverse Polish Notation expresses the order of evaluation without parentheses, so it is used inside calculators and compilers. To pop, use stack[--top] (decrement top first, then read); to push, use stack[top++] = value (write, then increment top). Order matters for subtraction and division: 7 2 / means 7 ÷ 2, so the 2 popped first is the right operand.
G21 Advanced

Problem 21. Search a member list (struct, strings, functions)

Read the number of members n (from 1 to 50) and, for each member, "a member number (integer), a name (letters, up to 19 characters) and an age", into an array of structures. Then read one name to search for and print every member with that name in the form "No.102 Hanako (age 20)". If there are none, print "Not found". On the last line, print the average age of all members except those with the searched name, with 1 digit after the decimal point (if no one is left, print "Average age: -"). Do the search with a function int find(struct Member m[], int n, const char *name, int found[]) (it stores the indices found in found and returns how many there are).
Sample run (input is underlined)
4 101 Taro 19 102 Hanako 20 103 Jiro 22 104 Hanako 31 Hanako No.102 Hanako (age 20) No.104 Hanako (age 31) Average age: 20.5
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
Check whether two strings are equal with strcmp(a, b) == 0, not ==. In find, record the index each time you find a match with found[count++] = i;. The average age is "the total of everyone − the total of those found" divided by "n − the count".
#include <stdio.h>
#include <string.h>

struct Member {
    int no;
    char name[20];
    int age;
};

int find(struct Member m[], int n, const char *name, int found[]) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        if (strcmp(m[i].name, name) == 0) {
            found[count++] = i;
        }
    }
    return count;
}

int main(void) {
    struct Member m[50];
    int n, found[50];
    char key[20];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d %19s %d", &m[i].no, m[i].name, &m[i].age);
    scanf("%19s", key);

    int k = find(m, n, key, found);
    if (k == 0) {
        printf("Not found\n");
    }
    int total = 0;
    for (int i = 0; i < n; i++) total += m[i].age;
    for (int j = 0; j < k; j++) {
        struct Member *p = &m[found[j]];
        printf("No.%d %s (age %d)\n", p->no, p->name, p->age);
        total -= p->age;
    }
    if (n - k == 0) printf("Average age: -\n");
    else printf("Average age: %.1f\n", (double)total / (n - k));
    return 0;
}
Explanation: If you record the indices in found rather than copies of the elements, you can later refer to all of the original data (member number, age and so on). Making a pointer to the structure, as in struct Member *p = &m[found[j]];, lets you write the shorter p->name. strcmp is case-sensitive, so "ann" and "Ann" are treated as different names.

Fill-in-the-Blank Problems (final exam prep) (9 problems)

Here you fill in the blanks of a whole program, then run it and are graded on its output. For short-answer blanks (keywords, format specifiers, and so on), see C Fill-in Exam Prep (45 questions).

K01 Beginner

Problem 22. Vowel or consonant (fill in the blanks)

Fill in 【①】–【③】 to complete a program that reads one lowercase letter and prints "'e' is a vowel" if it is a vowel (a, e, i, o, u), or "'k' is a consonant" otherwise.
Sample run (input is underlined)
e 'e' is a vowel
Your code
"Run" executes your code with the input above. "Check" tests it against 6 prepared inputs.
①: scanf takes the address of the variable. ②: Which vowel is still missing? ③: What do you print when it is not a vowel?
#include <stdio.h>

int main(void) {
    char c;
    scanf("%c", &c);

    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
        printf("'%c' is a vowel\n", c);
    } else {
        printf("'%c' is a consonant\n", c);
    }
    return 0;
}
Explanation: ① &c: even for a char variable, scanf takes its address. ② c == 'o': you cannot abbreviate it as c == 'a' || 'o'; write each comparison separately and join them with ||. ③ consonant.
K02 Intermediate

Problem 23. A four-operation calculator (fill in the blanks)

Read the number of an operation (1: addition, 2: subtraction, 3: multiplication, 4: division); if it is not 1–4, print "Please choose 1-4" and read it again. Then read real numbers x and y and print the result of the chosen operation (for division, y is not 0). Fill in 【①】–【④】 to complete the program.
Sample run (input is underlined)
7 4 21 4 Please choose 1-4 x / y = 5.250000
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
①: Repeat while it is less than 1 or greater than 4. ②: What is the format for reading a double? ③: Which value do you branch on? ④: The division expression.
#include <stdio.h>

int main(void) {
    int sw;
    double x, y;

    scanf("%d", &sw);
    while (sw < 1 || sw > 4) {
        printf("Please choose 1-4\n");
        scanf("%d", &sw);
    }
    scanf("%lf", &x);
    scanf("%lf", &y);

    switch (sw) {
    case 1: printf("x + y = %f\n", x + y); break;
    case 2: printf("x - y = %f\n", x - y); break;
    case 3: printf("x * y = %f\n", x * y); break;
    case 4: printf("x / y = %f\n", x / y); break;
    }
    return 0;
}
Explanation: ① sw < 1 || sw > 4: "out of range" is two conditions joined by or (with && no number satisfies both at once, so the loop would never repeat). ② %lf: use %lf to read a double with scanf; printf can print it with %f. ③ sw. ④ x / y: x and y are doubles, so this is a division with a fractional result.
K03 Intermediate

Problem 24. Compare string lengths (fill in the blanks)

Fill in 【①】–【④】 in a program that finds the lengths of two strings (letters, up to 100 characters) with a hand-written function length and compares them.
Sample run (input is underlined)
orange apple orange has 6 characters apple has 5 characters Total: 11 characters orange is longer
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
①: How do you write a parameter that receives an array? (Inside the function it is used under the name str.) ②: What character is at the end of every C string? ③: Return the number of characters counted. ④: Add the two lengths.
#include <stdio.h>
#define MAX 101

int length(char str[]) {
    int len = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        len++;
    }
    return len;
}

int main(void) {
    char s1[MAX], s2[MAX];
    scanf("%100s", s1);
    scanf("%100s", s2);

    int len1 = length(s1), len2 = length(s2);
    printf("%s has %d characters\n", s1, len1);
    printf("%s has %d characters\n", s2, len2);
    printf("Total: %d characters\n", len1 + len2);

    if (len1 > len2) printf("%s is longer\n", s1);
    else if (len2 > len1) printf("%s is longer\n", s2);
    else printf("Same length\n");
    return 0;
}
Explanation: ① str[] (*str means the same): an array parameter is actually received as the address of its first element. ② '\0': the null character that marks the end of a string. Counting until it appears is exactly how strlen works. ③ len. ④ len1 + len2.
K04 Advanced

Problem 25. Count dice (fill in the blanks)

Fill in 【①】–【④】 in a program that reads a random seed and a count n (from 1 to 100000), rolls a die n times, and prints how many times each face came up and its percentage (1 digit after the decimal point). So that the results are the same every time it is checked, the program uses the provided function my_rand() (which returns 0–32767) instead of the standard rand.
Sample run (input is underlined)
1 1000 Face 1: 157 (15.7%) Face 2: 177 (17.7%) Face 3: 157 (15.7%) Face 4: 161 (16.1%) Face 5: 165 (16.5%) Face 6: 183 (18.3%)
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
①: Repeat n times. ②: To get the 6 values 0–5, take the remainder of dividing by what? ③: Increase by 1 the element of count that corresponds to the rolled face die. ④: Convert each face's count to double before dividing.
#include <stdio.h>

unsigned int next = 1;
int my_rand(void) {           // returns a random number from 0 to 32767
    next = next * 1103515245u + 12345u;
    return (int)(next / 65536u % 32768u);
}

int main(void) {
    int n, count[6] = {0};
    scanf("%u %d", &next, &n);

    for (int i = 0; i < n; i++) {
        int die = my_rand() % 6;  // 0 to 5
        count[die]++;
    }

    for (int i = 0; i < 6; i++) {
        printf("Face %d: %d (%.1f%%)\n",
               i + 1, count[i], (double)count[i] / n * 100);
    }
    return 0;
}
Explanation: ① n. ② 6: the result of % 6 is 0–5, so it can be used directly as an index into the count array (add 1 when printing). ③ count[die]++: instead of writing six ifs, you can count with an array index in one step. ④ count[i]: without (double) this is an integer division and the percentages come out as almost 0. %% is how you print the % sign itself. my_rand uses a well-known formula from a sample implementation of rand; overflow of unsigned int is defined to wrap around "modulo 2³²", so it produces the same sequence of random numbers on every system.
K05 Advanced

Problem 26. Pseudo-random numbers by the linear congruential method (fill in the blanks)

Generate 100 pseudo-random numbers with the linear congruential method xn+1 = (a × xn + b) mod m (a = 717, b = 23, m = 65536), convert each to a real number from 0 up to (but not including) 1 with y = x / m, and print them 10 per line. Finally, print the average and the proportion of values that are at least 0.2 and less than 0.4. The initial value x is read from input (from 0 to 65535). Fill in 【①】–【⑥】.
Sample run (input is underlined)
1234 0.501 0.211 0.636 0.298 0.626 0.530 0.119 0.238 0.782 0.955 0.923 0.543 0.112 0.315 0.813 0.165 0.005 0.687 0.807 0.307 0.102 0.401 0.168 0.423 0.294 0.033 0.413 0.216 0.722 0.412 0.308 0.638 0.775 0.616 0.867 0.894 0.095 0.974 0.358 0.436 0.572 0.063 0.294 0.967 0.347 0.712 0.443 0.440 0.810 0.998 0.819 0.059 0.603 0.251 0.688 0.277 0.615 0.047 0.566 0.796 0.988 0.215 0.218 0.571 0.111 0.834 0.661 0.803 0.627 0.230 0.159 0.946 0.424 0.984 0.228 0.704 0.644 0.921 0.635 0.029 0.678 0.122 0.393 0.124 0.166 0.913 0.770 0.444 0.998 0.873 0.281 0.689 0.316 0.831 0.692 0.815 0.510 0.863 0.017 0.024 The average is 0.505 Proportion of values from 0.2 to under 0.4: 0.200
Your code
"Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
①: The condition for repeating 100 times. ②: The a × x + b part of the recurrence. ③: What you add to the sum is the converted value. ④: At least 0.2 and less than 0.4. ⑤: Start a new line after every 10 values (when i is 9, 19, 29, …). ⑥: Proportion = count ÷ total number.
#include <stdio.h>

int main(void) {
    int m = 65536, a = 717, b = 23, x;
    int i, count = 0;
    double y, sum = 0.0;
    scanf("%d", &x);

    for (i = 0; i < 100; i++) {
        x = (a * x + b) % m;
        y = (double)x / m;
        sum += y;

        if (y >= 0.2 && y < 0.4) {
            count++;
        }

        printf("%.3f ", y);
        if (i % 10 == 9) {
            printf("\n");
        }
    }
    printf("The average is %.3f\n", sum / i);
    printf("Proportion of values from 0.2 to under 0.4: %.3f\n", (double)count / i);
    return 0;
}
Explanation: ① i < 100. ② a * x + b: x is at most 65535, so even 717 × 65535 + 23 fits in an int. ③ y. ④ y >= 0.2 && y < 0.4: if you write the math expression "0.2 ≤ y < 0.4" as 0.2 <= y < 0.4, C does not do what you intend. ⑤ i % 10 == 9: i counts from 0, so the 10th value is at i = 9. ⑥ count / i: when the loop ends, i is 100. The (double) in front applies to count, so the division has a fractional result.
K06 Intermediate

Problem 27. Copy an array in reverse (fill in the blanks)

Fill in 【①】 and 【②】 in a program that reads a count n (from 1 to 10) and n integers, copies the elements of array a into array b in reverse order, and prints them.
Sample run (input is underlined)
5 1 2 3 4 5 5 4 3 2 1
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
①: When i = 0 it is the last element (index n − 1), when i = 1 it is n − 2, and so on. ②: The number of elements to pass to the function.
#include <stdio.h>

void reverse_copy(int src[], int dst[], int n) {
    for (int i = 0; i < n; i++) {
        dst[i] = src[n - 1 - i];
    }
}

int main(void) {
    int a[10], b[10], n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);

    reverse_copy(a, b, n);
    for (int i = 0; i < n; i++) printf("%d ", b[i]);
    printf("\n");
    return 0;
}
Explanation: ① n - 1 - i: the last index is n − 1, so use an expression that decreases n − 1, n − 2, … as i increases. With n - i, when i = 0 you would read src[n], which is out of bounds. ② n: passing an array to a function does not pass its number of elements, so pass it as a separate argument.
K07 Intermediate

Problem 28. Matrix multiplication (fill in the blanks)

Fill in 【①】 and 【②】 in a program that reads 2×2 matrices A and B (each element an integer from −100 to 100), computes the product C = AB, and prints it.
Sample run (input is underlined)
1 2 3 4 5 6 7 8 19 22 43 50
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
The (i, j) element of a matrix product is the sum of the products of corresponding elements of "row i of A" and "column j of B": C[i][j] = Σk A[i][k] × B[k][j].
#include <stdio.h>
#define N 2

int main(void) {
    int A[N][N], B[N][N], C[N][N] = {0};
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) scanf("%d", &A[i][j]);
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) scanf("%d", &B[i][j]);

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < N; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }

    for (int i = 0; i < N; i++) {
        printf("%d %d\n", C[i][0], C[i][1]);
    }
    return 0;
}
Explanation: ① N. ② A[i][k] * B[k][j]: k steps through "the columns of A" and "the rows of B" at the same time. C is initialized to all zeros with = {0}, so you can accumulate into it with +=. If you forget the initialization, C starts out holding garbage values and the result is wrong.
K08 Intermediate

Problem 29. Double an array through a pointer (fill in the blanks)

Fill in 【①】 and 【②】 in a program that reads a count n (from 1 to 10) and n integers, doubles each element of the array with the function double_array, and prints them.
Sample run (input is underlined)
4 3 7 1 9 6 14 2 18
Your code
"Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
①: What is the type of a parameter that receives the address of the first element of an int array? ②: There are two ways to access the i-th element through the pointer arr.
#include <stdio.h>

void double_array(int *arr, int n) {
    for (int i = 0; i < n; i++) {
        arr[i] *= 2;
    }
}

int main(void) {
    int data[10], n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &data[i]);

    double_array(data, n);
    for (int i = 0; i < n; i++) printf("%d ", data[i]);
    printf("\n");
    return 0;
}
Explanation: ① int *: in an expression, the array name data becomes the address of its first element (a pointer to int). ② arr[i] or *(arr + i): these two mean exactly the same thing. Values changed inside the function are reflected directly in main's data.
K09 Advanced

Problem 30. Insert at the head of a linked list (fill in the blanks)

Read integers until the end of input, adding each one to the head of a linked list in the order read. Finally, traverse the list from the head, print it in the form "30 -> 20 -> 10 -> NULL", and free every node. Fill in 【①】–【⑤】.
Sample run (input is underlined)
10 20 30 30 -> 20 -> 10 -> NULL
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
①: The size of one node. ②: The value to store in the new node. ③: The node after the new one is "the old head". ④: Which node is the new head? ⑤: Save the location of the next node before calling free.
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

struct Node *insert_head(struct Node *head, int val) {
    struct Node *new_node = malloc(sizeof(struct Node));
    if (new_node == NULL) exit(1);
    new_node->data = val;
    new_node->next = head;
    return new_node;
}

int main(void) {
    struct Node *list = NULL;
    int v;
    while (scanf("%d", &v) == 1) {
        list = insert_head(list, v);
    }

    for (struct Node *p = list; p != NULL; p = p->next) {
        printf("%d -> ", p->data);
    }
    printf("NULL\n");

    while (list != NULL) {
        struct Node *next = list->next;
        free(list);
        list = next;
    }
    return 0;
}
Explanation: ① sizeof(struct Node): be careful not to confuse it with sizeof(struct Node *) (the size of a pointer). ② val. ③ head: by pointing the new node at the old head, it is linked in at the front of the list. ④ new_node: the caller updates list with the return value. ⑤ list->next: reading next from a node after it has been freed is undefined behavior, so take it out first. When the input is empty, the list stays empty and only "NULL" is printed.

Review these lessons

← Back to all practice problems