Ad space (banner)
๐Ÿ”งC Lessons
Lesson 8 / 68

Loops (while statements)

This lesson covers repeating logic in C using a while loop, so you understand when to use it over a for loop. It's for anyone searching "C while loop usage."

A while statement repeats logic as long as a condition holds. The rule of thumb: use a for loop when you know the end condition ahead of time, and a while loop when you don't know exactly when it should stop.

The example initializes int i = 1, then loops on the condition while (i <= 5), incrementing i by 1 with i++ inside the loop. You can see the loop exits the moment the condition becomes false.

A common early mistake is forgetting to update the variable the condition depends on inside the loop. Forgetting the update step causes an infinite loop.

In real projects, while loops are used when the number of repetitions isn't known in advance โ€” repeatedly prompting until a user enters valid input, for example.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)