SITERAW

Loops in C

Now that we've learned how to write conditions in C, it's time to discover how to create loops :)

What's a loop?

It's a way to repeat the same instructions multiple times. You'll see how incredibly useful this is, especially when we get to your first practical exercise after this chapter ;)

Take it easy: this part's going to be smooth. We tackled conditions and booleans in the last chapter — that was a hefty chunk to digest. But now, things are going to flow much more naturally.

Enjoy it while it lasts, because we'll soon dive into the advanced section of the tutorial... and trust me, you'll want to be well-prepared for what's coming next.

What's a loop?

Just like with conditions, there are several ways to create loops in C. In the end, it all boils down to the same goal: repeating a set of instructions a certain number of times.

We'll look at three common types of loops in C:

  • while
  • do... while
  • for

Regardless of which one you use, the logic is always the same. Here's what happens step by step:

  • The computer reads the instructions from top to bottom (as usual).
  • When it reaches the end of the loop, it jumps back to the start.
  • Then it reads the instructions again, top to bottom...
  • ...and loops back to the beginning once more.

Here's the catch: if you don't stop it, the computer will keep looping forever! And it's not the complaining type — it just does what you tell it to :p

And that's where conditions come back into play! When we write a loop, we always provide a condition. That condition basically means: "Keep looping as long as this is true."

There are different ways to go about it, as I mentioned. So let's not waste any more time and jump into the while loop in C :)

The while loop

Here's how a while loop is structured:

while (/* Condition */)
{
    // Instructions to repeat
}

It's that simple :D You're telling the computer: "As long as the condition is true, repeat the instructions inside the curly braces."

Let's do a quick test: we'll ask the user to type the number 21. As long as they don't type 21, we'll keep asking. The program will only stop once the user finally enters 21 (I know, I know):

int numberEntered = 0;

while (numberEntered != 21) { printf("Type the number 21! "); scanf("%d", &numberEntered); }

Here's what happened when I tested it:

Type the number 21! 10  
Type the number 21! 20  
Type the number 21! 30  
Type the number 21! 21

The program stopped after the user typed 21. This while loop keeps going as long as the user hasn't entered 21 — pretty straightforward.

Now let's try something a bit more interesting: we want our loop to run a specific number of times. To do that, we'll create a "counter" variable that starts at 0 and increases gradually. Remember incrementing? It just means adding 1 to a variable using variable++;.

Check out this snippet, and try to really understand how it works:

int counter = 0;

while (counter < 10) { printf("Welcome to SiteRaw!\n"); counter++; }

Output:

Welcome to SiteRaw!
Welcome to SiteRaw!
[...]
Welcome to SiteRaw!

This code prints "Welcome to SiteRaw!" ten times.

So how does it work exactly?

  • We start with a counter variable set to 0.
  • The while loop says: "Keep going while counter is less than 10." Since counter is 0, we enter the loop.
  • It prints "Welcome to SiteRaw!" using printf.
  • Then we increment the counter variable with counter++;. So it goes from 0 to 1.
  • We reach the end of the loop (the closing brace), so the computer goes back to the while. It checks again: "Is counter still less than 10?" Yup, it's 1 now. So we run the loop again.

And so on... counter goes from 0 to 1, 2, 3, ..., up to 9. When it finally reaches 10, the condition counter < 10 is no longer true. Since the condition is false, we exit the loop.

We could even print the value of counter each time to see how it changes:

int counter = 0;

while (counter < 10) { printf("The variable counter is %d\n", counter); counter++; }

Output:

The variable counter is 0  
The variable counter is 1  
The variable counter is 2  
The variable counter is 3  
The variable counter is 4  
The variable counter is 5  
The variable counter is 6  
The variable counter is 7  
The variable counter is 8  
The variable counter is 9

And there you go — if you got that, you've basically understood everything ;) Feel free to change the number of loops (e.g., use < 100 instead of < 10).

Honestly, this would've saved me a lot of time back in school when I had to write punishments out 100 times :-°

Watch out for infinite loops

Whenever you write a loop, always make sure it has a way to stop! If the condition stays true forever, your program will never end!

Here's an example of an infinite loop (do NOT copy this code):

//while (1)
{
    printf("Infinite loop\n");
}

Remember how booleans work: 1 means true, 0 means false. In this case, the condition is always true, so this program will keep printing "Infinite loop" forever!

To stop a program like that on Windows, you'll have to close the console window using the X in the top-right corner. On Linux, you can press Ctrl + C.

So please be careful: avoid falling into an infinite loop at all costs.

That said, infinite loops can be useful in some situations — we'll talk more about that later, especially when we start making games.

The do... while loop

This type of loop is very similar to the while loop, though it's a bit less commonly used in general. The only real difference is the position of the condition. Instead of being at the beginning of the loop, the condition comes at the end:

int counter = 0;

do { printf("Welcome to SiteRaw!\n"); counter++; } while (counter < 10);

So what difference does that make?

It's pretty simple: a while loop might never run at all if the condition is false right from the start. For instance, if we had set counter to 50 initially, the condition would be false from the get-go, and we'd never enter the loop.

But with a do... while loop, it's different: this kind of loop always runs at least once. That's because, as you can see, the check happens after the loop body. So even if counter starts at 50, the loop will still execute one time.

That makes do... while loops handy in situations where you want to make sure the loop body runs at least once. Though, to be honest, those cases are kind of rare ;)

There's one little quirk with the do... while loop that beginners often forget: there's a semicolon at the end! Don't forget to put a semicolon after the while, or your program will throw a compilation error.

The for loop

Technically, you can create any kind of loop you want using while.

But just like how we use switch as a more elegant way to handle multiple conditions, it's sometimes useful to have a more "compact" loop syntax that's quicker to write.

Enter the for loop — a staple in programming. I don't have exact stats on hand, but you'll probably end up using for loops just as often as while loops. So it's important to get comfortable with both.

As I mentioned earlier, a for loop is really just another way of writing a while loop.

Here's an example of a while loop we looked at earlier:

int counter = 0;

while (counter < 10) { printf("Welcome to SiteRaw!\n"); counter++; }

Now here's the same thing, written with a for loop:

int counter;

for (counter = 0 ; counter < 10 ; counter++) { printf("Welcome to SiteRaw!\n"); }

So what's different?

  • You'll notice we didn't initialize counter when declaring it (though we could have)
  • There's a lot going on between the parentheses after for (we'll break that down next)
  • There's no more counter++; inside the loop body (because it's now in the parentheses)

Let's take a closer look at what's inside the parentheses — this is where the real magic of for loops happens. You've got three compact instructions, separated by semicolons:

  • Initialization – This is where you set up your counter variable. In our example, we start counter at 0.
  • Condition – Just like in while, this condition decides whether the loop continues. As long as it's true, the loop keeps running.
  • Increment – This bit runs at the end of each loop cycle. Most of the time you'll use it to increment (++), but you could also decrement (--) or even do something like counter += 2; to count by twos.

So yeah, the for loop is really just a cleaner way to write everything in one place ;) Learn how to use it well — you're going to need it a lot!

Oh, and there's a fourth kind of loop: the infamous goto loop. But that one's a bit odd and not really used much nowadays. Like they say: "The fact that goto can do anything is exactly why we don't use it."

Learn C Programing for Beginners

Enjoyed this C / C++ course?

If you liked this lesson, you can find the book "Learn C Programing for Beginners" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete C / C++ workshop with many exclusive bonus chapters.

More information