39 university-level practice problems with difficulty filters, hints, and solution code. Perfect for self-study and exam preparation.
% operator to check even/odd.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; }
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; }
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; }
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; }
{88, 72, 95, 55, 63} and display them.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; }
'\0'.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; }
*, with + placed on the diagonal positions. The interior is whitespace.#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; }
disp_face that prints (^_^) each time it is called. Call it three times from main to produce (^_^)(^_^)(^_^).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; }
area_rectangle function that computes the area of a rectangle using a function prototype declaration.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; }
lcm that computes the least common multiple (LCM).LCM = a * b / GCD.while(b != 0) { tmp = b; b = a % b; a = tmp; } Final value of a is the 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; }
VALUE as 50SUM(a,b) that adds two values50+50=100#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; }
void ascend(int arr[], int n). Use bubble sort.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; }
val (initial value 0) and ninput(): read an integer from the keyboard into naddition(): add n to valproduct(): multiply val by ndisplay(): display the value of valwhile(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; }
draw_graph function.* for each unit of sales, and = at tick positionsj % 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("%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; }
f(x,y,z) = x*x + 2*x*y + y*y*z, then display the result.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; }
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; }
void calc(int *arr, int n, int *sum, double *avg).*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; }
to_upper(char *s) that takes a string and converts all lowercase letters to uppercase using a pointer.'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).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; }
Student with a name (up to 20 characters) and a score. Read data for 3 students and display the student with the highest score.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; }
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.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; }
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; }
fopen("scores.txt", "w") -> fprintf -> fclose.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; }
*.*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; }
#, tick positions with +, and everything else with -.i==0 || i==h-1 || j==0 || j==w-1 -> #i%v_interval==0 && j%h_interval==0 -> +-#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"); } }
int is_prime(int n).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; }
add(int a, int b): display the sum of two integersmax(double a, double b, double c): display the maximum of three real numbers#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; }
#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; }
int power(int base, int exp). Do not use loops.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; }
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; }
γ???γ parts in the code. These questions are designed to resemble real exam questions.#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; }
&c (pass the address of char)c=='o' (remaining vowel 'o')consonant#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; }
sw < 1 || sw > 4 (loop while out of range)%lf (format specifier for reading double)sw (variable to switch on)x / y (division expression)#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; }
str[] (receive array as argument)'\0' (null terminator)len (return the computed length)len1 + len2 (total length)#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; }
n (loop n times)6 (generate random value 0-5)count[die]++ (increment count for the rolled face)count[i] (cast occurrence count to double)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).#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; }
i < 100 (100 iterations)a * x + b (linear congruential recurrence)y (add y to the sum)y >= 0.2 && y < 0.4 (check if value is in [0.2, 0.4))i % 10 == 9 (newline every 10 values)count / i (proportion = count / total)#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; }
n - 1 - i.n - 1 - i (reverse-order index)5 (array size)#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; }
A[i][k] * B[k][j]#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; }
int * (int pointer receives the array)arr[i] or *(arr + i) (element access via pointer)#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; }
sizeof(struct Node) (allocate memory for one node)val (store the argument in data)head (set the old head as the new node's next)new_node (return the new head)Reviewing with a book after solving problems greatly improves retention
* The links above are affiliate links. Purchases help support this site.