What is the output of this C code snippet?
#include <stdio.h> int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) break; printf("%d%d ", i, j); } } return 0; }
Remember that break exits the inner loop immediately when j == 2.
The inner loop prints i and j until j == 2, then breaks. So only when j == 1 the print happens for each i.
What is the value of count after running this code?
#include <stdio.h> int main() { int count = 0; for (int i = 0; i < 4; i++) { for (int j = i; j < 4; j++) { count++; } } printf("%d", count); return 0; }
Count how many times the inner loop runs for each i.
When i=0, inner loop runs 4 times; i=1 runs 3 times; i=2 runs 2 times; i=3 runs 1 time. Total = 4+3+2+1 = 10.
What error does this code produce when compiled?
#include <stdio.h> int main() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) printf("%d %d\n", i, j); printf("Done\n"); return 0; }
Check how the indentation affects which statements belong to the loops.
Only the inner loop is controlled by the second for. The printf("Done\n") is outside both loops and runs once after all loops finish.
What value does this program print?
#include <stdio.h> int main() { int count = 0; for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { if (i * j % 2 == 0) { count++; } } } printf("%d", count); return 0; }
Count pairs (i, j) where product is even.
5x5=25 total pairs. i * j % 2 == 0 when at least one is even. Odds: 1,3,5 (3); evens: 2,4 (2). Odd-odd pairs (odd product): 3x3=9. Even products: 25-9=16.
What is the output of this code?
#include <stdio.h> int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == j) continue; if (i + j == 4) continue; printf("%d%d ", i, j); } } return 0; }
Skip pairs where i == j or i + j == 4.
Skips when i == j (11,22,33) or i + j == 4 (13,22,31). Printed: 12, 21, 23, 32.