C & C++ fundamentals / 07

while, break, and continue

Repeat statements with while loops, exit early with break, and skip to the next iteration with continue.

On this page

There are several kinds of loops. Two common ones are while and for. Like an if statement, a while loop checks a condition in parentheses before executing the block in braces. The difference is that it repeats the block until the condition becomes false.

You can also leave the loop explicitly with break;. Combine an if statement with break to stop when a particular condition is met:

#include <stdio.h>

int main()
{
    int a=0;

    while(a<100)
    {
        a++;
        printf("a\n");

        if(a == 90)
        {
            break;
        }
    }
    return 0;
}

The loop runs while a < 100. Each iteration increments a with the postfix increment operator and prints the letter a. When the value reaches 90, the if statement breaks out of the loop, before the counter reaches its usual limit.

Removing the early exit

If we comment out the if statement, the example becomes:

#include <stdio.h>

int main()
{
    int a=0;

    while(a<100)
    {
        a++;
        printf("a\n");

    /*    
        if(a == 90)
        {
            break;
        }
    */
    }
    return 0;
}

Now the loop ends because its own condition becomes false.

Editorial note: the original explanation said the counter finishes at 99. In this code, the final iteration increments it from 99 to 100 before the next condition check ends the loop. Also, printf("a\n") prints the literal letter, not the counter's numeric value.

Infinite loops and continue

Putting 1 in the condition—while (1)—creates an infinite loop. Without a way to exit, such as break, it continues running.

The continue statement skips the remaining statements in the current iteration and starts the next condition check. Here is another example:

#include <stdio.h>

int main()
{
    int a=0;

    while(1)
    {

        scanf("%d",&a);     
        printf("Hello World!\n"); 

        if(a == 1)
        {
            continue;
        }
        
        else 
        {
            break;
        }
        
    }
    return 0;
}

The integer a is read inside the loop, and the program prints Hello World!. It then checks the input: when a equals 1, execution continues with the next iteration. Any other value breaks out of the loop.

The next lesson introduces for loops.

Moved here from Tistory

I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.

The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.

Original post on Tistory English edition · Aug 30, 2026
← Back to all articles