Skip to content
Topic guide · Programming

Control Flow and Loops: if-else, switch, for, while, do-while with Traced Examples · কন্ট্রোল ফ্লো ও লুপ: if-else, switch, for, while, do-while ও ট্রেস করা উদাহরণ

Control flow statements decide which statements run and how often: selection (if, if-else, switch and the ?: operator) chooses a path, iteration (for, while, do-while) repeats a block, and jumps (break, continue, goto, return) leave it early. for and while are entry-controlled loops that test the condition first and may run zero times, while do-while is exit-controlled and always runs its body at least once. In a switch, execution falls through to the next case unless a break ends it, and break leaves only the innermost loop or switch, while continue skips to the next iteration.

কন্ট্রোল ফ্লো স্টেটমেন্ট ঠিক করে কোন স্টেটমেন্ট চলবে এবং কতবার: সিলেকশন (if, if-else, switch ও ?: অপারেটর) পথ বেছে নেয়, ইটারেশন (for, while, do-while) একটি ব্লক বারবার চালায়, আর জাম্প (break, continue, goto, return) আগেভাগে বেরিয়ে যায়। for ও while এন্ট্রি-কন্ট্রোলড লুপ: আগে শর্ত যাচাই করে, তাই একবারও না-ও চলতে পারে; কিন্তু do-while এক্সিট-কন্ট্রোলড, তাই এর বডি অন্তত একবার চলবেই। switch-এ break না দিলে পরের case-এও কাজ চলতে থাকে (ফল-থ্রু); break কেবল সবচেয়ে ভেতরের লুপ বা switch থেকে বের করে, আর continue পরের ইটারেশনে চলে যায়।

Asked in past exams
74
Papers
54

1. Three ways a program can flow

Statements normally run one after another, top to bottom. That is sequence. Böhm and Jacopini showed in 1966 that any program can be written with just three structures, which is the basis of structured programming:

Structure What it does C, C++ and Java statements
Sequence Runs statements in order Ordinary statements
Selection (decision) Chooses one path by a condition if, if-else, else-if ladder, switch, ?:
Iteration (repetition) Repeats a block while a condition holds for, while, do-while
Jump (transfer) Leaves a block or loop early break, continue, goto, return

So "for, while and do-while" are all examples of iteration, and an exam that asks for "three types of control statements" wants selection, iteration and jump (or sequence, selection and iteration, if it means the structures).

2. if, if-else and the else-if ladder

if (marks >= 80)      grade = 'A';
else if (marks >= 60) grade = 'B';
else if (marks >= 40) grade = 'C';
else                  grade = 'F';

The conditions are tested from the top, and only the first true branch runs. Rules that exams test:

  • In C, any non-zero value is true and 0 is false. So if (5) and if (-1) both run, and if (printf("0")) runs because printf returns 1, the number of characters it printed.
  • = is not ==. if (n = 7) assigns 7 and is always true; if (n = 0) assigns 0 and is always false. Java refuses both, because an if condition must be boolean.
  • Dangling else: an else belongs to the nearest unmatched if, whatever the indentation says.
int x = 2, y = 3;
if (x > 5)
    if (y > 1) printf("A\n");
else printf("B\n");      /* belongs to "if (y > 1)" */
printf("done\n");

This prints only done: x > 5 is false, and the else is part of the inner if, so nothing else runs. Use braces to make the intent clear.

  • When x can only be 0 or 1, if (x == 0) x = 1; else x = 0; is the same as x = 1 - x; (a past MCQ).
  • Python uses if, elif and else with a colon, and the indentation marks the block; wrong indentation is an IndentationError.

3. switch and fall-through

switch compares one value with constant case labels:

#include <stdio.h>
int main(void) {
    int i;
    for (i = 1; i <= 3; i++) {
        printf("s%d:", i);
        switch (i) {
            case 1: printf("one ");      /* no break: falls through */
            case 2: printf("two "); break;
            default: printf("other ");
        }
        printf("\n");
    }
    return 0;
}

Output:

s1:one two
s2:two
s3:other

When i is 1, control enters at case 1, prints "one", and falls through into case 2 because there is no break; the break after "two" then leaves the switch.

Rules of switch:

  • In C the controlling expression and every case label must be integer types: int, char, enum and so on. float and double cannot be used, and neither can ranges or variables as labels.
  • case labels must be constant and unique. default is optional, may appear anywhere, and runs when no case matches.
  • Java allows char, byte, short, int, their wrapper classes, enums and String (since Java 7), but not long, float, double or boolean; fall-through works the same. Python has no switch; Python 3.10 added match/case, which does not fall through.
Point if-else ladder switch
Tests Any condition, including ranges (x > 5 && x < 10) Equality with constant values only
Types (C) Any scalar, including float Integer types only
Fall-through No Yes, unless break
Best for Ranges and mixed conditions A menu of fixed choices

4. The conditional operator ?:

condition ? value_if_true : value_if_false is the only ternary operator in C, C++ and Java. It is an expression, so it can sit inside other expressions, and it groups right to left:

int a = 7, b = 12, c = 9;
int m = a > b ? (a > c ? a : c) : (b > c ? b : c);   /* m = 12 */

a > b is false, so the right part runs: b > c is true, and m = 12. Python writes the same idea as x if condition else y.

5. The three loops

Loop Syntax Condition tested Minimum runs Typical use
for for (init; condition; update) body Before each pass (entry-controlled) 0 A known number of passes
while while (condition) body Before each pass (entry-controlled) 0 Repeat until something happens
do-while do body while (condition); After each pass (exit-controlled) 1 Menus, input validation
A while loop tests its condition before the body, so it can skip the body entirely, while a do-while runs the body first and tests afterwards.
  • Because the body of a do-while always runs once, it suits a menu: show the menu, read a choice, repeat until the user picks "exit". This is the keyed answer to "which loop is useful for processing a menu selection".
  • Note the semicolon after while (condition); in a do-while; it is required there and wrong after for (…) or while (…) (see section 9).
  • With int a = 10;, while (a < 5) {…} runs 0 times, but do {…} while (a < 5); runs once.
  • Any for can be written as a while: for (i = 1; i <= n; i++) sum += i; becomes i = 1; while (i <= n) { sum += i; i++; } (one difference: continue in a for still runs the update, but in this while it would skip i++; another is that a variable declared in the for header exists only inside the loop).
  • Two variables can be driven at once with the comma operator: for (i = 0, j = 9; i < j; i++, j--) runs 5 times (i = 0 … 4 while j = 9 … 5).
  • All three parts of a for are optional: for (;;) (or while (1)) is an infinite loop, which ends only with break, return, goto or exit(). The usual keyed answer to "what can terminate for(;;)?" is break.
  • Python has for item in sequence: (often range(start, stop, step), where stop is excluded) and while condition:, but no do-while. A Python loop may have an else block that runs only if the loop was not left by break.

6. break, continue and the other jumps

Statement Effect
break Leaves the innermost loop or switch at once
continue Skips the rest of this pass and starts the next one (in a for, the update still runs)
goto label Jumps to a label in the same function (legal, but avoid it)
return Leaves the whole function
exit(n) Ends the whole program (from <stdlib.h>)
break label; / continue label; (Java) Leaves, or continues, the labelled outer loop: outer: for (…) { for (…) { if (x) break outer; } }

continue belongs only in loops; inside a switch that is not in a loop it is a compile error.

for (i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;   /* skip even numbers */
    if (i > 7) break;           /* stop after 7 */
    printf("%d ", i);
}
printf("| i=%d\n", i);

Output: 1 3 5 7 | i=9. Even values are skipped by continue; at i = 9 the break runs before the printf, so i stays 9 after the loop.

7. Counting passes and tracing loops

For for (i = a; i < b; i += s) with a < b, the loop runs ⌈(b − a) / s⌉ times; with <= it runs ⌊(b − a) / s⌋ + 1 times. So for (i = 0; i < n; i++) runs n times and for (i = 1; i <= n; i++) also n times, but for (i = 0; i <= n; i++) runs n + 1 times.

Code Passes Value after the loop (all checked by running)
for (i = 1; i <= 100; i *= 2) 7 (i = 1, 2, 4, 8, 16, 32, 64) i = 128
for (i = 10; i > 0; i -= 3) 4 (i = 10, 7, 4, 1) i = −2
x = 0; while (x < 100) x += 2; 50 x = 100
for (k = 0.0; k < 3.0; k++) with double k 3 k = 3.0
for (i = 0; i < 5; i++) for (j = 0; j < 5; j++) count++; 25 count = 25
for (i = n - 1; i > -1; i--) n, the same indexes as for (i = 0; i < n; i++), in reverse i = −1

Worked example 1: a triangular nested loop.

int i, j, count = 0;
for (i = 0; i < 5; i++)
    for (j = 0; j < i; j++)
        count++;
printf("%d", count);

The inner loop runs i times for each i:

i Inner passes (j = 0 … i − 1) count afterwards
0 0 0
1 1 1
2 2 3
3 3 6
4 4 10

Output: 10 (0 + 1 + 2 + 3 + 4 = 5 × 4 / 2). In general a loop like this runs n(n − 1)/2 times.

Which is not an infinite loop? (a past MCQ, with int i = 0;)

  • for (;;) {} is infinite, and while ( ) {} does not even compile (a while needs a condition).
  • while (++i < 0) { --i; }: ++i makes i = 1, 1 < 0 is false, so the loop ends at once. Not infinite.
  • do { ++i; } while (--i <= 0);: each pass adds 1 and takes it away again, so i stays 0 and 0 <= 0 stays true for ever. Infinite.

8. Classic loop programs

These short programs are asked again and again in written papers. All outputs below were produced by running them.

Sum of digits and reverse of a number. Take the last digit with n % 10 and drop it with n / 10:

int n = 3426, sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }        /* sum = 15 */

int m = 6789, rev = 0;
while (m > 0) { rev = rev * 10 + m % 10; m /= 10; } /* rev = 9876 */

The same pattern counts how often a digit occurs (digit 2 in 12223 → 3), and repeating the digit sum until one digit is left gives the digital root (9875 → 29 → 11 → 2).

Worked example 2: primes from 1 to n. A number n ≥ 2 is prime if no d with 2 ≤ d ≤ √n divides it. Testing up to √n is enough, because if n = a × b then one of a or b is at most √n.

#include <stdio.h>
int isPrime(int n) {
    int d;
    if (n < 2) return 0;            /* 0 and 1 are not prime */
    for (d = 2; d * d <= n; d++)
        if (n % d == 0) return 0;   /* found a divisor */
    return 1;
}
int main(void) {
    int i, n = 30;
    for (i = 1; i <= n; i++)
        if (isPrime(i)) printf("%d ", i);
    printf("\n");
    return 0;
}

Output: 2 3 5 7 11 13 17 19 23 29. Tracing isPrime(97): d runs from 2 to 9 (9 × 9 = 81 ≤ 97, but 10 × 10 = 100 > 97); none of 2 … 9 divides 97, so 97 is prime. For 91, d = 7 divides it (91 = 7 × 13), so it is not prime.

Factorial, leap year and Fibonacci:

long long f = 1;
for (i = 1; i <= 5; i++) f *= i;                       /* 5! = 120 */

int leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;

int a = 0, b = 1, t;
while (a <= 100) { printf("%d ", a); t = a + b; a = b; b = t; }
  • Leap year: 2000 and 2024 are leap years; 1900, 2023 and 2100 are not (a century year must divide by 400).
  • The Fibonacci loop prints 0 1 1 2 3 5 8 13 21 34 55 89.
  • Other one-loop classics: sum 1 to 100 = 5050; 1² + 2² + … + 10² = 385; 153 is an Armstrong number (1³ + 5³ + 3³ = 153); the GCD of 12 and 18 is 6 and their LCM is 12 × 18 / 6 = 36.

Worked example 3: patterns with nested loops. The outer loop counts rows; the inner loop prints that row.

for (i = 1; i <= 4; i++) {
    for (j = 1; j <= i; j++) printf("%d", j);
    printf("\n");
}
1
12
123
1234

Print "*" instead of j for a star triangle. For a centred pyramid, row i prints 3 − i spaces and then 2i − 1 stars (for 3 rows: 1, 3 and 5 stars).

9. Tricky loop cases

  • A semicolon after the header makes an empty loop: for (i = 0; i < 5; i++); runs five empty passes, and the block below it then runs once, with i = 5. The same mistake after while (…) usually gives an infinite loop.
  • Unsigned counters never go below 0: for (unsigned u = 3; u >= 0; u--) never ends, because after 0 the value wraps to 4,294,967,295.
  • Floating-point counters: for (f = 0.0f; f != 1.0f; f += 0.1f) never ends, because 0.1 is not exact in binary and f skips past 1.0. Count with an integer, or compare with <.
  • Overflow inside a loop: 13! = 6,227,020,800 is larger than the 32-bit int maximum 2,147,483,647, so a factorial loop in int breaks from 13! (signed overflow is undefined behaviour in C). long long holds up to 20! = 2,432,902,008,176,640,000 but not 21!.
  • Wrong starting value: a "find the maximum" loop that starts with max = 0 fails when every element is negative; it returns 0. Start with max = a[0] (a past Java MCQ).
  • An invalid header: for (int x = 10; k <= 5; x / 9) is the invalid one in a past MCQ: k was never declared. (In Java, x / 9 as the update is also an error, "not a statement"; C accepts it with a warning, but it never changes x.)
  • switch (f) with a float f does not compile in C or Java, and a break inside a switch that sits inside a loop leaves only the switch, not the loop.

Practice · অনুশীলন

  1. Which loop is exit-controlled, and what does that guarantee?
    Answer

    The do-while loop. It tests the condition after the body, so the body always runs at least once.

  2. How many times does for (i = 1; i <= 100; i *= 2) run, and what is i afterwards?
    Answer

    7 times (i = 1, 2, 4, 8, 16, 32, 64); after the loop i = 128.

  3. What is the output: for (i = 1; i <= 10; i++) { if (i % 2 == 0) continue; if (i > 7) break; printf("%d ", i); }
    Answer

    1 3 5 7. Even numbers are skipped by continue, and the loop stops when i reaches 9.

  4. Which data type cannot be used in a C switch statement: char, int or float?
    Answer

    float. A switch expression and its case labels must be integer types (char, int, enum and so on).

  5. Rewrite for (i = 1; i <= n; i++) sum += i; as a while loop.
    Answer

    i = 1; while (i <= n) { sum += i; i++; }

Asked in past exams · আগের পরীক্ষায় যেভাবে এসেছে

Our past papers have 74 questions on this topic (36 MCQ, 38 written) from 54 exams. Here are 12 of them; each links to its full paper.

  1. Which loop is an exit-controlled loop?

    • a)for loop
    • b)while loop
    • c)do while loop (correct answer)
    • d)None of the above
    Explanation · ব্যাখ্যা

    Correct answer: (c) do while loop

    A loop is called exit-controlled when its condition is checked at the exit point, after the body. In do { body } while (condition); the body runs first and the condition is evaluated after every pass, so the body always runs at least once. A test with a false condition (n = 10, n < 5) confirmed it: the do-while printed one line, the while printed nothing.

    Why the other options are wrong

    • (a) for loop: Entry-controlled; its condition is evaluated before each pass, so it can run zero times.
    • (b) while loop: Entry-controlled; it also tests before each pass.
    • (d) None of the above: Wrong, because do-while is exit-controlled.

    Tip: Entry-controlled = for, while (test first); exit-controlled = do-while (test last).

    Source: do-while loop - cppreference.com; while loop - cppreference.com; for loop - cppreference.com

  2. Which of the following is a technique for hiding the internal implementation details of an object?

    • a)Encapsulation (correct answer)
    • b)Polymorphism
    • c)Inheritance
    • d)All of the above
    Explanation · ব্যাখ্যা

    Correct answer: (a) Encapsulation

    Encapsulation hides an object's internals: fields are made private, and outside code may use only the public methods. Because callers interact only with those methods, the internal implementation stays hidden and can change without breaking them. This is called information hiding.

    Why the other options are wrong

    • (b) Polymorphism: lets one call behave differently for different objects. It is about varying behaviour, not hiding internals.
    • (c) Inheritance: lets a subclass reuse a parent's members. It actually makes inherited public and protected members visible to the subclass, so it is not a hiding technique.
    • (d) All of the above: only encapsulation is a hiding technique, so "all" is wrong.

    Tip: private data + public methods = encapsulation = information hiding. (Abstraction, which shows only the essentials, is a close cousin but is not offered here.)

    Source: What Is an Object? (The Java Tutorials, Oracle)

  3. The ____ loop is especially useful when you process a menu selection.

    • a)while
    • b)do-while (correct answer)
    • c)for
    • d)switch
    Explanation · ব্যাখ্যা

    Correct answer: (b) do-while

    A menu program has to display the menu and read the user's choice at least once, then repeat until the user picks "Exit". A do-while loop fits this exactly: its body runs first and the condition is tested only after each pass, so the menu always appears once with no extra setup.

    int choice;
    do {
        printf("1. Add  2. Delete  0. Exit\n");
        scanf("%d", &choice);
        /* handle the choice, usually with switch */
    } while (choice != 0);
    

    choice gets its value inside the body before the test, so the condition never reads an uninitialised variable.

    Why the other options are wrong

    • (a) while: Tests the condition before the body, so choice must be given a value before the loop (or the menu code repeated). It works, but less naturally.
    • (c) for: Also tests first, and is meant for counter-controlled repetition, not "repeat until the user quits".
    • (d) switch: A selection statement that handles the chosen item. It repeats nothing, so it is not a loop at all.

    Tip: "Show at least once, then ask whether to repeat" → do-while.

    Source: do-while loop - cppreference.com; Statements - cppreference.com

  4. Which for loop statement is invalid?

    • a)for(int x=10; k<=5; x/9) (correct answer)
    • b)for(int x=10; x>=2; --x)
    • c)for(int x=10; x>=200; x=3*x)
    • d)for(int x=10; x>=0; x+=2)
    Explanation · ব্যাখ্যা

    Correct answer: (a) for(int x=10; k<=5; x/9)

    A for header has three parts: for (init; condition; update). Check (a) part by part:

    1. int x=10 declares the loop variable x.
    2. The condition k<=5 uses k, which is never declared, so the compiler stops. gcc reports 'k' undeclared (first use in this function).
    3. Even if some k existed, the update x/9 only computes a value and throws it away (gcc warns "statement with no effect"), so x never changes. A working update would be x/=9 or x=x/9.

    Why the other options are wrong

    • (b) for(int x=10; x>=2; --x): Valid. x takes the values 10, 9, …, 2, so the body runs 9 times.
    • (c) for(int x=10; x>=200; x=3*x): Valid syntax. The test 10 ≥ 200 is false at the start, so the body runs 0 times. A loop that never runs is still a legal loop.
    • (d) for(int x=10; x>=0; x+=2): Valid syntax. x only grows (10, 12, 14, …), so the condition stays true and the loop runs indefinitely unless the body uses break. Endless is not the same as invalid.

    Tip: "Invalid" means it will not compile: look first for an undeclared name or a malformed header, then check that the update really changes the loop variable.

    Declaring int x inside the for header needs C99 or later (or C++).

    Source: for loop - cppreference.com

  5. Type of software which is designed for users to customize programs is-

    • a)freeware
    • b)shareware
    • c)macros (correct answer)
    • d)none of these
    Explanation · ব্যাখ্যা

    Correct answer: (c) macros

    A macro is a series of commands and instructions grouped into a single command that carries out a task automatically. Programs such as Word and Excel let users record or write macros (in VBA) and attach them to a button or keyboard shortcut, so each user can automate repetitive work and customize the program to fit the way they work. Of the options, only macros exist to let users customize programs.

    Why the other options are wrong

    • (a) freeware: Software that is given away free of charge. The term describes price and licensing, not customization.
    • (b) shareware: Software distributed free on a trial basis, with payment expected for continued use or full features. It is also a distribution model.
    • (d) none of these: Wrong, because (c) fits.

    Tip: Freeware/shareware = how software is distributed; macros = how users automate and customize it.

    Source: Create or run a macro - Microsoft Support

  6. What is an example of iteration in C?

    • a)for
    • b)while
    • c)do-while
    • d)all of the above (correct answer)
    Explanation · ব্যাখ্যা

    Correct answer: (d) all of the above

    Iteration means executing a statement repeatedly while a condition holds. C has exactly three iteration (loop) statements, and every one of them is listed:

    • for (init; condition; update): usually used when the number of passes is known; the condition is tested before each pass.
    • while (condition): tests before each pass, so it may run zero times.
    • do … while (condition);: tests after each pass, so it runs at least once.

    Why the other options are wrong

    • (a) for: A correct example of iteration, but choosing it alone leaves out while and do-while.
    • (b) while: Also a loop statement, but not the only one offered.
    • (c) do-while: Also a loop statement; picking it alone ignores the other two.

    Because all three are iteration statements, the complete answer is (d).

    Tip: C's loops are for, while and do-while; its selection statements are if, if-else and switch.

    Source: Statements - cppreference.com

  7. What does the 'continue' statement do inside a loop?

  8. Write a C program that accepts 10 elements in an array and finds the maximum elements from the array.

  9. Write down a program is any high level language to read an integer and display a pattern like below. For example, if the given integer number is 1234, then the following pattern will be printed.

  10. (a) Difference between a while loop and do-while loop.

  11. For a non-negative integer x, which of the following operations gives the remainder after division of x by 8?

  12. Write a C/Java program to determine if a given year is a leap year nor not.

Common mistakes · সাধারণ ভুল

  • Forgetting break in a switch, so execution falls through into the next case.
  • Putting a semicolon after for (...) or while (...), which makes the loop body empty.
  • Writing if (x = 5) instead of if (x == 5): in C the assignment is always true.
  • Saying a while loop always runs at least once: only do-while does; while and for may run zero times.
  • Off-by-one counting: for (i = 0; i <= n; i++) runs n + 1 times, not n.
  • Thinking break leaves every enclosing loop: it leaves only the innermost loop or switch.

বাংলায় সংক্ষেপে

  • প্রোগ্রামের তিন মৌলিক কাঠামো: সিকোয়েন্স, সিলেকশন (if, switch, ?:) ও ইটারেশন (for, while, do-while); break, continue, goto ও return হলো জাম্প স্টেটমেন্ট।
  • C-তে শূন্য ছাড়া যেকোনো মান সত্য; else সবসময় সবচেয়ে কাছের সেই if-এর সঙ্গে যুক্ত হয়, যার এখনও কোনো else নেই।
  • switch-এ break না দিলে পরের case-এ ফল-থ্রু হয়; C-তে কেবল পূর্ণসংখ্যা টাইপ (int, char, enum) চলে, float চলে না।
  • for ও while এন্ট্রি-কন্ট্রোলড (শূন্যবারও চলতে পারে); do-while এক্সিট-কন্ট্রোলড, অন্তত একবার চলে, তাই মেনুর জন্য উপযোগী।
  • break সবচেয়ে ভেতরের লুপ বা switch থেকে বের করে; continue বাকি অংশ বাদ দিয়ে পরের ইটারেশনে যায়।
  • i = ০ থেকে শুরু করে i < n শর্তের লুপ চলে n বার, কিন্তু i <= n দিলে n + ১ বার; নেস্টেড লুপে ভেতরের লুপের মোট সংখ্যা যোগ করে গণনা করতে হয়।
  • মৌলিক সংখ্যা যাচাইয়ে √n পর্যন্ত ভাজক দেখাই যথেষ্ট; অঙ্কের যোগফলে n % ১০ দিয়ে শেষ অঙ্ক নিয়ে n / ১০ দিয়ে তা বাদ দেওয়া হয়।

Updated 2026-10-18. Written by ARBS Academy; the past exam questions are from public recruitment exams.