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 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.
if StatementThe 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.
if-else StatementSometimes, 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");}switch-case StatementWhen 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 --> EndLoops 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 LoopThe 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);}while LoopThe 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++;}do-while LoopThe 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 --> EndBranching statements alter the normal flow of loops or functions. The main branching statements are:
These statements help control loops precisely and improve program efficiency.
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 --> EndStep 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.
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.
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.
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.
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.
When to use: When dealing with nested or multiple control structures.
continue skips the current iteration but does not exit the loop. When to use: To avoid infinite loops and correctly manage loop iterations.
switch-case for multiple discrete conditions instead of many if-else. When to use: When checking a variable against many constant values.
When to use: While writing or debugging complex nested loops and conditions.
When to use: When writing loops that iterate over ranges or arrays.
= instead of comparison operator == in conditions== for comparison in conditional statementsbreak or continue leading to unexpected flow controlbreak and continue carefully, understanding their effect on loopsswitch-case leading to fall-through errorsbreak after each case or default to prevent fall-throughProgress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.
Go to practice →