Loops in C

Sometimes you need to do the same thing many times. Print 100 numbers. Check every item in a list. Keep asking until the user types something valid.

You could copy and paste the same code 100 times. But that’s silly.

Loops repeat code over and over. You write it once, and the computer runs it many times.

The while Loop

The while loop keeps going as long as a condition is true:

int count = 0;

while (count < 5) {
    printf("%d\n", count);
    count++;  // Don't forget this!
}

This prints:

0
1
2
3
4

Here’s what happens:

  1. Check: is count < 5? Yes (0 < 5), so run the code inside
  2. Print 0, then add 1 to count (now count is 1)
  3. Check: is count < 5? Yes (1 < 5), so run the code inside
  4. Print 1, then add 1 to count (now count is 2)
  5. …and so on until count reaches 5
  6. Check: is count < 5? No (5 is not less than 5), so stop

Infinite Loops

If the condition never becomes false, the loop runs forever:

while (1) {
    printf("This never stops!\n");
}

Since 1 is always “true” (remember, anything non-zero is true), this keeps going forever.

If your program freezes, you probably have an infinite loop. Press Ctrl+C to stop it.

The most common cause: forgetting to change the loop variable.

int count = 0;
while (count < 5) {
    printf("%d\n", count);
    // Oops! Forgot count++;
    // count stays 0 forever!
}

The do-while Loop

Regular while checks the condition first. do-while runs the code first, then checks:

int number;

do {
    printf("Enter a positive number: ");
    scanf("%d", &number);
} while (number <= 0);

printf("You entered: %d\n", number);

This is useful when you want the code to run at least once. Here, we ask for input at least once, then keep asking if they enter something invalid.

See the semicolon after while (number <= 0);? That’s required for do-while. Regular while doesn’t need it.

The for Loop

The for loop is the most common loop. It puts three things on one line:

  1. Starting value
  2. Condition to keep going
  3. What to change each time
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

This does exactly the same thing as:

int i = 0;        // Start at 0
while (i < 5) {   // Keep going while i < 5
    printf("%d\n", i);
    i++;          // Add 1 each time
}

The for loop is just shorter to write.

Breaking Down the for Loop

for (int i = 0; i < 5; i++) {
//   ^^^^^^^^^  ^^^^^  ^^^
//      |         |     |
//      |         |     +-- After each loop: add 1 to i
//      |         +-------- Keep going while: i < 5
//      +------------------ Start with: i = 0

The variable i is a tradition. It stands for “index” or “iterator.” But you can name it anything.

Counting Different Ways

Count backwards:

for (int i = 5; i > 0; i--) {
    printf("%d\n", i);  // Prints: 5 4 3 2 1
}

Count by twos:

for (int i = 0; i < 10; i += 2) {
    printf("%d\n", i);  // Prints: 0 2 4 6 8
}

Count by tens:

for (int i = 10; i <= 100; i += 10) {
    printf("%d\n", i);  // Prints: 10 20 30 ... 100
}

Looping Through Arrays

Loops are perfect for going through every item in an array:

int scores[] = {85, 90, 78, 92, 88};
int length = sizeof(scores) / sizeof(scores[0]);

for (int i = 0; i < length; i++) {
    printf("Score %d: %d\n", i + 1, scores[i]);
}

Output:

Score 1: 85
Score 2: 90
Score 3: 78
Score 4: 92
Score 5: 88

This is why arrays start at position 0. The loop counter i matches the array positions perfectly: 0, 1, 2, 3, 4.

Escaping Loops Early

break: Stop the Loop Completely

for (int i = 0; i < 100; i++) {
    if (i == 5) {
        break;  // Exit the loop right now
    }
    printf("%d\n", i);
}
// Prints: 0 1 2 3 4 (then stops)

break says “I’m done, get me out of here.”

continue: Skip to the Next Round

for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue;  // Skip the rest of this round
    }
    printf("%d\n", i);
}
// Prints: 0 1 3 4 (skips 2)

continue says “skip the rest of this round, but keep looping.”

Loops Inside Loops

You can put a loop inside another loop:

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 3; col++) {
        printf("(%d,%d) ", row, col);
    }
    printf("\n");
}

Output:

(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

The outer loop runs 3 times. Each time it runs, the inner loop runs 3 times. That’s 9 total prints.

This is useful for grids, tables, and two-dimensional patterns.

Complete Example: Number Guessing Game

Let’s build a simple game:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    // Set up random numbers (don't worry about how this works)
    srand(time(NULL));
    int secret = rand() % 100 + 1;  // Random number from 1 to 100

    int guess;
    int attempts = 0;

    printf("I'm thinking of a number between 1 and 100.\n");

    do {
        printf("Your guess: ");
        scanf("%d", &guess);
        attempts++;

        if (guess < secret) {
            printf("Too low! Try higher.\n");
        } else if (guess > secret) {
            printf("Too high! Try lower.\n");
        } else {
            printf("Correct! You got it in %d attempts.\n", attempts);
        }
    } while (guess != secret);

    return 0;
}

Compile and run:

gcc -Wall -o guess guess.c
./guess

Complete Example: Finding the Sum

Calculate the sum of numbers 1 through 100:

#include <stdio.h>

int main(void) {
    int sum = 0;

    for (int i = 1; i <= 100; i++) {
        sum = sum + i;
    }

    printf("Sum of 1 to 100 is: %d\n", sum);  // 5050

    return 0;
}

Try It Yourself

  1. Print all even numbers from 1 to 100 using a loop
  2. Write a program that finds the largest number in an array of 5 numbers
  3. Modify the guessing game to give hints like “very close!” when within 5
  4. Challenge: Write FizzBuzz - print numbers 1 to 100, but print “Fizz” for multiples of 3, “Buzz” for multiples of 5, and “FizzBuzz” for multiples of both

Common Mistakes

  • Off-by-one errors: i <= 5 vs i < 5 - one gives you 6 iterations, one gives 5
  • Infinite loops: Forgetting to change the loop variable
  • Wrong condition: Using > when you meant <
  • Forgetting curly braces: Without { }, only the next line is part of the loop
// Wrong - only the first printf is in the loop
for (int i = 0; i < 5; i++)
    printf("In the loop: %d\n", i);
    printf("NOT in the loop!\n");  // Runs AFTER the loop ends, once

// Right - both statements are in the loop
for (int i = 0; i < 5; i++) {
    printf("In the loop: %d\n", i);
    printf("Also in the loop!\n");  // Runs 5 times
}

Which Loop Should I Use?

  • for: When you know how many times to loop (counting, going through arrays)
  • while: When you don’t know how many times (keep going until some condition)
  • do-while: When you need to run at least once (input validation)

Most of the time, for is the right choice.

Next Up

In Part 8, we’ll learn about functions - how to organize your code into reusable pieces. Instead of copying and pasting, you’ll write code once and use it wherever you need it.


Enjoyed This?

If this helped something click, subscribe to my YouTube channel. More content like this, same approach - making things stick without insulting your intelligence. It’s free, it helps more people find this stuff, and it tells me what’s worth making more of.