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.
Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.
Student 25 is in class B"."Run" executes your code with the input above. "Check" tests it against 6 prepared inputs.
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; }
||. 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."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
% 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; }
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."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; }
%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.%f."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
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; }
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.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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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; }
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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
;: 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; }
returns it, leaving the printing to main, it becomes a function you can reuse in other situations.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)."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
#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; }
#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".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)"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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; }
max can clash with a standard library or macro name in some environments, so a specific name like max3 is safer.*; 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."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
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; }
*. Trailing spaces are ignored when checking, but in this program every line ends with * anyway, so you do not need to worry about them.#; 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)."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
+ 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"); } }
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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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"); }
(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.val (initially 0) and n, write the following menu-driven calculator.val is now 10" after the calculationExiting (val = 30)" and finish"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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; }
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.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)."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
*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; }
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.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."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
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; }
-lm option.int capitalize(char *s) that returns the number of words."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
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; }
*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.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)."Run" executes your code with the input above. "Check" tests it against 7 prepared inputs.
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; }
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.value (difference)". Print the difference with a sign and 2 digits after the decimal point (%+.2f). Call free at the end."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; }
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".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)."Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
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; }
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'.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."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
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; }
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".+ - * / (/ 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."Run" executes your code with the input above. "Check" tests it against 8 prepared inputs.
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; }
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.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)."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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; }
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.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).
'e' is a vowel" if it is a vowel (a, e, i, o, u), or "'k' is a consonant" otherwise."Run" executes your code with the input above. "Check" tests it against 6 prepared inputs.
#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; }
&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.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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
#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; }
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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
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; }
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.my_rand() (which returns 0–32767) instead of the standard rand."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
#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; }
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."Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
#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; }
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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
#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; }
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."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
#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; }
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."Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
#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; }
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.30 -> 20 -> 10 -> NULL", and free every node. Fill in 【①】–【⑤】."Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
#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; }
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.