Review the key points with a cheat sheet, six code-reading questions, and a checklist of common mistakes.
for (int i = 0; i < 3; i++) { printf("%d ", i); } // Output: 0 1 2
// Check condition → execute while (cond) { // Zero or more iterations } // Execute → check condition do { // At least one iteration } while (cond);
; is required) for (int i = 0; i < 5; i++) { if (i == 3) break; // Exit the loop → 0 1 2 if (i == 2) continue; // Skip this iteration only printf("%d ", i); }
int a[5] = {10, 20, 30, 40, 50}; // Indices run from 0 to N-1 (0–4 here) printf("%d\n", a[0]); // 10 printf("%d\n", a[4]); // 50 // a[5] is out of bounds: undefined behavior
for(i=0; i<N; i++) ... a[i] ...char s[] = "Hi"; // Memory: 'H' 'i' '\0' — terminator added automatically printf("%s\n", s); // Hi printf("%zu\n", strlen(s)); // 2 (excluding \0) printf("%zu\n", sizeof s); // 3 (array size including \0)
\0(a string literal includes it automatically) strlen counts characters before \0; sizeof gives the array size in bytes #include <string.h> declares strlen and related functions for (int i = 1; i <= 5; i++) { printf("%d ", i); }
int i = 10; do { printf("%d ", i); i++; } while (i < 3);
int a[] = {2, 4, 6, 8}; int sum = 0; for (int i = 0; i < 4; i++) sum += a[i]; printf("%d\n", sum);
20. A standard array loop visits indices 0 through N-1.for (int i = 0; i < 5; i++) { if (i == 3) break; printf("%d ", i); }
0 1 2. Replacing break with continue would skip only that iteration and print 0 1 2 4.int a[3] = {10, 20, 30}; for (int i = 0; i <= 3; i++) { printf("%d ", a[i]); }
i < N.#include <stdio.h> #include <string.h> int main(void) { char s[10] = "Hello"; printf("%zu\n", strlen(s)); return 0; }
5. The terminator is excluded. In this example sizeof s is 10, the array capacity in bytes.<and <=caused an off-by-one iteration count i<5 runs five times; i<=5 runs six. With an array, that can access outside its bounds. while(i<5){...}inside i++ can leave the loop running forever if the update is omitted. Ensure something makes the condition false eventually. break exits the loop; continue starts the next iteration. Confusing them changes the output. do { ... } while (cond); needs its final semicolon, unlike an ordinary while loop.strlen("Hi") is 2 (character count); sizeof "Hi" is 3 (bytes including \0). They serve different purposes.