Here are 13 problems, from beginner to advanced, that use arrays. They cover the basics of 1D arrays, 2D arrays (matrices), sorting and binary search. Write your code in the browser and press "Check": it is run with real gcc on several inputs to see whether the output is correct.
Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
scanf("%d", &a[i]); with for (i = 0; i < n; i++). To print, start at i = n - 1 and go back to 0 with i--.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } for (int i = n - 1; i >= 0; i--) { printf("%d ", a[i]); } printf("\n"); return 0; }
i = n, you read a[n], which is outside the array (out-of-bounds access is undefined behavior; it may not cause an error and just print a garbage value). The end condition must also be i >= 0, or a[0] is not printed."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
sum for the total to 0 and repeat sum += a[i]; N times. For the average, divide with one side converted to double: (double)sum / n.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } printf("Sum: %d\n", sum); printf("Average: %.2f\n", (double)sum / n); return 0; }
sum / n is division of two ints, and the fractional part is discarded (5 / 3 is 1). If you write (double)sum / n, sum is converted to double before the division, so you get 1.666…. (double)(sum / n) converts after dividing, so it doesn't help."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
imax = 0 and update imax = i when a[i] > a[imax]. When printing, the position is imax + 1.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int imax = 0, imin = 0; for (int i = 1; i < n; i++) { if (a[i] > a[imax]) imax = i; if (a[i] < a[imin]) imin = i; } printf("Max: %d (position %d)\n", a[imax], imax + 1); printf("Min: %d (position %d)\n", a[imin], imin + 1); return 0; }
0, you get the wrong answer when all the numbers are negative. Starting from the first element is the safe choice. Also, if you compare with >=, it updates on equal values too, and you end up with the last position."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
i from 0 to n - 2 and print a[i + 1] - a[i]. The loop condition is i < n - 1.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } for (int i = 0; i < n - 1; i++) { printf("%d ", a[i + 1] - a[i]); } printf("\n"); return 0; }
a[i + 1], think about whether i + 1 is inside the array. If the condition is i < n, the last step reads a[n] (out of bounds). When N=1, the loop doesn't run even once, and only an empty line is printed.Not found"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
a[i] == x, record i if the position is still −1, and increase the count by 1 every time.#include <stdio.h> int main(void) { int n, x; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } scanf("%d", &x); int pos = -1, count = 0; for (int i = 0; i < n; i++) { if (a[i] == x) { if (pos == -1) pos = i; count++; } } if (count == 0) { printf("Not found\n"); } else { printf("First position: %d\n", pos + 1); printf("Count: %d\n", count); } return 0; }
break as soon as you find it, but this problem also counts them, so you check to the end. Instead, record the position only the first time (if you do pos = i every time, you get the last position). Representing "not found" with −1, a value that can never be an index, is a standard technique."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
a[i] >= avg.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } double avg = (double)sum / n; printf("Average: %.2f\n", avg); for (int i = 0; i < n; i++) { if (a[i] >= avg) { printf("%d ", a[i]); } } printf("\n"); return 0; }
int avg = sum / n;, the input 1 2 2 gives an average of 1, and 1 gets printed too. In the comparison a[i] >= avg, the int is converted to double before comparing.* characters. There are 10 ranges: 0-9, 10-19, …, 80-89, 90-100 (100 belongs to 90-100). Print ranges with nobody in them too, like "20-29:"."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
int cnt[10] = {0}; to count the people in each range. The range number for a score s is s / 10, but 100 gives 10, so change it to 9 only in that case.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int cnt[10] = {0}; for (int i = 0; i < n; i++) { int k = a[i] / 10; if (k == 10) k = 9; cnt[k]++; } for (int k = 0; k < 10; k++) { if (k == 9) { printf("90-100: "); } else { printf("%d-%d: ", k * 10, k * 10 + 9); } for (int j = 0; j < cnt[k]; j++) { printf("*"); } printf("\n"); } return 0; }
cnt[10], which is out of bounds. Initialize the counting array with = {0} so that every element starts at 0 (an array inside a function has indeterminate contents unless you initialize it).No second largest value"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
max, and the second pass finds "the largest value that is smaller than max". In the second pass, use a variable (a flag) that means "nothing found yet".#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int max = a[0]; for (int i = 1; i < n; i++) { if (a[i] > max) max = a[i]; } int found = 0, second = 0; for (int i = 0; i < n; i++) { if (a[i] < max && (!found || a[i] > second)) { second = a[i]; found = 1; } } if (found) { printf("Second largest: %d\n", second); } else { printf("No second largest value\n"); } return 0; }
second at a fixed value such as 0, it fails when all the numbers are negative. That is why found is used to say "accept the first value found as is"."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
a[i][j] is "row i, column j". For row sums, put i in the outer loop and loop over j; for column sums, put j in the outer loop and loop over i. Reset the sum variable to 0 every time you enter the outer loop.#include <stdio.h> int main(void) { int r, c; int a[10][10]; scanf("%d %d", &r, &c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { scanf("%d", &a[i][j]); } } printf("Row sums:"); for (int i = 0; i < r; i++) { int sum = 0; for (int j = 0; j < c; j++) { sum += a[i][j]; } printf(" %d", sum); } printf("\n"); printf("Column sums:"); for (int j = 0; j < c; j++) { int sum = 0; for (int i = 0; i < r; i++) { sum += a[i][j]; } printf(" %d", sum); } printf("\n"); return 0; }
sum = 0 outside the nested loop, the previous row's sum carries over and you get a running total. Swapping the indexes, as in a[j][i], for the column sums is another common mistake; when R and C differ, it reads out of bounds."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
j from 0 to n - 2 - i and swap when a[j] > a[j + 1]. Use a temporary variable tmp for the swap.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } int swaps = 0; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; swaps++; } } } for (int i = 0; i < n; i++) { printf("%d ", a[i]); } printf("\nSwaps: %d\n", swaps); return 0; }
a[j] = a[j + 1]; a[j + 1] = a[j];, the first statement destroys the original a[j], so both end up with the same value. Always save it in tmp first. Each round of the outer loop fixes the maximum at the right end, so you can shrink the inner range to n - 1 - i. Note that the number of swaps equals the number of pairs where a larger value is to the left of a smaller one (the inversion count).Pass k: ", separated by spaces."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
i = k - 1. Start with imin = i, check j = i + 1 to n - 1, and set imin = j when a[j] < a[imin]. Finally, swap a[i] and a[imin] and print the array.#include <stdio.h> int main(void) { int n; int a[100]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } for (int i = 0; i < n - 1; i++) { int imin = i; for (int j = i + 1; j < n; j++) { if (a[j] < a[imin]) imin = j; } int tmp = a[i]; a[i] = a[imin]; a[imin] = tmp; printf("Pass %d:", i + 1); for (int j = 0; j < n; j++) { printf(" %d", a[j]); } printf("\n"); } return 0; }
<=, the rightmost minimum is chosen when there are several, and the intermediate results for the input 3 1 3 1 change."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
i (rows of C) and j (columns of C), and inside them loop k from 0 to m−1, accumulating c[i][j] += a[i][k] * b[k][j];.#include <stdio.h> int main(void) { int n, m, p; int a[10][10], b[10][10], c[10][10]; scanf("%d %d %d", &n, &m, &p); for (int i = 0; i < n; i++) { for (int k = 0; k < m; k++) { scanf("%d", &a[i][k]); } } for (int k = 0; k < m; k++) { for (int j = 0; j < p; j++) { scanf("%d", &b[k][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { c[i][j] = 0; for (int k = 0; k < m; k++) { c[i][j] += a[i][k] * b[k][j]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { printf("%d ", c[i][j]); } printf("\n"); } return 0; }
+= on c[i][j] without initializing it to 0, you start adding to an indeterminate value. The loop limits are n for i, p for j and m for k. If you mix any of them up, the tests with square matrices may pass, but it reads out of bounds when n, m and p differ.Not found" if it isn't there. Use binary search."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
lo to hi (initially 0 to N−1). While lo <= hi, compare with the middle element mid and halve the range. If a[mid] is smaller, set lo = mid + 1; if it is larger, set hi = mid - 1.#include <stdio.h> int main(void) { int n, q; int a[1000]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } scanf("%d", &q); for (int t = 0; t < q; t++) { int x; scanf("%d", &x); int lo = 0, hi = n - 1, pos = -1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == x) { pos = mid; break; } else if (a[mid] < x) { lo = mid + 1; } else { hi = mid - 1; } } if (pos >= 0) { printf("%d\n", pos + 1); } else { printf("Not found\n"); } } return 0; }
lo = mid, the range may never shrink and you get an infinite loop. And if the condition is lo < hi, the loop ends without checking the last remaining element. It assumes the array is sorted; if it isn't, you must sort it first.