πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English
Advertisement

C Programming Practice Problems

39 university-level practice problems with difficulty filters, hints, and solution code. Perfect for self-study and exam preparation.

Conditional Statement Problems

EX-01 Beginner
Class Assignment
Create a program that accepts a student ID number (positive integer) as input and assigns a class:
- Number 1-20 -> Class A
- Number 21 or greater and even -> Class A
- Number 21 or greater and odd -> Class B
Enter student ID: 25 Student 25 is in Class B
Use an if statement to check the number range. For 21 or greater, use the % operator to check even/odd.
Even: n % 2 == 0, Odd: n % 2 != 0
#include <stdio.h>

int main(void) {
    int num;
    printf("Enter student ID: ");
    scanf("%d", &num);

    if (num >= 1 && num <= 20) {
        printf("Student %d is in Class A\n", num);
    } else if (num % 2 == 0) {
        printf("Student %d is in Class A\n", num);
    } else {
        printf("Student %d is in Class B\n", num);
    }
    return 0;
}
EX-02 Beginner
Maximum of Three Integers
Read three integers (all different values) from the keyboard, display them in input order, and then display the largest number.
Use if-else if-else statements and logical operators.
a = 12 b = 45 c = 7 Inputs: a=12, b=45, c=7 Maximum is 45
Combine comparisons with the AND operator like a >= b && a >= c to determine the maximum.
#include <stdio.h>

int main(void) {
    int a, b, c;
    printf("a = "); scanf("%d", &a);
    printf("b = "); scanf("%d", &b);
    printf("c = "); scanf("%d", &c);
    printf("Inputs: a=%d, b=%d, c=%d\n", a, b, c);

    if (a >= b && a >= c) {
        printf("Maximum is %d\n", a);
    } else if (b >= a && b >= c) {
        printf("Maximum is %d\n", b);
    } else {
        printf("Maximum is %d\n", c);
    }
    return 0;
}
EX-03 Beginner
Even/Odd Check and Quotient/Remainder
Read two integers into variables a and b, print whether each is even or odd, then display the quotient and remainder of a divided by b.
a = 17 b = 5 a is odd b is odd 17 / 5 = quotient 3, remainder 2
Quotient: a / b (integer division), Remainder: a % b. Check even/odd with n % 2.
#include <stdio.h>

int main(void) {
    int a, b;
    printf("a = "); scanf("%d", &a);
    printf("b = "); scanf("%d", &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;
}

Loop and Array Problems

EX-04 Beginner
Multiplication Table
Print the 1-9 multiplication table from row 1 to row 9 using a nested for loop. Use a single for statement for the outer loop.
1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 ... 9 18 27 36 45 54 63 72 81
Outer loop: for(i=1; i<=9; i++), inner loop: for(j=1; j<=9; j++). Use %2d or %3d for column alignment.
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= 9; j++) {
            printf("%3d", i * j);
        }
        printf("\n");
    }
    return 0;
}
EX-05 Beginner
Find the Minimum in an Array
Find the minimum value and its index in a 5-element int array {88, 72, 95, 55, 63} and display them.
minimum is d[3]: 55
Use a variable min_idx to keep track of the minimum index and compare in a loop. Initialize it to 0.
#include <stdio.h>

int main(void) {
    int d[] = {88, 72, 95, 55, 63};
    int n = 5, min_idx = 0;

    for (int i = 1; i < n; i++) {
        if (d[i] < d[min_idx]) min_idx = i;
    }
    printf("minimum is d[%d]: %d\n", min_idx, d[min_idx]);
    return 0;
}
EX-06 Intermediate
Reverse a String
Read a string (no spaces) from the keyboard and display it in reverse order.
Hint: A string ends with '\0'.
Enter a string: abcdef Reversed string is fedcba
Use strlen(str) to get the length, then print one character at a time from the last index (len-1) to the first (0).
#include <stdio.h>
#include <string.h>

int main(void) {
    char str[128];
    printf("Enter a string: ");
    scanf("%s", str);

    int len = strlen(str);
    printf("Reversed string is ");
    for (int i = len - 1; i >= 0; i--) {
        printf("%c", str[i]);
    }
    printf("\n");
    return 0;
}
EX-07 Intermediate
Rectangle Pattern Drawing
Read a size (width and height) and draw a rectangular border using *, with + placed on the diagonal positions. The interior is whitespace.
Width: 7 Height: 5 ******* *+ +* * + + * * + * *******
Use a nested loop to determine each cell. Border: (i==0, i==h-1, j==0, j==w-1). Diagonal: (i==j or i+j==w-1).
#include <stdio.h>

int main(void) {
    int w, h;
    printf("Width: "); scanf("%d", &w);
    printf("Height: "); scanf("%d", &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;
}

Function Problems

EX-08 Beginner
Smiley Face Function
Create a function disp_face that prints (^_^) each time it is called. Call it three times from main to produce (^_^)(^_^)(^_^).
(^_^)(^_^)(^_^)
Define a function with no arguments and no return value: void disp_face(void), and simply call printf("(^_^)") inside it.
#include <stdio.h>

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

int main(void) {
    disp_face();
    disp_face();
    disp_face();
    printf("\n");
    return 0;
}
EX-09 Intermediate
Rectangle Area Function (with Prototype)
Define an area_rectangle function that computes the area of a rectangle using a function prototype declaration.
- main reads "height" and "width" from the keyboard
- The function only performs the calculation and returns the result
- main displays the area
Height: 5 Width: 8 Area is 40
Prototype declaration: write int area_rectangle(int h, int w); before main. Write the function body after main.
#include <stdio.h>

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

int main(void) {
    int h, w;
    printf("Height: "); scanf("%d", &h);
    printf("Width: "); scanf("%d", &w);
    printf("Area is %d\n", area_rectangle(h, w));
    return 0;
}

int area_rectangle(int h, int w) {
    return h * w;
}
EX-10 Intermediate
Least Common Multiple Function
Read two integers and create a function lcm that computes the least common multiple (LCM).
Find the GCD using the Euclidean algorithm, then compute LCM = a * b / GCD.
a = 12 b = 18 LCM is 36
Euclidean algorithm: while(b != 0) { tmp = b; b = a % b; a = tmp; } Final value of a is the GCD.
LCM = original a * original b / GCD
#include <stdio.h>

int gcd(int a, int b) {
    while (b != 0) {
        int tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}

int lcm(int a, int b) {
    return a / gcd(a, b) * b;
}

int main(void) {
    int a, b;
    printf("a = "); scanf("%d", &a);
    printf("b = "); scanf("%d", &b);
    printf("LCM is %d\n", lcm(a, b));
    return 0;
}
EX-11 Intermediate
Using Macros
Create a program that satisfies:
- Define macro VALUE as 50
- Define a function-like macro SUM(a,b) that adds two values
- The main function only contains printf and return, producing output 50+50=100
50+50=100
Define #define VALUE 50 and #define SUM(a,b) ((a)+(b)). It is safer to wrap macro arguments in parentheses.
#include <stdio.h>
#define VALUE 50
#define SUM(a, b) ((a) + (b))

int main(void) {
    printf("%d+%d=%d\n", VALUE, VALUE, SUM(VALUE, VALUE));
    return 0;
}

Comprehensive Problems

EX-12 Advanced
Ascending Sort Function
Read 5 integers from the keyboard and display them sorted in ascending order.
Implement the sort as a function void ascend(int arr[], int n). Use bubble sort.
Input 1: 10 Input 2: 32 Input 3: 8 Input 4: 42 Input 5: 13 Ascending: 8, 10, 13, 32, 42
Bubble sort: compare adjacent elements from back to front and swap if out of order. Repeat n-1 times.
Swap: tmp = a[j-1]; a[j-1] = a[j]; a[j] = tmp;
#include <stdio.h>

void ascend(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = n - 1; j > i; j--) {
            if (arr[j - 1] > arr[j]) {
                int tmp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = tmp;
            }
        }
    }
    printf("Ascending: ");
    for (int i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if (i < n - 1) printf(", ");
    }
    printf("\n");
}

int main(void) {
    int data[5];
    for (int i = 0; i < 5; i++) {
        printf("Input %d: ", i + 1);
        scanf("%d", &data[i]);
    }
    ascend(data, 5);
    return 0;
}
EX-13 Advanced
Calculator Using Global Variables
Create a program with the following specification:
- Declare global variables val (initial value 0) and n
- input(): read an integer from the keyboard into n
- addition(): add n to val
- product(): multiply val by n
- display(): display the value of val
- In main, implement a while-loop menu: 1:Add 2:Multiply -1:Exit
1: Add 2: Multiply -1: Exit> 1 Enter a value> 10 val is now 10 1: Add 2: Multiply -1: Exit> 2 Enter a value> 3 val is now 30 1: Add 2: Multiply -1: Exit> -1
Loop with while(sw != -1) and branch with switch(sw). Inside each case, call input -> addition/product -> display.
#include <stdio.h>

int val = 0;
int n;

void input(void)    { printf("Enter a value> "); 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 (sw != -1) {
        printf("1: Add 2: Multiply -1: Exit> ");
        scanf("%d", &sw);
        switch (sw) {
        case 1: input(); addition(); display(); break;
        case 2: input(); product();  display(); break;
        }
    }
    return 0;
}
EX-14 Advanced
Graph Drawing Function
Store product sales counts in an array and draw a bar graph using a draw_graph function.
- Set a tick interval via a global variable (e.g., 5)
- Print * for each unit of sales, and = at tick positions
- Use a function prototype declaration
Item 1 (12): ****=****=** Item 2 ( 8): ****=*** Item 3 (20): ****=****=****=****=
Print one character per iteration. If j % interval == 0 && j != 0, print =, otherwise print *.
#include <stdio.h>

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

int main(void) {
    int data[] = {12, 8, 20};
    int n = 3;
    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");
}

printf / scanf / Formatting Problems

EX-15 Beginner
Formatted Display of Weights
Read two weights (real numbers) and display them aligned with one decimal place. Also display the sum and the difference.
Weight 1: 3.5 Weight 2: 7.25 Weight 1 = 3.5 kg Weight 2 = 7.3 kg Sum = 10.8 kg Diff = 3.8 kg
printf("%5.1f", val) displays the value right-aligned with total width 5 and one decimal place.
#include <stdio.h>

int main(void) {
    double w1, w2;
    printf("Weight 1: "); scanf("%lf", &w1);
    printf("Weight 2: "); scanf("%lf", &w2);
    printf("Weight 1 = %5.1f kg\n", w1);
    printf("Weight 2 = %5.1f kg\n", w2);
    printf("Sum      = %5.1f kg\n", w1 + w2);
    printf("Diff     = %5.1f kg\n", w1 > w2 ? w1 - w2 : w2 - w1);
    return 0;
}
EX-16 Intermediate
Expression with Three Variables
Read real numbers x, y, z from the keyboard and compute f(x,y,z) = x*x + 2*x*y + y*y*z, then display the result.
x: 1.2 y: 2.2 z: 1.5 f(x,y,z) = 13.920000
Declare variables as double and read them with scanf("%lf", &x). You can write the formula directly.
#include <stdio.h>

int main(void) {
    double x, y, z;
    printf("x: "); scanf("%lf", &x);
    printf("y: "); scanf("%lf", &y);
    printf("z: "); scanf("%lf", &z);
    double result = x*x + 2*x*y + y*y*z;
    printf("f(x,y,z) = %f\n", result);
    return 0;
}

Pointer Problems

EX-17 Intermediate
Swap Values with Pointers
Read two integers and swap them using a swap function that takes pointers, then display the result.
a = 10 b = 20 Before swap: a=10, b=20 After swap: a=20, b=10
Use int *pa, int *pb for the parameters and a temporary variable tmp to swap *pa and *pb. Call it as swap(&a, &b).
#include <stdio.h>

void swap(int *pa, int *pb) {
    int tmp = *pa;
    *pa = *pb;
    *pb = tmp;
}

int main(void) {
    int a, b;
    printf("a = "); scanf("%d", &a);
    printf("b = "); scanf("%d", &b);
    printf("Before swap: a=%d, b=%d\n", a, b);
    swap(&a, &b);
    printf("After swap:  a=%d, b=%d\n", a, b);
    return 0;
}
EX-18 Intermediate
Sum and Average via Pointers
Store 5 integers in an array and create a function that computes the sum and average using pointers.
Implement it as void calc(int *arr, int n, int *sum, double *avg).
data = {10, 20, 30, 40, 50} Sum: 150 Average: 30.0
Return sum and average through pointers. Initialize with *sum = 0;, accumulate with *sum += arr[i];, then compute *avg = (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 data[] = {10, 20, 30, 40, 50};
    int sum; double avg;
    calc(data, 5, &sum, &avg);
    printf("Sum: %d\n", sum);
    printf("Average: %.1f\n", avg);
    return 0;
}
EX-19 Advanced
Convert String to Uppercase via Pointer
Create a function to_upper(char *s) that takes a string and converts all lowercase letters to uppercase using a pointer.
Input: Hello World Converted: HELLO WORLD
If 'a' <= *s && *s <= 'z', do *s -= 32; (the ASCII difference between upper and lower case is 32). Iterate until the null terminator with while(*s).
Use fgets for input that includes spaces.
#include <stdio.h>
#include <string.h>

void to_upper(char *s) {
    while (*s) {
        if (*s >= 'a' && *s <= 'z') *s -= 32;
        s++;
    }
}

int main(void) {
    char str[128];
    printf("Input: ");
    fgets(str, 128, stdin);
    str[strcspn(str, "\n")] = '\0';
    to_upper(str);
    printf("Converted: %s\n", str);
    return 0;
}

Structure Problems

EX-20 Intermediate
Student Score Management
Define a structure Student with a name (up to 20 characters) and a score. Read data for 3 students and display the student with the highest score.
Student 1 Name: Taro Score: 80 Student 2 Name: Hanako Score: 95 Student 3 Name: Jiro Score: 70 Highest: Hanako (95 points)
Define struct Student { char name[20]; int score; }; and allocate an array for 3 students. Find the index with the maximum score in a loop.
#include <stdio.h>

struct Student { char name[20]; int score; };

int main(void) {
    struct Student s[3];
    for (int i = 0; i < 3; i++) {
        printf("Student %d Name: ", i+1); scanf("%s", s[i].name);
        printf("           Score: "); scanf("%d", &s[i].score);
    }
    int max = 0;
    for (int i = 1; i < 3; i++)
        if (s[i].score > s[max].score) max = i;
    printf("Highest: %s (%d points)\n", s[max].name, s[max].score);
    return 0;
}
EX-21 Advanced
Distance Between Points
Define a structure Point holding 2D coordinates (x, y). Read two points and create a function double distance(Point p1, Point p2) that computes the distance between the two points.
Point 1 x: 0.0 y: 0.0 Point 2 x: 3.0 y: 4.0 Distance: 5.000
Distance = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)). Use sqrt from math.h. The compile option -lm may be required.
#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, dy = p2.y - p1.y;
    return sqrt(dx*dx + dy*dy);
}

int main(void) {
    struct Point p1, p2;
    printf("Point 1 x: "); scanf("%lf", &p1.x);
    printf("        y: "); scanf("%lf", &p1.y);
    printf("Point 2 x: "); scanf("%lf", &p2.x);
    printf("        y: "); scanf("%lf", &p2.y);
    printf("Distance: %.3f\n", distance(p1, p2));
    return 0;
}

Dynamic Memory and File I/O Problems

EX-22 Advanced
Dynamic Array for Arbitrary Number of Integers
First read the number of elements n, allocate an array of n elements with malloc, read n integers, and display the sum and average. Always free the memory at the end.
Number of elements: 4 data[0] = 10 data[1] = 20 data[2] = 30 data[3] = 40 Sum: 100, Average: 25.0
Allocate with int *data = (int *)malloc(sizeof(int) * n);. Do not forget the NULL check. Call free(data); when done.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n;
    printf("Number of elements: "); scanf("%d", &n);
    int *data = (int *)malloc(sizeof(int) * n);
    if (data == NULL) { printf("Memory allocation failed\n"); return 1; }

    int sum = 0;
    for (int i = 0; i < n; i++) {
        printf("data[%d] = ", i); scanf("%d", &data[i]);
        sum += data[i];
    }
    printf("Sum: %d, Average: %.1f\n", sum, (double)sum / n);
    free(data);
    return 0;
}
EX-23 Advanced
Write Scores to a File
Read names and scores for 3 people and write them to a text file "scores.txt". After writing, read the file back and display its contents.
Name 1: Taro Score: 80 Name 2: Hanako Score: 95 Name 3: Jiro Score: 70 --- contents of scores.txt --- Taro 80 Hanako 95 Jiro 70
Writing: fopen("scores.txt", "w") -> fprintf -> fclose.
Reading: fopen("scores.txt", "r") -> loop fscanf until EOF -> fclose.
#include <stdio.h>

int main(void) {
    char names[3][20]; int scores[3];
    for (int i = 0; i < 3; i++) {
        printf("Name %d: ", i+1); scanf("%s", names[i]);
        printf("  Score: "); scanf("%d", &scores[i]);
    }
    // Write
    FILE *fp = fopen("scores.txt", "w");
    for (int i = 0; i < 3; i++)
        fprintf(fp, "%s %d\n", names[i], scores[i]);
    fclose(fp);
    // Read
    printf("--- contents of scores.txt ---\n");
    fp = fopen("scores.txt", "r");
    char n[20]; int s;
    while (fscanf(fp, "%s %d", n, &s) != EOF)
        printf("%s %d\n", n, s);
    fclose(fp);
    return 0;
}

Pattern Drawing and Algorithm Problems

EX-24 Intermediate
Triangle Pattern
Read a height n and draw a right triangle using *.
Height: 5 * ** *** **** *****
Outer loop for row (i=1..n), inner loop prints i *s, then a newline.
#include <stdio.h>

int main(void) {
    int n;
    printf("Height: "); scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < i; j++) printf("*");
        printf("\n");
    }
    return 0;
}
EX-25 Intermediate
Grid Drawing (Globals and Functions)
Read width, height, horizontal interval, and vertical interval, and create a grid function that prints the border with #, tick positions with +, and everything else with -.
Manage the intervals with global variables and use a function prototype declaration.
Width: 10 Height: 7 H-Interval: 3 V-Interval: 2 ########## #--+--+--# #--------# #--+--+--# #--------# #--+--+--# ##########
Border: i==0 || i==h-1 || j==0 || j==w-1 -> #
Ticks: i%v_interval==0 && j%h_interval==0 -> +
Otherwise: -
#include <stdio.h>

void grid(int w, int h);
int v_interval, h_interval;

int main(void) {
    int w, h;
    printf("Width: "); scanf("%d", &w);
    printf("Height: "); scanf("%d", &h);
    printf("H-Interval: "); scanf("%d", &h_interval);
    printf("V-Interval: "); scanf("%d", &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");
    }
}
EX-26 Advanced
Prime Check
Read an integer n and display all prime numbers from 2 up to n. Implement the prime test as a function int is_prime(int n).
n = 30 2 3 5 7 11 13 17 19 23 29 Number of primes: 10
Prime test: check divisibility from 2 up to sqrt(n). If any divides evenly, it is not prime. Using sqrt from math.h is efficient.
#include <stdio.h>
#include <math.h>

int is_prime(int n) {
    if (n < 2) return 0;
    for (int i = 2; i <= (int)sqrt(n); i++)
        if (n % i == 0) return 0;
    return 1;
}

int main(void) {
    int n, count = 0;
    printf("n = "); scanf("%d", &n);
    for (int i = 2; i <= n; i++) {
        if (is_prime(i)) { printf("%d ", i); count++; }
    }
    printf("\nNumber of primes: %d\n", count);
    return 0;
}
EX-27 Advanced
add and max Functions
Write a program with the following two functions:
- add(int a, int b): display the sum of two integers
- max(double a, double b, double c): display the maximum of three real numbers
In main, initialize int variables (12, 25) and double variables (23.5, 69.2, 10.3) and call each function.
12 + 25 = 37 max(23.5, 69.2, 10.3) = 69.2
The add function can either be void and call printf inside, or return an int and let main call printf. The max function compares three values.
#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 = 12, y = 25;
    double a = 23.5, b = 69.2, c = 10.3;
    add(x, y);
    max3(a, b, c);
    return 0;
}
EX-28 Advanced
Descending Sort (Selection Sort)
Read 5 integers from the keyboard and display them sorted in descending order.
EX-12 used bubble sort; this time implement it using selection sort.
Input 1: 5 Input 2: 23 Input 3: 11 Input 4: 2 Input 5: 17 Descending: 23, 17, 11, 5, 2
Selection sort: find the maximum in the unsorted region and swap it to the front. Since the sort is descending, look for the "maximum".
#include <stdio.h>

void descend(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int max_idx = i;
        for (int j = i + 1; j < n; j++)
            if (arr[j] > arr[max_idx]) max_idx = j;
        int tmp = arr[i]; arr[i] = arr[max_idx]; arr[max_idx] = tmp;
    }
}

int main(void) {
    int data[5];
    for (int i = 0; i < 5; i++) {
        printf("Input %d: ", i+1); scanf("%d", &data[i]);
    }
    descend(data, 5);
    printf("Descending: ");
    for (int i = 0; i < 5; i++) {
        printf("%d", data[i]);
        if (i < 4) printf(", ");
    }
    printf("\n");
    return 0;
}
EX-29 Advanced
Power via Recursion
Read a base and an exponent, and compute the power using a recursive function int power(int base, int exp). Do not use loops.
Base: 2 Exponent: 10 2^10 = 1024
Base case: exp == 0 -> return 1. Recursive case: base * power(base, exp - 1).
#include <stdio.h>

int power(int base, int exp) {
    if (exp == 0) return 1;
    return base * power(base, exp - 1);
}

int main(void) {
    int b, e;
    printf("Base: "); scanf("%d", &b);
    printf("Exponent: "); scanf("%d", &e);
    printf("%d^%d = %d\n", b, e, power(b, e));
    return 0;
}
EX-30 Advanced
Binary Search
Given an ascending-sorted array, use binary search to find an input value and display its index. If not found, display "Not found".
data = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} Value to search: 23 Found at data[5]
Set low=0, high=n-1. Compute mid = (low + high) / 2. If arr[mid] == target, found. If arr[mid] < target, set low = mid + 1; otherwise high = mid - 1.
#include <stdio.h>

int binary_search(int arr[], int n, int target) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == target) return mid;
        else if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main(void) {
    int data[] = {2,5,8,12,16,23,38,56,72,91};
    int n = 10, target;
    printf("Value to search: "); scanf("%d", &target);
    int idx = binary_search(data, n, target);
    if (idx >= 0) printf("Found at data[%d]\n", idx);
    else printf("Not found\n");
    return 0;
}

Fill-in-the-Blank Problems (Final Exam Prep)

In the following problems, fill in the 【???】 parts in the code. These questions are designed to resemble real exam questions.
EX-31 Beginner
Vowel Check (Fill-in)
Fill in the blanks of a program that reads one character and prints "is a vowel" if it is a vowel (a, e, i, o, u) or "is a consonant" otherwise.
Enter a character> e 'e' is a vowel Enter a character> k 'k' is a consonant
#include <stdio.h>

int main(void) {
    char c;
    printf("Enter a character> ");
    scanf("%c", 【???】);

    if (c=='a' || c=='e' || c=='i' || 【???】 || c=='u') {
        printf("'%c' is a vowel\n", c);
    } else {
        printf("'%c' is a 【???】\n", c);
    }
    return 0;
}
Blank 1: how do you pass an address to scanf? Blank 2: what are the remaining vowels? Blank 3: what is the opposite of a vowel?
Answer:
Blank 1: &c (pass the address of char)
Blank 2: c=='o' (remaining vowel 'o')
Blank 3: consonant
EX-32 Intermediate
Four-Operation Calculator (Fill-in)
Fill in the blanks of a program that lets the user select an operation (1:Add 2:Subtract 3:Multiply 4:Divide) and performs the calculation on two numbers. Invalid choices require re-input.
Operation (1:+ 2:- 3:* 4:/)> 4 x = 21.0 y = 4.0 x / y = 5.250000
#include <stdio.h>

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

    printf("Operation (1:+ 2:- 3:* 4:/)> ");
    scanf("%d", &sw);
    while (【???】) {
        printf("Enter 1-4> ");
        scanf("%d", &sw);
    }
    printf("x = "); scanf("【???】", &x);
    printf("y = "); scanf("%lf", &y);

    switch (【???】) {
    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", 【???】); break;
    }
    return 0;
}
While condition: reject values outside 1-4. scanf format: reading a double. switch: which variable to branch on? Division expression: x/y.
Answer:
Blank 1: sw < 1 || sw > 4 (loop while out of range)
Blank 2: %lf (format specifier for reading double)
Blank 3: sw (variable to switch on)
Blank 4: x / y (division expression)
EX-33 Intermediate
String Length Comparison (Fill-in)
Fill in the blanks of a program that uses a custom length function to compare the lengths of two strings.
String 1> orange String 2> apple orange is 6 characters apple is 5 characters Total is 11 characters orange is longer
#include <stdio.h>
#define MAX 101

int length(char 【???】) {
    int len = 0;
    for (int i = 0; str[i] != 【???】; i++) {
        len++;
    }
    return 【???】;
}

int main(void) {
    char s1[MAX], s2[MAX];
    printf("String 1> "); scanf("%s", s1);
    printf("String 2> "); scanf("%s", s2);

    int len1 = length(s1), len2 = length(s2);
    printf("%s is %d characters\n", s1, len1);
    printf("%s is %d characters\n", s2, len2);
    printf("Total is %d characters\n", 【???】);

    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;
}
Function argument: how to receive an array? Terminator: what is the end of a C string? return: what should it return? Total: add both lengths.
Answer:
Blank 1: str[] (receive array as argument)
Blank 2: '\0' (null terminator)
Blank 3: len (return the computed length)
Blank 4: len1 + len2 (total length)
EX-34 Advanced
Dice Simulation (Fill-in)
Fill in the blanks of a program that rolls a die n times and displays the count and proportion of each face.
Rolls: 1000 Face 1: 168 times (16.8%) Face 2: 172 times (17.2%) Face 3: 155 times (15.5%) Face 4: 170 times (17.0%) Face 5: 167 times (16.7%) Face 6: 168 times (16.8%)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    int n, count[6] = {0};
    printf("Rolls: "); scanf("%d", &n);
    srand((unsigned)time(NULL));

    for (int i = 0; i < 【???】; i++) {
        int die = rand() % 【???】;  // 0-5
        【???】;
    }

    for (int i = 0; i < 6; i++) {
        printf("Face %d: %d times (%.1f%%)\n",
            i + 1, count[i], (double)【???】 / n * 100);
    }
    return 0;
}
Loop count: n rolls. rand()%6: generate 0-5. Count: increment the corresponding index. Proportion: cast count[i] to double.
Answer:
Blank 1: n (loop n times)
Blank 2: 6 (generate random value 0-5)
Blank 3: count[die]++ (increment count for the rolled face)
Blank 4: count[i] (cast occurrence count to double)
EX-35 Advanced
Linear Congruential Pseudo-Random (Fill-in)
Generate a pseudo-random sequence following the recurrence xn+1 = (a x xn + b) mod m. Fill in the blanks to compute the average of 100 values and the proportion of values in [0.2, 0.4).
Parameters: a=717, b=23, m=65536, initial x=1234. Convert to a real number in [0, 1) using y = x / m.
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 ... (omitted) ... Average is 0.505 Proportion of values in [0.2, 0.4) is 0.200
#include <stdio.h>

int main(void) {
    int m = 65536, a = 717, b = 23, x = 1234;
    int i, count = 0;
    double y, sum = 0.0;

    for (i = 0; 【???】; i++) {
        x = (【???】) % m;
        y = (double)x / m;
        sum += 【???】;

        if (【???】) {
            count++;
        }

        printf("%1.3f ", y);
        if (【???】) {
            printf("\n");
        }
    }
    printf("\nAverage is %1.3f\n", sum / i);
    printf("Proportion of values in [0.2, 0.4) is %1.3f\n",
           (double)【???】);
    return 0;
}
Loop condition: 100 iterations. Recurrence: a*x+b. Accumulate: add y. Range check: y>=0.2 and y<0.4. Newline: every 10 values. Proportion: count/i.
Answer:
Blank 1: i < 100 (100 iterations)
Blank 2: a * x + b (linear congruential recurrence)
Blank 3: y (add y to the sum)
Blank 4: y >= 0.2 && y < 0.4 (check if value is in [0.2, 0.4))
Blank 5: i % 10 == 9 (newline every 10 values)
Blank 6: count / i (proportion = count / total)
EX-36 Intermediate
Reverse Copy an Array (Fill-in)
Fill in the blanks of a function that copies the elements of an array into another array in reverse order.
#include <stdio.h>

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

int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    int b[5];
    reverse_copy(a, b, 【???】);
    for (int i = 0; i < 5; i++)
        printf("%d ", b[i]);
    printf("\n");  // Output: 5 4 3 2 1
    return 0;
}
Reverse index: when i=0, the last element (n-1); when i=1, n-2, ... so n - 1 - i.
Answer:
Blank 1: n - 1 - i (reverse-order index)
Blank 2: 5 (array size)
EX-37 Advanced
Matrix Multiplication (Fill-in)
Fill in the blanks of a program that computes the product of two 2x2 matrices.
A = {{1,2},{3,4}}, B = {{5,6},{7,8}} C[0][0]=19 C[0][1]=22 C[1][0]=43 C[1][1]=50
#include <stdio.h>
#define N 2

int main(void) {
    int A[N][N] = {{1,2},{3,4}};
    int B[N][N] = {{5,6},{7,8}};
    int C[N][N] = {0};

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < N; k++) {
                C[i][j] += 【???】;
            }
        }
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf("C[%d][%d]=%d ", i, j, C[i][j]);
        printf("\n");
    }
    return 0;
}
Matrix product: C[i][j] = Sigma A[i][k] * B[k][j]. Accumulate inside the innermost of three nested loops.
Answer:
A[i][k] * B[k][j]
Definition of matrix product: Cij = Sigmak Aik x Bkj
EX-38 Intermediate
Pointer and Array (Fill-in)
Fill in the blanks of a function that doubles each element of an array using a pointer.
#include <stdio.h>

void double_array(【???】 arr, int n) {
    for (int i = 0; i < n; i++) {
        【???】 *= 2;
    }
}

int main(void) {
    int data[] = {3, 7, 1, 9};
    double_array(data, 4);
    for (int i = 0; i < 4; i++)
        printf("%d ", data[i]);
    printf("\n");  // Output: 6 14 2 18
    return 0;
}
Function argument: what type receives an array via a pointer? Element access: how to access the i-th element via a pointer?
Answer:
Blank 1: int * (int pointer receives the array)
Blank 2: arr[i] or *(arr + i) (element access via pointer)
EX-39 Advanced
Linked List Insertion (Fill-in)
Fill in the blanks of a function that inserts a node at the head of a singly linked list.
#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 = (struct Node*)malloc(【???】);
    new_node->data = 【???】;
    new_node->next = 【???】;
    return 【???】;
}

int main(void) {
    struct Node *list = NULL;
    list = insert_head(list, 30);
    list = insert_head(list, 20);
    list = insert_head(list, 10);

    struct Node *p = list;
    while (p != NULL) {
        printf("%d -> ", p->data);
        p = p->next;
    }
    printf("NULL\n"); // Output: 10 -> 20 -> 30 -> NULL
    return 0;
}
malloc: size of one Node. data: the argument value. next: the original head. return: the new head node.
Answer:
Blank 1: sizeof(struct Node) (allocate memory for one node)
Blank 2: val (store the argument in data)
Blank 3: head (set the old head as the new node's next)
Blank 4: new_node (return the new head)

Recommended Books to Pair with These Exercises

Reviewing with a book after solving problems greatly improves retention

πŸ“˜
The C Programming Language (2nd Edition)
B. W. Kernighan, D. M. Ritchie
The classic "K&R". The canonical C book. Ideal step-up after mastering the basics.
View on Amazon
πŸ“—
C Primer Plus (6th Edition)
Stephen Prata
A friendly, thorough introduction with plenty of examples and exercises.
View on Amazon
πŸ“™
Effective C
Robert C. Seacord
Modern C practices and how to write safer, clearer code.
View on Amazon

* The links above are affiliate links. Purchases help support this site.

Share this article
Share on X (Twitter) Share on Facebook Share on LinkedIn Share on Reddit