Skip to content

Part 1 · Lesson 6

Loops

  • interactive
On this page

What you'll learn: repeating code with for, while and do-while loops, and reading input in a loop without hanging on bad input or end of input.

Before you start: Lessons 1-5.

Imagine you needed to print "Hello!" five times. You could write:

printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");
printf("Hello!\n");

This is tedious and not scalable. What if you needed to do it 500 times? This is where LOOPS come in. A LOOP is a programming structure that repeats a sequence of instructions until a specific condition is met. Each single execution of the loop's body is called an ITERATION.

C has three main types of loops:

  1. The for loop
  2. The while loop
  3. The do-while loop

The for loop is ideal when you know exactly how many times you want to repeat a block of code. It has a very specific structure with three parts inside its parentheses, separated by semicolons.

for (INITIALIZATION; CONDITION; POST-ITERATION)
{
    // Code to be repeated
}
  1. INITIALIZATION: A statement that runs only ONCE before the loop starts. It's typically used to declare and initialize a counter variable.
  2. CONDITION: An expression that is checked BEFORE each iteration. If the condition is true, the loop body runs. If it's false, the loop terminates.
  3. POST-ITERATION: A statement that runs AFTER each iteration. It's typically used to increment or decrement the counter variable. i++ is shorthand for i = i + 1, and i-- for i = i - 1.

The lesson counts down from 5:

for (int i = 5; i > 0; i--)
{
    printf("%d...\n", i);
}

It prints 5, 4, 3, 2 and 1. When i reaches 0, the condition i > 0 is false and the loop ends.

The while loop is simpler. It repeats a block of code AS LONG AS its condition remains true. It's useful when you don't know the exact number of iterations beforehand.

while (condition)
{
    // Code to be repeated
}

The condition is checked BEFORE each iteration. The lesson's menu keeps asking until the user chooses 4:

int menu_choice = 0;
while (menu_choice != 4)
{
    // print the menu and read a new menu_choice
}

CRITICAL: You must ensure that something inside the loop's body will eventually make the condition false. Otherwise, you will create an INFINITE LOOP, and your program will never end!

The do-while loop is a variation of the while loop. The key difference is that the condition is checked AT THE END of the loop's body.

do
{
    // Code to be repeated
} while (condition);

This means a do-while loop is GUARANTEED to execute at least once. Note the semicolon after the condition.

This makes it perfect for situations like input validation, where you need to get the input first before you can check if it's valid.

Reading Input Inside a Loop

Loops and scanf together are a classic source of infinite loops, so this lesson handles every result scanf can return:

  • 1: the number was read. Use it.
  • EOF: the input has ended (for example, Ctrl+D), so no more input will ever arrive. Leave the loop instead of asking forever.
  • 0: the user typed something that is not a number, like abc. scanf leaves that text waiting in the INPUT BUFFER, so the next call would fail on the same text again. Throw the rest of the line away first:
int leftover = getchar();
while (leftover != '\n' && leftover != EOF)
{
    leftover = getchar();
}

getchar() reads ONE character and returns it as an int. It returns an int rather than a char so that it can also return EOF.

Full Source

6_loops.c 226 lines Download View on GitHub
/**
 * @file 6_loops.c
 * @brief Part 1, Lesson 6: Loops
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces loops, which are control structures that allow
 * a block of code to be executed repeatedly.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Imagine you needed to print "Hello!" five times. You could write:
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 * printf("Hello!\n");
 *
 * This is tedious and not scalable. What if you needed to do it 500 times?
 * This is where LOOPS come in. A LOOP is a programming structure that repeats a
 * sequence of instructions until a specific condition is met. Each single
 * execution of the loop's body is called an ITERATION.
 *
 * C has three main types of loops:
 * 1. The `for` loop
 * 2. The `while` loop
 * 3. The `do-while` loop
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: The `for` Loop ---

    /*
     * The `for` loop is ideal when you know exactly how many times you want to
     * repeat a block of code. It has a very specific structure with three parts
     * inside its parentheses, separated by semicolons.
     *
     * for (INITIALIZATION; CONDITION; POST-ITERATION) {
     *     // Code to be repeated
     * }
     *
     * 1. INITIALIZATION: A statement that runs only ONCE before the loop starts.
     *    It's typically used to declare and initialize a counter variable.
     * 2. CONDITION: An expression that is checked BEFORE each iteration. If the
     *    condition is true, the loop body runs. If it's false, the loop terminates.
     * 3. POST-ITERATION: A statement that runs AFTER each iteration. It's
     *    typically used to increment or decrement the counter variable. `i++` is
     *    shorthand for `i = i + 1`.
     */
    printf("--- Part 1: The 'for' Loop (Countdown) ---\n");

    // Let's create a countdown from 5 down to 1.
    // Initialization: `int i = 5`
    // Condition: `i > 0` (loop as long as i is greater than 0)
    // Post-iteration: `i--` (decrement i by 1 after each loop; shorthand for i = i - 1)
    for (int i = 5; i > 0; i--)
    {
        printf("%d...\n", i);
    }
    printf("Blast off!\n\n");

    // --- Part 2: The `while` Loop ---

    /*
     * The `while` loop is simpler. It repeats a block of code AS LONG AS its
     * condition remains true. It's useful when you don't know the exact number
     * of iterations beforehand.
     *
     * while (condition) {
     *     // Code to be repeated
     * }
     *
     * The condition is checked BEFORE each iteration.
     *
     * CRITICAL: You must ensure that something inside the loop's body will
     * eventually make the condition false. Otherwise, you will create an
     * INFINITE LOOP, and your program will never end!
     */
    printf("--- Part 2: The 'while' Loop (Simple Menu) ---\n");

    int menu_choice = 0;

    // Loop as long as the user has not chosen option 4 to quit.
    while (menu_choice != 4)
    {
        printf("Menu:\n");
        printf("1. Start New Game\n");
        printf("2. Load Game\n");
        printf("3. Options\n");
        printf("4. Quit\n");
        printf("Enter your choice: ");

        /*
         * Reading input inside a loop needs extra care. As you saw in Lesson 3,
         * `scanf` returns how many items it read. We save that in a variable so
         * we can handle each of its three possible outcomes.
         */
        int items_read = scanf("%d", &menu_choice); // This updates the loop variable.

        if (items_read == 1)
        {
            printf("You chose: %d\n\n", menu_choice);
        }
        else if (items_read == EOF)
        {
            /*
             * The input has ended (for example, the user pressed Ctrl+D), so no
             * more choices will ever arrive. If we did nothing, `menu_choice`
             * would never become 4 and this would be an INFINITE LOOP. Setting
             * it to 4 makes the loop condition false, so the loop ends.
             */
            printf("\nNo more input. Quitting.\n");
            menu_choice = 4;
        }
        else
        {
            /*
             * The user typed something that is not a number, like `abc`.
             * `scanf` refuses to read it and leaves it waiting in the INPUT
             * BUFFER. If we just looped back, the next `scanf` would see the
             * same `abc`, fail again, and loop forever!
             *
             * To fix this, we throw away everything up to the end of the line.
             * `getchar()` reads ONE character from the input and returns it. We
             * keep reading until we reach the newline `'\n'` (the user pressed
             * Enter) or `EOF` (the input ended). `getchar` returns an `int`, not
             * a `char`, so that it can also return `EOF`.
             */
            printf("That was not a number. Please try again.\n\n");
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
        }
    }
    printf("Thanks for playing!\n\n");

    // --- Part 3: The `do-while` Loop ---

    /*
     * The `do-while` loop is a variation of the `while` loop. The key difference
     * is that the condition is checked AT THE END of the loop's body.
     *
     * This means a `do-while` loop is GUARANTEED to execute at least once.
     *
     * This makes it perfect for situations like input validation, where you need
     * to get the input first *before* you can check if it's valid.
     */
    printf("--- Part 3: The 'do-while' Loop (Input Validation) ---\n");
    int secret_number = 0;

    do
    {
        printf("Please enter a number between 1 and 10: ");
        int items_read = scanf("%d", &secret_number);

        if (items_read == EOF)
        {
            // No input left, so we can never get a valid number. Stop here.
            printf("\nNo more input. Exiting.\n");
            return 1;
        }
        if (items_read == 0)
        {
            // Not a number. Throw away the rest of the line, just like above,
            // and set an invalid value so the loop asks again.
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
            secret_number = 0;
        }

        // This check happens AFTER the user has already entered a number.
        if (secret_number < 1 || secret_number > 10)
        {
            printf("Invalid input. Please try again.\n");
        }

    } while (secret_number < 1 || secret_number > 10); // The condition is checked here.

    printf("You successfully entered the number %d.\n", secret_number);

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned how to make your program perform repetitive tasks.
 *
 * Key Takeaways:
 * - Loops are used to execute a block of code multiple times.
 * - The `for` loop is great for when you know the number of iterations in advance.
 *   It consists of an initializer, a condition, and a post-iteration step.
 * - The `while` loop is great for when you want to loop as long as a condition is
 *   true, and the number of iterations isn't fixed.
 * - The `do-while` loop is similar to `while`, but it always executes its body at
 *   least once because the condition is checked at the end.
 * - When a loop reads input, handle every result `scanf` can return. Bad input
 *   stays in the input buffer until you discard it, and `EOF` means no more input
 *   will ever arrive. Ignoring either one is a classic cause of infinite loops.
 *
 * Mastering loops is a massive step towards writing complex and useful programs.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the GCC compiler to create an executable file:
 *    `gcc -Wall -Wextra -std=c17 -o 6_loops 6_loops.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./6_loops`
 *    - On Windows (WSL): `./6_loops`
 */

How to Compile and Run

Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.

Once, before your first lesson

Install Apple's command line tools. They include the cc compiler: xcode-select --install

New to the terminal? The setup guide walks through it.

Build

$ cc -Wall -Wextra -std=c17 -o 6_loops 6_loops.c

Run

$ ./6_loops
  • Run these commands in the folder that holds the lesson's file. Download it as a zip.
  • The program waits for your input: type an answer and press Enter.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Print the multiplication table for a number the user enters, from 1 times to 10 times.
  2. Use a while loop to add up numbers the user types until they enter 0, then print the total.
  3. Write a number-guessing game: keep asking until the user types 7, and count the guesses. Make sure garbage input and Ctrl+D do not make it loop forever.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/06-loops/ in the repository and on this lesson's page on the website.

Solutions

One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.

Show the solution to exercise 1
1_multiplication_table.c 46 lines View on GitHub
/**
 * @file 1_multiplication_table.c
 * @brief Lesson 6, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Print the multiplication table for a number the user enters, from 1 times
 * to 10 times.
 */

#include <stdio.h>

int main(void)
{
    int number = 0;

    printf("Which multiplication table would you like? ");
    if (scanf("%d", &number) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    // We know in advance how many times to repeat (10), so `for` is the
    // right loop. The counter `i` is also the number we multiply by.
    // `i <= 10` (not `i < 10`) makes the last line "10 times".
    for (int i = 1; i <= 10; i++)
    {
        // `%2d` prints the number in a field at least 2 characters wide, so
        // the single digits line up with the 10.
        printf("%2d x %d = %d\n", i, number, i * number);
    }

    return 0;
}

/*
 * A loop that runs one time too many or too few is called an OFF-BY-ONE
 * error, and it is the most common loop bug there is. Check the first and
 * last lines of the output: they should be "1 x" and "10 x".
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_multiplication_table 1_multiplication_table.c
 *   ./1_multiplication_table
 */
Show the solution to exercise 2
2_running_total.c 71 lines View on GitHub
/**
 * @file 2_running_total.c
 * @brief Lesson 6, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Use a `while` loop to add up numbers the user types until they enter 0,
 * then print the total.
 */

#include <stdio.h>

int main(void)
{
    int total = 0;

    // The loop runs while `number` is not 0, and the condition is checked
    // BEFORE the first pass. So `number` must start as anything except 0,
    // or the loop would never run at all.
    int number = 1;

    while (number != 0)
    {
        printf("Enter a number (0 to stop): ");
        int items_read = scanf("%d", &number);

        if (items_read == 1)
        {
            // Adding the final 0 changes nothing, so it needs no special case.
            total = total + number;
        }
        else if (items_read == EOF)
        {
            // No input is left. Set the value that ends the loop, as the
            // lesson's menu does.
            printf("\nNo more input.\n");
            number = 0;
        }
        else
        {
            // Not a number. The bad text is still in the input buffer, so
            // read and discard it up to the end of the line, or the next
            // `scanf` would fail on it again, forever.
            printf("That was not a number. Please try again.\n");
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
        }
    }

    printf("The total is %d.\n", total);

    return 0;
}

/*
 * THINGS TO TRY
 *
 * - 5, 10, -3, 0 prints 12.
 * - 0 straight away prints 0: the loop body runs once and adds nothing.
 * - 5, abc, 10, 0 prints 15: the bad line is skipped and `number` keeps its
 *   old value (5, not 0), so the loop carries on.
 * - 5, then Ctrl+D prints 5.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_running_total 2_running_total.c
 *   ./2_running_total
 */
Show the solution to exercise 3
3_guessing_game.c 80 lines View on GitHub
/**
 * @file 3_guessing_game.c
 * @brief Lesson 6, Exercise 3: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Write a number-guessing game: keep asking until the user types 7, and count
 * the guesses. Make sure garbage input and Ctrl+D do not make it loop
 * forever.
 */

#include <stdio.h>

int main(void)
{
    int guess = 0;
    int guess_count = 0;

    // The player must guess at least once, so the question comes before the
    // test. That is what `do-while` is for.
    do
    {
        printf("Guess the number: ");
        int items_read = scanf("%d", &guess);

        if (items_read == EOF)
        {
            // Ctrl+D: no more guesses can ever arrive. Without this check
            // every later `scanf` would fail the same way and the loop
            // would spin forever.
            printf("\nNo more input. The number was 7.\n");
            return 1;
        }

        if (items_read == 0)
        {
            // Garbage such as "seven". Throw the rest of the line away so
            // the next `scanf` starts on fresh input, and do not count it
            // as a guess.
            int leftover = getchar();
            while (leftover != '\n' && leftover != EOF)
            {
                leftover = getchar();
            }
            printf("Please type a whole number.\n");
            guess = 0; // Anything but 7, so the loop asks again.
        }
        else
        {
            guess_count++;
            if (guess != 7)
            {
                printf("No, try again.\n");
            }
        }

    } while (guess != 7);

    printf("Correct! You needed %d guesses.\n", guess_count);

    return 0;
}

/*
 * THE TWO WAYS THIS LOOP COULD HANG
 *
 * 1. Bad text stays in the input buffer. `scanf("%d")` stops at the first
 *    character that cannot be part of a number and leaves it there. Ask
 *    again without removing it and `scanf` fails on the same character,
 *    again and again. The `getchar` loop removes it.
 * 2. Input ends. At end of input every read fails at once, so a loop that
 *    only says "try again" never stops. The `EOF` check ends the program.
 *
 * Test both: type `seven`, then press Ctrl+D on a later run.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_guessing_game 3_guessing_game.c
 *   ./3_guessing_game
 */

Finished this lesson?

Mark it complete to track your progress through the course.

Search the course

Type at least two letters. Press / anywhere to search.

↑ ↓ to choose, Enter to open. On a lesson, j and k go to the next and previous lesson.