Beginner Logical Thinking C

Simple Loop Programs in C for Practice

Practise for, while and do-while loops in C with small programs and predict their output.

  • TimeO(n) for the sum, table, factorial and even sum; O(d) for counting d digits
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

Use a for loop in C when you know how many times to repeat, such as summing 1 to n or printing a multiplication table. Use a while loop when you repeat until a condition changes, such as counting the digits of a number. Use a do-while loop when the body must run at least once. Most loop programs keep one counter and one result variable, for example sum += i.

for loopwhile loopdo-while loopLoop counters and accumulators
1

Problem statement

Write these simple loop programs in C and check that your output matches:

  1. Sum of the first n natural numbers (for loop).
  2. Multiplication table of a number (for loop).
  3. Count the digits of a number (while loop).
  4. Factorial of a number (for loop).
  5. Sum of even numbers from 1 to 20 (for loop with a step of 2).
  6. Print 5 down to 1 (do-while loop).

All six are in one program in the solution so you can run them together.

Input

Fixed values inside the program: n = 10, table of 7, number 45872, 6!, even numbers up to 20.

Output

The result of each program, as shown in the solution.

Examples

Example 1
InputSum of 1 to 10
Output55

1 + 2 + ... + 10 = 55, which also equals 10 * 11 / 2.

Example 2
InputCount digits of 45872
Output5

Dividing by 10 five times reaches 0.

Constraints

  • Values fit in an int; the factorial uses long long
2

Think before you code

Reveal the questions to ask yourself first
  • Do you know the number of repeats before the loop starts? Then a for loop fits.
  • What variable changes each time, and what result builds up?
  • What is the first value and the last value of the counter?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start an accumulator at 0 for sums and at 1 for products.
2 Hint 2
For a table, the counter goes 1 to 10 and the line is t x i = t * i.
3 Hint 3
To count digits, divide by 10 in a while loop until the number becomes 0.
4

Approach

Reveal the step-by-step approach

Which loop to use

Loop Checks condition Runs at least once? Good for
for before each pass no known count: 1 to n, tables
while before each pass no unknown count: digits, input until 0
do-while after each pass yes menus, "ask again" input

Parts of a for loop

for (int i = 1; i <= n; i++) {
    /* body */
}

int i = 1 runs once. i <= n is checked before every pass. i++ runs after every pass. When the check is false, the loop ends.

Read loops in programming for the idea in plain words.

5

Dry run

Walk through the example step by step

Count digits of 45872:

temp  | temp != 0? | count | temp / 10
------+------------+-------+----------
45872 | yes        | 1     | 4587
4587  | yes        | 2     | 458
458   | yes        | 3     | 45
45    | yes        | 4     | 4
4     | yes        | 5     | 0
0     | no, stop   |       |
6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

int main(void) {
    /* 1. Sum of first n natural numbers (for loop) */
    int n = 10, sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    printf("Sum of 1 to %d = %d\n", n, sum);

    /* 2. Multiplication table (for loop) */
    int t = 7;
    for (int i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", t, i, t * i);
    }

    /* 3. Count digits (while loop) */
    int num = 45872, count = 0, temp = num;
    while (temp != 0) {
        count++;
        temp /= 10;
    }
    printf("%d has %d digits\n", num, count);

    /* 4. Factorial (for loop) */
    long long fact = 1;
    for (int i = 1; i <= 6; i++) {
        fact *= i;
    }
    printf("6! = %lld\n", fact);

    /* 5. Sum of even numbers from 1 to 20 (step of 2) */
    int evenSum = 0;
    for (int i = 2; i <= 20; i += 2) {
        evenSum += i;
    }
    printf("Sum of even numbers up to 20 = %d\n", evenSum);

    /* 6. Print numbers 5 down to 1 (do-while loop) */
    int k = 5;
    do {
        printf("%d ", k);
        k--;
    } while (k >= 1);
    printf("\n");
    return 0;
}

Output:

Sum of 1 to 10 = 55
7 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 = 70
45872 has 5 digits
6! = 720
Sum of even numbers up to 20 = 110
5 4 3 2 1
  • Sum of n: the formula n * (n + 1) / 2 gives the same 55 without a loop. Use it to check your answer.
  • Table: the counter i is both the multiplier and the loop control.
  • Count digits: the number of passes equals the number of digits.
  • Factorial: starts at 1, not 0, or every product would be 0.
  • Even sum: i += 2 skips odd numbers, so the loop runs only 10 times. 2 + 4 + ... + 20 = 110.
  • do-while: the body runs first, then k >= 1 is checked.

While loop programs in C with user input

A while loop is the natural choice when you do not know how many inputs will come:

#include <stdio.h>

int main(void) {
    int x, total = 0;
    printf("Enter numbers (0 to stop): ");
    scanf("%d", &x);
    while (x != 0) {
        total += x;
        scanf("%d", &x);
    }
    printf("Total = %d\n", total);
    return 0;
}
Enter numbers (0 to stop): 4 8 15 0
Total = 27

Loop practice questions

# Task Loop
1 Print 1 to 100 for
2 Sum of digits of a number while
3 Reverse a number while
4 Print all factors of n for
5 Power a^b without pow() for
6 Fibonacci series for, see Fibonacci in C
7 Armstrong check while, see Armstrong number in C
8 Sort an array nested for, see selection sort in C

For loops inside loops, try number pattern programs (in Python, but the logic is the same in C).

TimeO(n) for the sum, table, factorial and even sum; O(d) for counting d digits
SpaceO(1)
7

Review before the interview

Common mistakes

  • Putting a semicolon after for (...); which makes the loop body empty.
  • Starting a product at 0, so the factorial is always 0.
  • Forgetting to change the variable in a while loop, which makes it loop forever.
  • Using i < n when the question says 1 to n, which misses the last number.
  • Forgetting the semicolon after while (...) at the end of a do-while.

Edge cases to test

  • Count digits of 0: the while (temp != 0) loop does not run and prints 0 digits. Use a do-while or a special case to get 1.
  • Negative numbers: the digit count loop still works because temp moves towards 0.
  • n = 0 in the sum program prints 0.
  • Factorial above 20! overflows even a long long.

Interview follow-ups

  • Can you print the multiplication table in reverse, from 10 down to 1?
  • How would you count digits without a loop, using log10?
  • When is a do-while loop a better choice than a while loop?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us