Nearby lessons

45 of 124

C - Do...while Loop

Do...while Loop is one of the foundational topics in C programming. This lesson explains The do-while Loop with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The do-while Loop

The do-while loop runs the body first, then checks the condition. So its body runs at least once even if the condition is false.

In simple words: do-while is "enter first, then check the door" — you get inside at least once, then the condition decides whether you come back in.
Example01
CCode Cell
1do {
2 // body
3} while (condition);

The do-while Loop

Here the user is asked again and again until a positive number comes — the do-while is perfect for ask-at-least-once situations.

Example02
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int n;
6 do {
7 printf("Enter a positive number: ");
8 scanf("%d", &n);
9 } while (n <= 0); // repeat until positive
10 
11 printf("You entered %d\n", n);
12}
📝 Key Takeaways
  • while checks first; do-while runs at least once; for gathers start/condition/update.
  • for is best when you know the number of iterations.
  • break stops the loop; continue skips one round.
  • Nested loops: inner loop completes for each outer round.
  • Pattern programs = outer loop (rows) + inner loop (columns).
  • Never forget the update (i++) — else you get an infinite loop.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1