A loop repeats a block of statements. The while and do–while loops repeat as long as a condition stays true, which suits tasks where the number of repetitions is not known in advance, such as reading input until the user enters 0.
The while loop
Syntax
while (condition) { body}
The condition is tested before each repetition. If it is true, the body runs and the condition is tested again; when it becomes false, control moves to the statement after the loop. If the condition is false at the start, the body never runs. Because the test happens on entry, while is called an entry-controlled loop.
Every loop needs something in its body that eventually makes the condition false; otherwise it is an infinite loop.
The do-while loop
Syntax
do { body} while (condition);
The body runs first and the condition is tested after each repetition, so the body always runs at least once. do–while is therefore an exit-controlled loop. Note the semicolon after while (condition).
It suits tasks that must happen at least once, such as showing a menu and then asking whether to show it again.
while versus do-while
Aspect
while
do-while
Test position
Before the body (entry-controlled)
After the body (exit-controlled)
Minimum executions
0
1
Semicolon after while (...)
No (would make an empty loop)
Required
Typical use
Read until a sentinel value, unknown count
Menus, input validation that must run once
Key takeaways
while is entry-controlled: the test comes first, so the body may run zero times.
do–while is exit-controlled: the body runs first, so it runs at least once.
The body must change something that eventually makes the condition false.
printf prints exactly what its format says, including spaces.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a while loop that adds the digits of a positive integer n (for example 472 → 13), and trace it for 472.
Show worked answer
int sum = 0; while (n > 0) { sum = sum + n % 10; n = n / 10; }. n % 10 gives the last digit and n / 10 removes it. Trace: n = 472 → sum = 2, n = 47; → sum = 2 + 7 = 9, n = 4; → sum = 9 + 4 = 13, n = 0; the test 0 > 0 fails. Result: 13.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/decision-and-loop-control-statements/the-while-and-do-while-loops/ to read this page.