Skip to main content

Control Flow

Loops

Master Types of Loops, while vs do-while vs for, Nested Loops, Patterns, and break / continue using LEARNCODEGURU’s 6-level learning model.

Level 1 Basics Content

C Loops Overview

Loops (iteration) repeat a block of statements while a condition holds. In C, the main loop forms are while, do-while, and for. You also use break and continue to control early exit or skip.

This level covers why loops matter, each loop type with syntax and examples, a comparison table, nested loops, break / continue basics, and one complete sample program.

Topic 1

Overview — iteration & why loops

Without loops you would copy-paste the same statements dozens of times. Loops let you repeat work with a changing counter, until a condition fails, or until the user says stop.

  • Iteration — one pass through the loop body
  • Condition — expression tested to decide whether to keep looping (non-zero = true)
  • Control variable — often a counter like i that updates each pass
  • Infinite loop — condition never becomes false (sometimes intentional with break)
Iteration in C: the three loop types — while and for as entry-controlled loops that test the condition before the body, and do-while as an exit-controlled loop that runs the body at least once — showing initialisation, condition check, body, and update.
Loops in C — how initialisation, condition, body, and update repeat work
Init → check condition → body → update → check again → … → exit when false
Topic 2

while loop

A while loop is entry-controlled: it checks the condition first. If the condition is false at the start, the body never runs.

Syntax:


while (condition) {
    /* statements repeated while condition is true */
}

Example — print 1 to 5:


int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}
Use when: you may need zero iterations, or the count is not known up front (read until sentinel, process until empty).
Topic 3

do-while loop

A do-while loop is exit-controlled: the body runs first, then the condition is checked. The body always executes at least once.

Syntax:


do {
    /* statements — run at least once */
} while (condition);

Example — menu-style repeat:


int choice;
do {
    printf("1.Hello  2.Exit: ");
    scanf("%d", &choice);
} while (choice != 2);
Use when: you must show a prompt / run logic once before deciding whether to repeat (menus, “try again?”).
Topic 4

for loop

A for loop packs init, condition, and update in one header. It is also entry-controlled — ideal when the number of iterations is known or easy to express with a counter.

Syntax:


for (init; condition; update) {
    /* loop body */
}

Example — print 1 to 5:


int i;
for (i = 1; i <= 5; i++)
    printf("%d ", i);
Infinite loop sketch: for (;;) or while (1) runs until break / return. Use deliberately, not by accident (forgotten update).
Topic 5

Comparison — while vs do-while vs for

Feature while do-while for
Condition check timing Before body (entry) After body (exit) Before body (entry)
Body runs at least once? No Yes No
Typical use Unknown count; sentinel Menus; must-run-once Known count; counters
Use case highlight Read until end / flag Repeat until valid choice 1..n, arrays, patterns
Syntax sketch while (cond) { … } do { … } while (cond); for (i; cond; i++) { … }
Topic 6

Nested loops — intro

A nested loop places one loop inside another. The outer loop often controls rows; the inner loop controls columns (or symbols on that row).

Example — 3×4 rectangle of stars:


int row, col;
for (row = 1; row <= 3; row++) {
    for (col = 1; col <= 4; col++)
        printf("*");
    printf("\n");
}
Output is three lines of four stars each. Inner loop finishes a full row before the outer loop advances to the next row.
Topic 7

break and continue — basics

break leaves the innermost loop immediately. continue skips the rest of the current iteration and starts the next one.

break example:


for (int i = 1; i <= 10; i++) {
    if (i == 5)
        break;           /* stop loop when i is 5 */
    printf("%d ", i);
}
/* prints: 1 2 3 4 */

continue example:


for (int i = 1; i <= 5; i++) {
    if (i == 3)
        continue;        /* skip printing 3 */
    printf("%d ", i);
}
/* prints: 1 2 4 5 */
Example

Sample program — sum 1 to n with for

This complete program reads n and prints the sum of integers from 1 through n:


/* Loops — for loop sum 1..n sample */
#include <stdio.h>

int main(void) {
    int n, i, sum = 0;

    printf("Enter n: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
        sum = sum + i;

    printf("Sum = %d\n", sum);
    return 0;
}
What to observe: init sets i = 1, condition keeps going while i <= n, update does i++ after each addition. Same idea works to print 1..10.

Level 2 Advanced Content

Going deeper into loops

Level 1 showed the forms. Level 2 explains entry vs exit control, the three parts of for, nested-loop complexity and shadowing, pattern-building, how break / continue / return differ, intentional infinite loops, and an optional while vs do-while flowchart.

Topic 1

Entry-controlled vs exit-controlled loops

  • Entry-controlled — while, for: test first; body may run zero times
  • Exit-controlled — do-while: body first; then test; body runs ≥ 1 time
  • Choose entry-controlled when “do nothing if already done” is correct
  • Choose exit-controlled when the first pass must happen (show menu, read then validate)
Kind Loops When body can be skipped
Entry-controlled while, for Yes — if condition is false on entry
Exit-controlled do-while No — first iteration always runs
Topic 2

for loop parts — init; condition; update

Each header slot is optional. Empty condition means “always true” (infinite until break).

  • init — runs once before the loop (e.g. i = 0)
  • condition — checked before each iteration; empty ⇒ forever
  • update — runs after each body (e.g. i++), including after continue
  • Empty expressions: for (; i < n; ) or for (;;) are legal

int i = 0;
for (; i < 3; ) {          /* init done outside; update in body */
    printf("%d ", i);
    i++;
}

for (;;) {                     /* intentional infinite loop */
    /* ... break when done ... */
    break;
}
Topic 3

Nested loops — O(n²) intuition & shadowing

If the outer loop runs n times and the inner loop runs n times each, the body runs about n × n times — often described as O(n²) time. Triple nesting is roughly O(n³). That is why nested loops on large n can feel slow.

  • Prefer distinct names: row / col instead of two is
  • C99 nested for (int i = ...) inside another i shadows the outer variable
  • Reusing one i for both loops without care can break the outer counter
Interview tip: for output with nested loops, fix the outer value, then walk the full inner loop, then advance outer — never skip counting inner iterations.
Topic 4

Pattern building — rows / cols thinking

Almost every star or number pattern follows: outer = rows, inner = what to print on that row (stars, digits, or spaces then stars).

1) Right triangle of stars (n = 4):


/* Row i prints i stars */
for (int row = 1; row <= n; row++) {
    for (int col = 1; col <= row; col++)
        printf("*");
    printf("\n");
}
/* *   **   ***   **** */

2) Number triangle:


for (int row = 1; row <= n; row++) {
    for (int col = 1; col <= row; col++)
        printf("%d ", col);
    printf("\n");
}
/* 1 / 1 2 / 1 2 3 / ... */

3) Inverted star triangle:


for (int row = n; row >= 1; row--) {
    for (int col = 1; col <= row; col++)
        printf("*");
    printf("\n");
}
Approach: draw the output for n = 3, count symbols per row, then set the inner loop bound to that count (often row or n - row + 1).
Topic 5

break vs continue vs return

Keyword Effect Scope
break Exit the innermost loop or switch now One loop / switch only
continue Skip rest of this iteration; next iteration Innermost loop; for still runs update
return Leave the whole function immediately Function (e.g. main); code after loop does not run
Topic 6

Infinite loops — intentional stop

Infinite loops are useful for interactive menus or servers — but only if you plan an exit:

  • while (1) { … if (done) break; }
  • for (;;) { … if (quit) return 0; }
  • Accidental infinity: forgotten i++, wrong condition, or continue skipping the update in while

while (1) {
    printf("Enter 0 to stop: ");
    scanf("%d", &x);
    if (x == 0)
        break;              /* intentional exit */
}
Topic 7

Optional flowchart — while vs do-while

How the two loops decide whether the body runs:

1 while — check first Condition false? → skip body entirely. True? → body → update → check again.
2 do-while — body first Always run body once → then check condition → repeat if true.
3 Pick by “must run once?” Yes → do-while. No / maybe zero times → while or for.

Level 3 C Tricky Interview Points

Advanced tricky interview points on while / do-while / for, off-by-one, for(;;), break / continue, nested scope, and patterns.

Tricky Interview Point-1:

for (;;); is an infinite loop — empty condition is always true

Omitting the condition in for (init; ; update) means “always true.” Combined with an empty body semicolon, for (;;); spins forever. Interviewers ask you to spot this and to exit with break or return when the loop is intentional.

Tricky Interview Point-2:

Off-by-one: i <= n vs i < n changes iteration count

for (i = 0; i < n; i++) runs n times; for (i = 1; i <= n; i++) also runs n times but with different values. Mixing 0-based and 1-based bounds is the classic off-by-one bug — count iterations on paper before coding.

Tricky Interview Point-3:

while (n--); drains n then exits — empty body is easy to miss

A semicolon after while (cond) makes an empty loop body. while (n--); still evaluates and updates n until the condition becomes false. Trace post-decrement carefully: the old value is tested, then n decreases.

Tricky Interview Point-4:

do-while always runs the body once — even if condition starts false

Unlike while and for (entry-controlled), do-while checks after the body. If you need “run at least once” (menus, retry prompts), do-while fits; if the body must never run when the condition is initially false, use while or for.

Tricky Interview Point-5:

break exits only the innermost loop / switch

In nested loops, break leaves the inner loop; the outer loop continues. To escape multiple levels you need a flag, goto (rare), or restructure. Interview output questions often hide a break inside the inner for.

Tricky Interview Point-6:

continue skips to the next iteration — for still runs the update

In a for loop, continue jumps to the update expression (i++), then rechecks the condition. In while/do-while, continue jumps to the condition check — so you must update the control variable before continue or you can infinite-loop.

Tricky Interview Point-7:

Nested loop variable reuse / shadowing confuses output

Declaring int i in both outer and inner for (C99+) shadows the outer i inside the inner block. Reusing one i across both loops without redeclaration can corrupt the outer counter. Prefer distinct names: row and col.

Tricky Interview Point-8:

for (i = 0; i < n; i++) body runs 0 times when n is 0 or negative

If the condition is false on entry, the body never executes. Interviewers contrast this with do-while. Always state assumptions about n (n > 0) when predicting output.

Tricky Interview Point-9:

Comma operator in for init/update packs multiple expressions

for (i = 0, j = n - 1; i < j; i++, j--) is valid: commas sequence expressions; the condition is still a single expression. The value of a comma expression is the rightmost sub-expression — useful but easy to misread.

Tricky Interview Point-10:

Infinite while (1) needs an intentional exit path

while (1) { ... break; } or while (1) { if (done) return 0; } is idiomatic for servers/menus. Without break, return, exit, or a condition that becomes false, the program hangs — a common “find the bug” question.

Tricky Interview Point-11:

Pattern rows/cols: outer = rows, inner = columns (or stars per row)

For a right triangle of height n, outer loop runs n rows; inner loop runs i stars on row i (1-based) or i+1 (0-based). Wrong inner bound is the usual mistake — draw a 3-row grid before writing code.

Tricky Interview Point-12:

return leaves the whole function — stronger than break

break exits one loop; return exits main (or the current function) immediately. Mixing them in interview traces changes whether later statements after the loop still run.

Interview tip: For nested-loop output, freeze the outer counter and fully expand the inner loop. For continue in for, remember the update still runs; in while, you must update yourself.

Level 4 Simple Programs

Short programs demonstrating while / do-while, nested patterns, and break / continue.

Program 1 — while / do-while (digit count + menu)


/* while: count digits; do-while: simple menu */
#include <stdio.h>

int main(void) {
    int n, count = 0, choice;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    if (n == 0)
        count = 1;
    else {
        while (n > 0) {
            count++;
            n = n / 10;
        }
    }
    printf("Digits = %d\n", count);

    do {
        printf("1.Ping  2.Exit: ");
        scanf("%d", &choice);
        if (choice == 1)
            printf("Pong\n");
    } while (choice != 2);

    return 0;
}

Program 2 — nested for (star triangle)


/* nested for: right triangle of stars */
#include <stdio.h>

int main(void) {
    int n, row, col;

    printf("Enter rows: ");
    scanf("%d", &n);

    for (row = 1; row <= n; row++) {
        for (col = 1; col <= row; col++)
            printf("*");
        printf("\n");
    }

    return 0;
}

Program 3 — break and continue demo


/* break + continue: print 1..10, skip 3, stop at 8 */
#include <stdio.h>

int main(void) {
    int i;

    for (i = 1; i <= 10; i++) {
        if (i == 3)
            continue;      /* skip 3 */
        if (i == 8)
            break;         /* stop before printing 8 */
        printf("%d ", i);
    }
    printf("\n");
    /* output: 1 2 4 5 6 7 */

    return 0;
}
Comment Directive Type Keyword Function Variable String Number

Level 5 Problem Solving Tricks

How to master loops while solving problems

Most loop bugs come from off-by-one bounds, missing updates, wrong break/continue, and nested counters that fight each other. Use these colorful habits every time you write a loop or pattern.

Trick 1

Trace loops on paper with a small n first

Before coding or predicting output, pick n = 3 or 4. Make a table of i (and j if nested) each iteration. Paper traces catch off-by-one and break/continue mistakes faster than guessing.

Trick 2

Prefer for when the iteration count is known

Counting 1..n, array indices, or fixed pattern rows → for. Unknown count until a sentinel / user choice → while or do-while. Matching the loop form to the problem reduces missing updates.

Trick 3

Watch off-by-one: decide 0-based vs 1-based once

Pick a convention: for (i = 0; i < n; i++) or for (i = 1; i <= n; i++) — and stick to it for that problem. Mixing both in nested pattern loops is the #1 source of wrong star counts.

Trick 4

Name outer/inner counters row and col

Avoid double-i nesting. int row, col; makes pattern logic readable and prevents accidental reuse of one counter that breaks the outer loop.

Trick 5

Put the update before continue in while loops

If you continue early in a while, ensure the loop variable still advances (or the exit condition can become true). for handles this via the update clause; while does not.

Trick 6

Use break for “found it / stop early”; continue for “skip this case”

Searching for a value → break when found. Filtering (skip negatives, skip multiples) → continue. return when the whole function is done. Saying the intent aloud picks the right keyword.

Trick 7

Build patterns as rows × columns

Ask: How many rows? How many symbols on this row? Spaces before stars? Code outer = rows, inner = symbols (and maybe a second inner for spaces). Explain the pattern in words before typing braces.

Trick 8

Guard infinite loops with a clear exit

If you write while (1) or for (;;), immediately plan break / return / flag. Add a comment at the exit point. Never leave a “temporary” infinite loop without a way out.

Quick success checklist

  • Before run: init set? condition correct (< vs <=)? update present? continue still advances?
  • Debug order: trace n=3 on paper → check inner bound → verify break only exits one loop
  • Choose form: known count → for; unknown / sentinel → while; must-run-once → do-while
Level-5 goal: pick the right loop quickly, name row/col clearly, and never ship a pattern without a small hand-traced example — then arrays and nested algorithms feel natural.

Level 6 Practice Programs List

Programming questions only — focused on loops, nested patterns, and break / continue.

  1. 1. Write a C program that uses a for loop to print numbers from 1 to n (read n from the user).
  2. 2. Write a C program that uses a while loop to compute the sum of digits of a positive integer.
  3. 3. Write a C program that uses do-while to show a simple menu (e.g. 1=Hello, 2=Exit) until the user chooses Exit.
  4. 4. Write a C program that prints a right-angled triangle of stars with n rows using nested for loops.
  5. 5. Write a C program that prints a number triangle (row i prints 1..i) using nested loops.
  6. 6. Write a C program that prints an inverted star triangle with n rows.
  7. 7. Write a C program that demonstrates break: read integers until -1, then print how many were read before -1.
  8. 8. Write a C program that demonstrates continue: print numbers 1..20 but skip multiples of 3.