for#
The counting loop:
for (int i = 0; i < 5; i++) {
printf("%d\n", i); // 0 1 2 3 4
}
The three parts in the brackets are: what to do first (int i = 0), the condition checked before each round (i < 5), and what to do after each round (i++). Read it as "start at 0, keep going while i is below 5, add one each time".
Counting down, or in steps:
for (int i = 10; i > 0; i -= 2) {
printf("%d ", i); // 10 8 6 4 2
}
Adding up an array#
int nums[] = {4, 8, 15, 16, 23, 42};
int n = 6;
long long total = 0;
for (int i = 0; i < n; i++) {
total += nums[i];
}
printf("%lld\n", total); // 108
while#
When you do not know how many rounds there will be, loop while a condition holds:
int n = 4071, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
Something inside must move towards the end. If nothing changes, the loop never stops, and on a judge that shows up as Time limit exceeded.
do while#
Runs the body once before checking, which suits "do this, then repeat if needed":
int x;
do {
printf("Enter a positive number: ");
scanf("%d", &x);
} while (x <= 0);
break and continue#
for (int i = 0; i < n; i++) {
if (nums[i] < 0) {
break; // leave the loop entirely
}
if (nums[i] % 2 == 1) {
continue; // skip the rest of this round
}
printf("%d\n", nums[i]);
}
Nested loops#
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
printf("%d ", row * col);
}
printf("\n");
}
The inner loop runs completely for every round of the outer, so two loops over n items do n × n steps. That is fine for a thousand items and far too slow for a hundred thousand.
Off by one#
Most loop bugs are being one step out.
- An array of
nelements has positions0ton - 1.for (i = 0; i <= n; i++)readsnums[n], which does not exist. C will not stop you: it quietly reads whatever memory comes next, and the bug may show up somewhere else entirely. - Comparing each element with the next, stop one early:
i < n - 1, then usenums[i]andnums[i + 1]. - Going backwards:
for (int i = n - 1; i >= 0; i--).
Check both ends by hand: what is i on the first round, and on the last?
Key points#
for (start; condition; step)is the counting loop.whilerepeats while a condition holds;do whileruns at least once.breakleaves;continueskips to the next round.- Positions run
0ton - 1, and C does not check, so be exact.
Next: organising code into functions.