C Loop Exercises (for & while)

Here are 13 problems, from beginner to advanced, that use for and while loops. Write your code in the browser and press "Check": it is run with real gcc on several inputs to see whether the output is correct.

How to use these problems
  1. Read the problem and the sample run, then write your code in the box
  2. Press "▶ Run" to try it with your own input
  3. Press "✔ Check" to test the output against several prepared inputs
  4. Stuck? Open "Hint". Solved it? Compare with "Solution & explanation"
Checking rules
  • Print output exactly as in the sample run. Do not print input prompts such as "Enter a number"
  • Trailing spaces at line ends and trailing blank lines are ignored
  • Your code is saved automatically in this browser

Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.

13 problems (Beginner 4 · Intermediate 5 · Advanced 4)

for & while loops (13 problems)

L01 Beginner

Problem 1. Sum from 1 to N

Read an integer N (1 ≤ N ≤ 1000) and print the sum of the integers from 1 to N.
Sample run (input is underlined)
10 Sum: 55
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
Initialize a variable sum that holds the total to 0, then repeat sum += i; with for (i = 1; i <= n; i++).
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    printf("Sum: %d\n", sum);
    return 0;
}
Explanation: There are two common mistakes. If you forget to initialize sum, you start adding to an indeterminate value. If the condition is i < n, N is not added (one short — an "off-by-one" error).
L02 Beginner

Problem 2. Multiplication table

Print the multiplication table from 1 to 9 (rows 1 through 9). Each row goes on one line, and each number is printed with %3d so that it is 3 characters wide. There is no input.
Sample run
1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
Your code
"Run" executes your code with the input above. "Check" tests it against 1 prepared inputs.
Use a nested for loop. The outer loop is the "row" (the number being multiplied), and the inner loop is the "column" (the multiplier). When the inner loop finishes, print a newline with printf("\n");.
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= 9; j++) {
            printf("%3d", i * j);
        }
        printf("\n");
    }
    return 0;
}
Explanation: In a nested loop, the outer loop advances by one each time the inner loop completes a full round. If you put the newline printf("\n") inside the inner loop, a newline is printed after every number.
L03 Beginner

Problem 3. Even numbers up to N

Read an integer N (1 ≤ N ≤ 100) and print the even numbers from 2 to N in increasing order on one line, separated by spaces. If there are none, print an empty line.
Sample run (input is underlined)
10 2 4 6 8 10
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
If you start i at 2 and increase it with i += 2, you get only the even numbers in order. You can also solve it by testing i % 2 == 0.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 2; i <= n; i += 2) {
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}
Explanation: The third part of a for statement (the update) doesn't have to be i++; you can write anything, such as i += 2. This checker ignores trailing spaces, so it is still correct even though "%d " leaves a space at the end of the line.
L04 Beginner

Problem 4. Factorial

Read an integer N (0 ≤ N ≤ 20) and print N factorial, N!, in the form "N! = value". 0! is 1.
Sample run (input is underlined)
5 5! = 120
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
A variable that accumulates a product is initialized to 1. 20! does not fit in an int (the limit is about 2.1 billion), so use the long long type and the format %lld.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    long long fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    printf("%d! = %lld\n", n, fact);
    return 0;
}
Explanation: The starting value for a sum (addition) is 0; the starting value for a product (multiplication) is 1. If you compute with int, the value overflows from 13! onward and becomes garbage. The N=20 test checks this.
L05 Intermediate

Problem 5. Sum of digits

Read a non-negative integer N (0 ≤ N ≤ 2000000000) and print the sum of its digits.
Sample run (input is underlined)
12345 Sum of digits: 15
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
n % 10 gives the ones digit, and n / 10 drops the ones digit. Repeat this with a while loop until n becomes 0.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    printf("Sum of digits: %d\n", sum);
    return 0;
}
Explanation: A while loop suits repetition where the number of iterations isn't known in advance. "Take the ones digit → drop it" is the standard pattern for problems about digits, so remembering it will help you a lot.
L06 Intermediate

Problem 6. Sum until 0 is entered

Read integers one after another; stop when 0 is entered, and print the count, sum and average of the numbers entered before it (not including the 0). Print the average to 2 decimal places. If nothing was entered before the 0, print "No data".
Sample run (input is underlined)
3 5 7 0 Count: 3 Sum: 15 Average: 5.00
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
Make an infinite loop with while (1) and leave it with break when the value read is 0. For the average, divide with one side converted to double, as in (double)sum / count.
#include <stdio.h>

int main(void) {
    int x, count = 0, sum = 0;

    while (1) {
        scanf("%d", &x);
        if (x == 0) break;
        count++;
        sum += x;
    }

    if (count == 0) {
        printf("No data\n");
    } else {
        printf("Count: %d\n", count);
        printf("Sum: %d\n", sum);
        printf("Average: %.2f\n", (double)sum / count);
    }
    return 0;
}
Explanation: If you write sum / count, it is division of two ints and the fractional part is discarded. Worse, that int value is then passed to %.2f, so the output is garbage (undefined behavior; some environments print 0.00). The compiler warns about this too, so always read the warnings. Also, dividing while count is still 0 is division by zero, so handle that case separately first.
L07 Intermediate

Problem 7. List the divisors

Read an integer N (1 ≤ N ≤ 10000) and print the divisors of N in increasing order on one line, separated by spaces. On the next line, print the number of divisors.
Sample run (input is underlined)
12 1 2 3 4 6 12 Number of divisors: 6
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
For each i from 1 to N, if n % i == 0 (it divides evenly), i is a divisor. Count them while you print them.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    int count = 0;
    for (int i = 1; i <= n; i++) {
        if (n % i == 0) {
            printf("%d ", i);
            count++;
        }
    }
    printf("\nNumber of divisors: %d\n", count);
    return 0;
}
Explanation: This is the pattern of putting an if statement inside a loop to process only the values that meet a condition. N itself is also a divisor, so the condition is i <= n.
L08 Intermediate

Problem 8. Draw a right triangle

Read an integer N (1 ≤ N ≤ 20) and draw a right triangle of N rows with *. Row i has i * characters.
Sample run (input is underlined)
4 * ** *** ****
Your code
"Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
The outer loop goes through rows i from 1 to N, and the inner loop prints i * characters. The key point is that the inner loop's end condition depends on the outer variable i.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: The trick for drawing shapes is to write "what to print, and how many, on row i" as a formula. Here there are i * characters, so the inner loop uses j <= i.
L09 Intermediate

Problem 9. FizzBuzz

Read an integer N (1 ≤ N ≤ 100) and print the numbers from 1 to N, one per line. However, print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both 3 and 5.
Sample run (input is underlined)
15 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
The order of the checks matters. First check "is it a multiple of 15 (both 3 and 5)", then 3, then 5, using if … else if.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        if (i % 15 == 0) {
            printf("FizzBuzz\n");
        } else if (i % 3 == 0) {
            printf("Fizz\n");
        } else if (i % 5 == 0) {
            printf("Buzz\n");
        } else {
            printf("%d\n", i);
        }
    }
    return 0;
}
Explanation: If you check i % 3 == 0 first, 15 also stops at "Fizz" and FizzBuzz never appears. When conditions overlap, write the stricter condition first.
L10 Advanced

Problem 10. Print all primes up to N

Read an integer N (1 ≤ N ≤ 10000) and print the primes up to N in increasing order on one line, separated by spaces. On the next line, print the number of primes (when N is 1, print an empty line and "Number of primes: 0").
Sample run (input is underlined)
20 2 3 5 7 11 13 17 19 Number of primes: 8
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
The outer loop goes through candidates k from 2 to N, and the inner loop checks "is it divisible by any number from 2 to √k". Using j * j <= k as the condition avoids computing √.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    int count = 0;
    for (int k = 2; k <= n; k++) {
        int is_prime = 1;
        for (int j = 2; j * j <= k; j++) {
            if (k % j == 0) {
                is_prime = 0;
                break;
            }
        }
        if (is_prime) {
            printf("%d ", k);
            count++;
        }
    }
    printf("\nNumber of primes: %d\n", count);
    return 0;
}
Explanation: Don't forget to reset the flag variable that remembers "is it prime" (is_prime) to 1 for each candidate. Using break as soon as a divisor is found avoids wasted work.
L11 Advanced

Problem 11. Draw a pyramid

Read an integer N (1 ≤ N ≤ 20) and draw a pyramid of N rows with *. Row i consists of N−i spaces followed by 2i−1 * characters (no trailing spaces).
Sample run (input is underlined)
4 * *** ***** *******
Your code
"Run" executes your code with the input above. "Check" tests it against 3 prepared inputs.
Put two inner loops one after the other within each row. The first prints n - i spaces, the second prints 2 * i - 1 * characters, and then you print a newline.
#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < n - i; j++) {
            printf(" ");
        }
        for (int j = 0; j < 2 * i - 1; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Explanation: Make a table of the counts for each row and the formula becomes clear (for N=4: spaces 3,2,1,0 and stars 1,3,5,7). Leading spaces are compared by the checker, so if the count is off, the answer is wrong.
L12 Advanced

Problem 12. Greatest common divisor and least common multiple

Read two positive integers a and b (1 ≤ a, b ≤ 100000) separated by a space and print their greatest common divisor (GCD) and least common multiple (LCM). Use the Euclidean algorithm.
Sample run (input is underlined)
12 18 GCD: 6 LCM: 36
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
The Euclidean algorithm is simply "replace (a, b) with (b, a % b) until b becomes 0". The a at that point is the GCD. The LCM is a / g * b (where g is the GCD). The result may not fit in an int, so compute (long long)a / g * b and print it with %lld.
#include <stdio.h>

int main(void) {
    int a, b;
    scanf("%d %d", &a, &b);

    int x = a, y = b;
    while (y != 0) {
        int r = x % y;
        x = y;
        y = r;
    }
    int g = x;
    long long l = (long long)a / g * b;

    printf("GCD: %d\n", g);
    printf("LCM: %lld\n", l);
    return 0;
}
Explanation: The original a and b are needed to compute the LCM, so run the Euclidean algorithm on copies (x, y). The LCM can be about 10 billion, which doesn't fit in an int, so compute it as long long. In the order a * b / g, the multiplication is likely to overflow, so divide first.
L13 Advanced

Problem 13. The Collatz problem

Starting from a positive integer N (1 ≤ N ≤ 100000), repeat "if it is even, divide by 2; if it is odd, multiply by 3 and add 1" until N becomes 1. Print the number of steps it takes to reach 1 and the largest value that appears along the way (including N itself).
Sample run (input is underlined)
6 Steps: 8 Max: 16
Your code
"Run" executes your code with the input above. "Check" tests it against 4 prepared inputs.
Loop with while (n != 1), and each time do steps++ and update the maximum. The values along the way can become hundreds of times larger than N, so it is safer to use long long.
#include <stdio.h>

int main(void) {
    long long n;
    scanf("%lld", &n);

    int steps = 0;
    long long max = n;
    while (n != 1) {
        if (n % 2 == 0) {
            n /= 2;
        } else {
            n = 3 * n + 1;
        }
        steps++;
        if (n > max) max = n;
    }
    printf("Steps: %d\n", steps);
    printf("Max: %lld\n", max);
    return 0;
}
Explanation: This is a typical while-loop problem where you don't know how many times you will repeat. If you don't start the maximum at N itself, the maximum is wrong when N=1. The values along the way get much larger than N (for N=77031 it reaches about 21.93 million, and with larger N it exceeds the int limit).

Review these lessons

← Back to all practice problems