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 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 (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.
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")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")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 --> EndLoops 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.
A for loop repeats a block of code a known number of times. It usually involves three parts:
Example in C:
for (int i = 1; i <= 5; i++) { printf("%d\n", i);}This prints numbers 1 to 5.
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
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()
graph TD Start --> Initialization Initialization --> ConditionCheck{Is condition true?} ConditionCheck -- Yes --> ExecuteBlock[Execute loop block] ExecuteBlock --> Update Update --> ConditionCheck ConditionCheck -- No --> EndSometimes, you want to change the normal flow of loops. Two important statements help with this:
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.
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).
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
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
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.
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
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
When to use: When solving problems with multiple decision points or nested iterations.
When to use: Choosing the appropriate loop structure for a problem.
When to use: When searching for an element or condition inside a loop.
When to use: When writing loops that iterate over arrays or ranges.
When to use: Debugging complex nested loops.
Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.
Go to practice →