👁 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

Loops and Conditionals

Introduction

In programming, two fundamental concepts help us control how a program behaves: decision-making and repetition. Decision-making allows a program to choose different paths based on conditions, while repetition lets a program execute a block of code multiple times without rewriting it. These concepts are implemented using conditionals and loops, respectively.

Imagine you are following a recipe. Sometimes, you decide to add salt only if the dish tastes bland (a decision). Other times, you stir the mixture repeatedly until it thickens (a repetition). Similarly, in programming, conditionals help the computer make choices, and loops help it repeat tasks efficiently.

Mastering loops and conditionals is essential for writing efficient programs and solving complex problems, especially in competitive exams where time and accuracy matter.

Conditionals

Conditionals are statements that perform different actions based on whether a condition is true or false. The condition is a logical expression that evaluates to a boolean value: true or false.

The simplest conditional is the if statement. It executes a block of code only if the condition is true.

If Statement Syntax

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

For example, in Python:

if temperature > 30:    print("It's a hot day")

This code prints "It's a hot day" only if the temperature is greater than 30.

If-Else Statement

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

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

Example in Python:

if temperature > 30:    print("It's a hot day")else:    print("It's not a hot day")

Nested Conditionals

You can place one conditional inside another to check multiple conditions step-by-step. This is called nested if statements.

if (condition1) {    if (condition2) {        // code if both conditions are true    } else {        // code if condition1 true but condition2 false    }} else {    // code if condition1 false}

Example:

if age >= 18:    if has_voter_id:        print("Eligible to vote")    else:        print("Need voter ID to vote")else:    print("Not eligible to vote")

How Conditionals Control Flow

Conditionals direct the flow of program execution by choosing which blocks of code run. This decision-making is essential for programs that react differently based on input or state.

graph TD    Start --> Condition{Is condition true?}    Condition -- Yes --> TrueBlock[Execute True Block]    Condition -- No --> FalseBlock[Execute False Block]    TrueBlock --> End[End]    FalseBlock --> End

Loops

Loops allow a program to repeat a block of code multiple times. This is useful when you want to perform the same operation on many items or until a certain condition is met.

For Loop

A for loop repeats a block of code a known number of times. It usually involves three parts:

  • Initialization: Set the starting point.
  • Condition: Check if the loop should continue.
  • Update: Change the loop variable to eventually end the loop.

Example in C:

for (int i = 1; i <= 5; i++) {    printf("%d\n", i);}

This prints numbers 1 to 5.

While Loop

A while loop repeats as long as a condition remains true. It is useful when the number of iterations is not known beforehand.

while (condition) {    // code to repeat}

Example in Python:

count = 1while count <= 5:    print(count)    count += 1

Nested Loops

You can place one loop inside another to handle multi-dimensional data or repeated tasks within repeated tasks.

Example: Printing a multiplication table up to 3x3:

for i in range(1, 4):    for j in range(1, 4):        print(i * j, end=' ')    print()

Loop Execution Flow

graph TD    Start --> Initialization    Initialization --> ConditionCheck{Is condition true?}    ConditionCheck -- Yes --> ExecuteBlock[Execute loop block]    ExecuteBlock --> Update    Update --> ConditionCheck    ConditionCheck -- No --> End

Loop Control Statements

Sometimes, you want to change the normal flow of loops. Two important statements help with this:

Break Statement

The break statement immediately exits the loop, skipping the remaining iterations.

for i in range(1, 10):    if i == 5:        break    print(i)

This prints numbers 1 to 4 and stops when i becomes 5.

Continue Statement

The continue statement skips the current iteration and moves to the next one.

for i in range(1, 6):    if i == 3:        continue    print(i)

This prints 1, 2, 4, 5 (skips 3).

Formula Bank

Formula Bank

Sum of First N Natural Numbers
\[ S = \frac{N \times (N+1)}{2} \]
where: \(N\) = number of natural numbers, \(S\) = sum
Loop Iteration Count
\[ \text{Iterations} = \text{End} - \text{Start} + 1 \]
where: Start and End are loop boundary values

Worked Examples

Example 1: Calculate Sum of First N Natural Numbers Using a For Loop Easy
Write a program to calculate the sum of the first N natural numbers using a for loop.

Step 1: Initialize a variable sum to 0 to store the total.

Step 2: Use a for loop to iterate from 1 to N.

Step 3: In each iteration, add the current number to sum.

Step 4: After the loop ends, print the value of sum.

Code (Python):

N = 10sum = 0for i in range(1, N+1):    sum += iprint("Sum =", sum)    

Answer: Sum = 55

Example 2: Determine if a Number is Prime Using Loops and Conditionals Medium
Write a program to check if a given number is prime.

Step 1: A prime number is a number greater than 1 that has no divisors other than 1 and itself.

Step 2: For a given number num, check divisibility by all numbers from 2 to \(\sqrt{num}\).

Step 3: If any divisor divides num exactly, it is not prime.

Step 4: Use a loop and an if condition to test divisibility.

Code (Python):

num = 29is_prime = Trueif num <= 1:    is_prime = Falseelse:    for i in range(2, int(num**0.5) + 1):        if num % i == 0:            is_prime = False            breakif is_prime:    print(num, "is prime")else:    print(num, "is not prime")    

Answer: 29 is prime

Example 3: Print Multiplication Table Using Nested Loops Medium
Write a program to print the multiplication table from 1 to 10.

Step 1: Use an outer loop for numbers 1 to 10.

Step 2: Use an inner loop for numbers 1 to 10 to multiply with the outer loop number.

Step 3: Print the product in a formatted way.

Code (Python):

for i in range(1, 11):    for j in range(1, 11):        print(i * j, end='\t')    print()    

Answer: Prints a 10x10 multiplication table.

Example 4: Find the Largest Element in an Array Using Loops and Conditionals Medium
Given an array of integers, find the largest element.

Step 1: Initialize a variable max_val with the first element of the array.

Step 2: Loop through the array starting from the second element.

Step 3: In each iteration, compare the current element with max_val. If greater, update max_val.

Step 4: After the loop, max_val holds the largest element.

Code (Python):

arr = [12, 45, 7, 89, 34]max_val = arr[0]for num in arr[1:]:    if num > max_val:        max_val = numprint("Largest element is", max_val)    

Answer: Largest element is 89

Example 5: Break Statement to Exit Loop on Condition Easy
Write a program to find the first even number in a list and stop searching once found.

Step 1: Loop through the list elements.

Step 2: Check if the current element is even using modulus operator.

Step 3: If even, print the number and use break to exit the loop.

Code (Python):

numbers = [3, 7, 5, 8, 10]for num in numbers:    if num % 2 == 0:        print("First even number is", num)        break    

Answer: First even number is 8

Tips & Tricks

Tip: Use flowcharts to plan complex nested loops and conditionals before coding.

When to use: When solving problems with multiple decision points or nested iterations.

Tip: Remember that for loops are best when the number of iterations is known, while while loops suit unknown or condition-based iterations.

When to use: Choosing the appropriate loop structure for a problem.

Tip: Use break statements to optimize loops by exiting early once the desired condition is met.

When to use: When searching for an element or condition inside a loop.

Tip: Check loop boundary conditions carefully to avoid off-by-one errors.

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

Tip: Test nested loops with small input sizes first to verify logic before scaling up.

When to use: Debugging complex nested loops.

Common Mistakes to Avoid

❌ Using assignment operator (=) instead of equality operator (==) in conditionals.
✓ Use '==' for comparison in condition expressions.
Why: Confusion between assignment and comparison operators leads to logical errors.
❌ Creating infinite loops by not updating loop control variables.
✓ Ensure loop variables are incremented or updated inside the loop.
Why: Forgetting to update loop variables causes the loop condition to never become false.
❌ Misplacing break or continue statements causing unexpected flow control.
✓ Use break and continue carefully and test their effect on loop execution.
Why: Incorrect use can skip necessary iterations or exit loops prematurely.
❌ Off-by-one errors in loop boundaries (e.g., using <= instead of <).
✓ Carefully define loop start and end conditions to match problem requirements.
Why: Loop boundaries often cause errors in counting iterations or accessing array indices.
❌ Nested loops with incorrect inner loop limits causing wrong output or excessive computation.
✓ Verify inner loop ranges and conditions align with outer loop logic.
Why: Misaligned nested loops can produce incorrect results or performance issues.
Key Concept

Loops and Conditionals Summary

Loops repeat code blocks; conditionals choose code paths based on conditions.

  • If Statement: Executes code if condition is true.
  • If-Else Statement: Chooses between two paths.
  • For Loop: Repeats code a fixed number of times.
  • While Loop: Repeats code while condition is true.
  • Break: Exits loop immediately.
  • Continue: Skips current iteration.
✨ 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
Loops and Conditionals · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.