The sum of the first n numbers
Read a natural number n and print the sum 1 + 2 + … + n, computed with a for loop.
515Loop structures let a sequence of statements run as long as a condition stays true. The three forms in C/C++ are equivalent in computing power, but each expresses a particular kind of repetition more naturally.
for statementbreak and continue statements| Statement | Condition test | Minimum executions | Used when |
|---|---|---|---|
while | before the body | 0 | the number of repetitions is not known in advance |
do-while | after the body | 1 | the body must run at least once (menus, validation) |
for | before the body | 0 | the number of repetitions is known or a range is being traversed |
while (expression)
statement;
do
statement;
while (expression); // note: the semicolon here is mandatory
With while, the expression is tested first; if it is true (nonzero), the body
runs, then it is re-evaluated. With do-while, the body runs before the
first test, so at least once, regardless of the condition.
for (initialization; condition; step)
statement;
for (int i = 0; i < 10; i++) { ... }
│ │ └── runs AFTER every iteration
│ └─────────── tested BEFORE every iteration
└─────────────────────── runs ONCE, at the start
All three components are optional. for (;;) is a valid infinite loop,
equivalent to while (1).
| Form | Effect |
|---|---|
for (i = 0; i < n; i++) | classic ascending traversal |
for (i = n - 1; i >= 0; i--) | descending traversal |
for (i = 0, j = n; i < j; i++, j--) | two indices, using the comma operator |
for (;;) | infinite loop |
Change the three parameters and watch the iteration table: how many times the body runs, what values the counter takes, and what value it is left with after the loop ends. Set the step to 0 to see how an infinite loop is detected.
Watch how continue and break work in a loop that
only sums the even numbers, stopping at the first negative value.
| Statement | Effect | Scope of action |
|---|---|---|
break | exits the current loop or switch | only the innermost structure |
continue | skips to the next iteration | only the innermost loop |
return | exits the function, returning a value | the whole function |
goto label | unconditional jump to a label | within the same function |
exit(code) | terminates the entire program | the whole program |
goto makes
code hard to follow and maintain. The only use accepted in modern practice is a quick exit from
deeply nested loops, toward a common resource-cleanup point.break only exits the inner loop.
To leave both loops, use a flag (bool found), move the code into a function with
return, or - rarely - goto.for (i = 0; i < 10; i++); runs the loop ten times "doing nothing", and the block
below it runs only once.for (i = 0; i <= n; i++) runs n + 1 iterations. When traversing an array
of n elements, this overruns the bound by one position.do-while, continue jumps directly to the condition test. If
incrementing the counter is placed after continue, it never runs, and the loop
becomes infinite.for makes the behavior hard to follow and
is a frequent source of loops that never end.
#include <stdio.h>
int main(void)
{
int n, i = 0;
double value, sum = 0.0;
printf("How many values? ");
scanf("%d", &n);
while (i < n) {
printf("Value %d: ", i + 1);
scanf("%lf", &value);
sum += value;
i++; // WITHOUT this line: an infinite loop
}
if (n > 0)
printf("Arithmetic mean = %.4f\n", sum / n);
else
printf("No value entered\n");
return 0;
}
#include <stdio.h>
int main(void)
{
int choice;
do {
printf("\n--- MENU ---\n");
printf("1. Add\n2. Delete\n3. Show\n0. Exit\n");
printf("Choose: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("You chose add\n"); break;
case 2: printf("You chose delete\n"); break;
case 3: printf("You chose show\n"); break;
case 0: printf("Goodbye!\n"); break;
default: printf("Invalid option\n");
}
} while (choice != 0); // the menu is shown at least once
return 0;
}
#include <stdio.h>
int main(void)
{
printf("Prime numbers up to 50:\n");
for (int n = 2; n <= 50; n++) {
int prime = 1; // assume n is prime
for (int d = 2; d * d <= n; d++)
if (n % d == 0) {
prime = 0; // a divisor was found
break; // immediate exit from the inner loop
}
if (!prime) continue; // skip the non-primes
printf("%d ", n);
}
printf("\n");
// multiplication table, with nested loops
printf("\nMultiplication table 1-5:\n");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++)
printf("%4d", i * j);
printf("\n"); // new line after each row
}
return 0;
}
With loops, Step by step mode is the most useful tool: you see the counter growing and the condition being re-evaluated on every pass.
This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.
Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.
Read a natural number n and print the sum 1 + 2 + … + n, computed with a for loop.
515Read a natural number n and print the sum of its digits, using while.
123410Read an integer n and print, one per line, n x i = result for i from 1 to 10.
77 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70The first line holds n (n ≥ 1), then n integers. Print their average with two decimals.
3
4 5 96.00Read an integer n (it may be 0 or negative) and print how many digits it has. The number 0 has one digit. Use do-while.
123455Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.
Read an integer n (2 ≤ n ≤ 5000) and print, on one line, every prime less than or equal to n, separated by spaces.
302 3 5 7 11 13 17 19 23 29Read two non-zero natural numbers a and b (at most 50 000 000). Print their greatest common divisor and least common multiple.
12 186 36Read an integer n (1 ≤ n ≤ 30) and print a pyramid with n rows: row i (from 1) has n - i spaces followed by 2i - 1 stars. Do not leave spaces after the stars.
Spacing matters here: the output is compared character by character (only trailing spaces are ignored).
3 *
***
*****Starting from n (1 ≤ n ≤ 109), repeat: if n is even, n = n / 2, otherwise n = 3n + 1, until you reach 1. Print the number of steps and the largest value reached.
68 16while.for and then with do-while; compare the readability.continue.while.int type overflows.