👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Programming Fundamentals
Study mode

Control Structures

Introduction to Control Structures

Imagine you are following a recipe to bake a cake. Sometimes, you need to decide whether to add more sugar based on taste, or repeat stirring until the batter is smooth. Similarly, in programming, control structures are the building blocks that decide the flow of instructions a computer follows.

Control structures allow a program to make decisions, repeat tasks, or jump to different parts of the code. Without them, a program would simply execute instructions one after another, like a list of steps with no variation. But real-world problems require choices and repetition - this is where control structures come in.

In this section, we will explore the main types of control structures: conditional statements that help programs decide what to do, loops that allow repetition, and branching statements that control the flow within these structures. We will also see how these can be combined or nested to solve complex problems efficiently.

Conditional Statements

Conditional statements are instructions that allow a program to choose between different actions based on whether a condition is true or false. These conditions are expressed using boolean expressions, which evaluate to either true or false.

The most common conditional statements are if, if-else, and switch-case. Let's understand each with examples.

The if Statement

The if statement executes a block of code only if a specified condition is true.

Syntax:

if (condition) {    // code to execute if condition is true}

Example: Check if a number is positive.

if (number > 0) {    print("Number is positive");}

If number is greater than zero, the message will be printed; otherwise, nothing happens.

The if-else Statement

Sometimes, you want to choose between two paths: one if the condition is true, another if it is false. This is done using if-else.

Syntax:

if (condition) {    // code if true} else {    // code if false}

Example: Check if a number is even or odd.

if (number % 2 == 0) {    print("Even number");} else {    print("Odd number");}

The switch-case Statement

When you have multiple discrete values to check against a variable, switch-case is more efficient and readable than many if-else statements.

Syntax:

switch (variable) {    case value1:        // code block        break;    case value2:        // code block        break;    ...    default:        // code if no case matches}

Example: Print day of the week based on a number.

switch (day) {    case 1:        print("Monday");        break;    case 2:        print("Tuesday");        break;    ...    default:        print("Invalid day");}
graph TD    Start --> CheckCondition{Condition?}    CheckCondition -- True --> ExecuteTrue[Execute True Block]    CheckCondition -- False --> ExecuteFalse[Execute False Block]    ExecuteTrue --> End    ExecuteFalse --> End

Loops

Loops are control structures that repeat a block of code multiple times until a condition is met. This is useful for tasks like processing lists, counting, or performing repeated calculations.

There are three main types of loops:

  • for loop
  • while loop
  • do-while loop

The for Loop

The for loop repeats a block of code a specific number of times. It has three parts: initialization, condition, and increment/decrement.

Syntax:

for (initialization; condition; update) {    // code to repeat}

Example: Print numbers from 1 to 5.

for (int i = 1; i <= 5; i++) {    print(i);}

The while Loop

The while loop repeats as long as the condition is true. The condition is checked before each iteration.

Syntax:

while (condition) {    // code to repeat}

Example: Print numbers from 1 to 5.

int i = 1;while (i <= 5) {    print(i);    i++;}

The do-while Loop

The do-while loop is similar to while, but the code block executes at least once because the condition is checked after the block.

Syntax:

do {    // code to repeat} while (condition);

Example: Print numbers from 1 to 5.

int i = 1;do {    print(i);    i++;} while (i <= 5);
graph TD    Start --> Init[Initialize variable]    Init --> CheckCondition{Condition?}    CheckCondition -- True --> Execute[Execute Loop Body]    Execute --> Update[Update variable]    Update --> CheckCondition    CheckCondition -- False --> End

Branching Statements

Branching statements alter the normal flow of loops or functions. The main branching statements are:

  • break: Immediately exits the nearest enclosing loop or switch.
  • continue: Skips the current iteration of a loop and proceeds to the next iteration.
  • return: Exits from a function and optionally returns a value.

These statements help control loops precisely and improve program efficiency.

Nested Control Structures

Sometimes, you need to place one control structure inside another. This is called nesting. For example, an if-else inside a loop, or a loop inside another loop.

Nesting allows handling complex decision-making and repeated tasks. However, it requires careful indentation and logic to avoid confusion.

graph TD    Start --> LoopStart[Start Loop]    LoopStart --> CheckCondition{Condition?}    CheckCondition -- True --> NestedIf{Nested if-else Condition?}    NestedIf -- True --> TrueBlock[Execute True Block]    NestedIf -- False --> FalseBlock[Execute False Block]    TrueBlock --> LoopUpdate[Update Loop Variable]    FalseBlock --> LoopUpdate    LoopUpdate --> CheckCondition    CheckCondition -- False --> End

Worked Examples

Example 1: Calculate Grade Using if-else Easy
Given a student's marks out of 100, assign a grade as follows:
  • Marks ≥ 90: Grade A
  • Marks ≥ 75 and < 90: Grade B
  • Marks ≥ 50 and < 75: Grade C
  • Marks < 50: Grade F

Step 1: Check if marks are 90 or above.

Step 2: If not, check if marks are 75 or above.

Step 3: If not, check if marks are 50 or above.

Step 4: Otherwise, assign grade F.

if (marks >= 90) {    grade = 'A';} else if (marks >= 75) {    grade = 'B';} else if (marks >= 50) {    grade = 'C';} else {    grade = 'F';}    

Answer: Grade assigned based on marks.

Example 2: Sum of First N Natural Numbers Using for Loop Easy
Calculate the sum of the first N natural numbers (1 to N).

Step 1: Initialize sum to 0.

Step 2: Use a for loop from 1 to N, adding each number to sum.

Step 3: After the loop ends, print the sum.

int sum = 0;for (int i = 1; i <= N; i++) {    sum += i;}print(sum);    

Answer: Sum of numbers from 1 to N.

Example 3: Find Largest Number Using Nested if-else Medium
Given three numbers A, B, and C, find the largest among them.

Step 1: Compare A and B.

Step 2: If A > B, compare A with C.

Step 3: Else, compare B with C.

Step 4: The largest value from these comparisons is the answer.

if (A > B) {    if (A > C) {        largest = A;    } else {        largest = C;    }} else {    if (B > C) {        largest = B;    } else {        largest = C;    }}    

Answer: Largest number among A, B, and C.

Example 4: Print Even Numbers Using while Loop and continue Medium
Print all even numbers between 1 and 20 using a while loop and continue statement.

Step 1: Initialize a counter variable to 1.

Step 2: While counter is less than or equal to 20, check if it is odd.

Step 3: If odd, use continue to skip printing and move to next iteration.

Step 4: If even, print the number.

int i = 1;while (i <= 20) {    if (i % 2 != 0) {        i++;        continue;    }    print(i);    i++;}    

Answer: Even numbers from 2 to 20 printed.

Example 5: Break Statement to Exit Loop on Condition Medium
Print numbers from 1 upwards but stop printing when the number reaches 10 using a loop and break statement.

Step 1: Initialize counter to 1.

Step 2: Use an infinite loop (e.g., while(true)).

Step 3: Print the number.

Step 4: If number equals 10, use break to exit the loop.

Step 5: Increment the counter.

int i = 1;while (true) {    print(i);    if (i == 10) {        break;    }    i++;}    

Answer: Numbers 1 to 10 printed, then loop exits.

Formula Bank

Sum of First N Natural Numbers
\[ S = \frac{N \times (N + 1)}{2} \]
where: \( S \) = sum, \( N \) = number of natural numbers
Use this formula to quickly calculate the sum from 1 to N without looping.

Tips & Tricks

Tip: Use flowcharts to visualize complex control flows before coding.

When to use: When dealing with nested or multiple control structures.

Tip: Remember that continue skips the current iteration but does not exit the loop.

When to use: To avoid infinite loops and correctly manage loop iterations.

Tip: Use switch-case for multiple discrete conditions instead of many if-else.

When to use: When checking a variable against many constant values.

Tip: Indent code properly to easily identify nested control structures.

When to use: While writing or debugging complex nested loops and conditions.

Tip: Test boundary conditions separately to avoid off-by-one errors in loops.

When to use: When writing loops that iterate over ranges or arrays.

Common Mistakes to Avoid

❌ Using assignment operator = instead of comparison operator == in conditions
✓ Use == for comparison in conditional statements
Why: Students confuse assignment with equality check, leading to logical errors
❌ Infinite loops due to incorrect loop condition or missing increment/decrement
✓ Ensure loop conditions will eventually become false and update variables properly
Why: Forgetting to update loop variables or wrong condition causes endless execution
❌ Misplacing break or continue leading to unexpected flow control
✓ Use break and continue carefully, understanding their effect on loops
Why: Improper use can skip necessary iterations or exit loops prematurely
❌ Not handling all cases in switch-case leading to fall-through errors
✓ Use break after each case or default to prevent fall-through
Why: Switch-case executes subsequent cases if break is missing, causing bugs
❌ Incorrect nesting of control structures causing logic errors
✓ Carefully structure and indent nested ifs and loops, test stepwise
Why: Poor nesting leads to unintended execution paths and hard-to-find bugs
Key Concept

Control Structures

Control structures direct the flow of program execution by making decisions and repeating tasks.

✨ AI exam tools — try them free (included in every plan)
Tip: select any text above to Explain / Example / Simplify it.
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Control Structures · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.