Lesson 6 of 31
Loops
Loops
C has three loop constructs: for, while, and do-while.
for Loop
The most common loop. It has three parts: initialization, condition, and update:
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
"Captain, we appear to be caught in a temporal causality loop." -- The Enterprise keeps reliving the same moment (TNG S5E18). At least they had a
breakcondition.
while Loop
Repeats while a condition is true:
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
do-while Loop
Executes the body at least once, then checks the condition:
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
break and continue
break-- exits the loop immediatelycontinue-- skips to the next iteration
for (int i = 0; i < 10; i++) {
if (i == 5) break; // stops at 5
if (i % 2 == 0) continue; // skip even numbers
printf("%d\n", i); // prints 1, 3
}
Your Task
Write a function int sum_range(int a, int b) that returns the sum of all integers from a to b (inclusive). For example, sum_range(1, 5) returns 15. Print the result of sum_range(1, 10).
TCC compiler loading...
Loading...
Click "Run" to execute your code.