C Loops: for, while, do-while, break, continue & Control Flow
Welcome to Phase 5 (Part 1): C Loops, Iteration Mechanics & Control Flow Masterclass! In programming, repetitive manual execution violates the core DRY (Don't Repeat Yourself) principle. Loops allow your CPU to execute a block of instructions millions of times with microscopic precision and high performance. In this comprehensive guide, you will master the 3 structural pillars of every loop, the internal mechanics of the for loop, entry-controlled while loops vs exit-controlled do-while loops, control jump statements (break and continue), diagnosing infinite loop bugs, and traversing memory arrays and string buffers.
Oka task ni 1,000 times manually repeat cheyyakunda, automated loop construct dwara single line tho execute cheyyavachu. World lo prati loop (regardless of programming language) 3 Mandatory Components meedha run avthundhi:
- 1. Loop Initialization: Loop counter variable starting value ni set cheyyadam (e.g.
int i = 1;). - 2. Loop Condition: Prati iteration mundhu check chese boundary criteria (e.g.
i <= 10;). ConditionTRUEunnantha varaku loop run avthundhi. - 3. Loop Update (Increment / Decrement): Counter variable ni target value vaipu move cheyyadam (e.g.
i++). Missing update causes an Infinite Loop Bug!
for ( [1. Init] ; [2. Condition Check] ; [4. Update Counter] ) {
[3. Execute Loop Body Statements];
}
Flow Order: [1. Init] โโโบ [2. Check] (TRUE) โโโบ [3. Run Body] โโโบ [4. Update] โโโบ [2. Check again...]
Number of iterations mundhe thelisinappudu for loop best choice. C99 standard nunchi loop counter variable ni directly for header loni declare cheyyavachu (Block Scope):
#include <stdio.h>
int main(void) {
// Prints numbers from 1 to 5
for (int number = 1; number <= 5; number++) {
printf("%d\n", number);
}
return 0;
}
| Loop Construct | Condition Check Timing | Minimum Executions Guaranteed | Typical Real-World Use Case |
|---|---|---|---|
while Loop |
Entry-Controlled: Loop body execute avvaka mundhe condition check avthundhi. | 0 times (Condition first time fail ayithe body zero times run avthundhi). | File reading, network packet streaming, unknown iteration counts. |
do-while Loop |
Exit-Controlled: Loop body execute ayina tharvatha condition check avthundhi. | 1 time guaranteed (Even if condition is completely false!). | Interactive Console Menus (Prompt user at least once before checking choice). |
#include <stdio.h>
int main(void) {
int count = 10;
// while loop: condition is false (10 < 5), so body executes 0 times!
while (count < 5) {
printf("This while loop will NEVER print.\n");
count++;
}
// do-while loop: body executes 1 time BEFORE checking condition!
int val = 10;
do {
printf("do-while executes at least once! (val = %d)\n", val);
val++;
} while (val < 5); // โ ๏ธ Note the mandatory semicolon ';' at the end!
return 0;
}
โก break vs continue Control Jump Commands
โข break;: Loop execution ni ventane terminate chesi loop outer scope ki jump chesthundhi (Search element dorikinappudu loop nunchi exit avvadaniki).
โข continue;: Current iteration lo kindha unna code ni skip chesi, ventane next iteration (update step) ki jump chesthundhi (Even numbers filter cheyyadaniki).
#include <stdio.h>
int main(void) {
char message[] = "Hello C!";
int scores[] = {85, 92, 40, 78, 95};
int size = sizeof(scores) / sizeof(scores[0]);
// 1. Looping through string until null-terminator '\0'
printf("Characters in message: ");
for (int i = 0; message[i] != '\0'; i++) {
printf("[%c] ", message[i]);
}
printf("\n");
// 2. Looping through array with continue (skip failing grades < 50)
printf("Passing Scores: ");
for (int i = 0; i < size; i++) {
if (scores[i] < 50) {
continue; // Skip failing score
}
printf("%d ", scores[i]);
}
printf("\n");
return 0;
}
Run this 1 to 20 even number accumulator loop in our online C compiler:
#include <stdio.h>
int main(void) {
int sum = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
sum += i;
}
}
printf("Sum of even numbers (1 to 20) = %d\n", sum);
return 0;
}