C Language
4. Control Flow & LoopsBeginner9 min read

Loops in C: While, Do-While & For Loops

Iterate efficiently with for, while, and do-while loops. Learn loop control keywords: break, continue, and goto.

Key Takeaways & Core Concepts
  • for loops are ideal when the number of iterations is known ahead of time.
  • while loops are entry-controlled: condition checked before executing the body.
  • do-while loops are exit-controlled: guaranteed to execute at least once.
  • break terminates the enclosing loop immediately.
  • continue skips the rest of the current iteration and jumps to the next iteration.

Comparing the Three Loop Constructs in C

Loops repeat a block of code as long as a test condition remains true (non-zero).

  • For Loop: for (init; condition; update) { ... }
  • While Loop: while (condition) { ... } (Entry-controlled)
  • Do-While Loop: do { ... } while (condition); (Exit-controlled, runs at least once)
Comprehensive Loop Demonstration
1#include <stdio.h>
2
3int main(void) {
4 // 1. For loop with continue
5 printf("Printing even numbers up to 10:\n");
6 for (int i = 1; i <= 10; i++) {
7 if (i % 2 != 0) continue; // Skip odd numbers
8 printf("%d ", i);
9 }
10 printf("\n\n");
11
12 // 2. While loop with early break
13 printf("While loop searching for target:\n");
14 int count = 1;
15 while (count < 100) {
16 if (count == 5) {
17 printf("Found target %d! Breaking out of loop.\n", count);
18 break;
19 }
20 count++;
21 }
22 printf("\n");
23
24 // 3. Do-while loop guarantees at least one run
25 int number = 10;
26 do {
27 printf("Do-while executed once even though condition (number < 5) is FALSE!\n");
28 } while (number < 5);
29
30 return 0;
31}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
31 lines
Note: The do-while loop executes the body first, then checks the condition at the end.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

Which loop is guaranteed to execute its body at least once?

Beginner