Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
CBSE Class 11 Computer Science Chapter 6: Flow of Control
In the previous chapter you wrote simple programs that executed line by line from top to bottom. Real-world programs need to make decisions and repeat actions. Flow of control refers to the order in which statements are executed. Python provides conditional statements (if, elif, else) for decision-making and loops (for, while) for repetition. This chapter covers both in depth, along with loop control statements break, continue, and pass.
Key Definitions
| Term | Definition |
|---|---|
| Flow of Control | The order in which statements are executed in a program |
| Sequential Flow | Statements execute one after another from top to bottom |
| Selection | Choosing between alternative paths based on a condition (if-elif-else) |
| Repetition | Executing a block of statements multiple times (loops) |
| Condition | An expression that evaluates to True or False |
| Loop | A construct that repeats a block of code while a condition is True |
| Iteration | One complete execution of the loop body |
| Infinite Loop | A loop that never terminates because its condition never becomes False |
| Nested Loop | A loop placed inside another loop |
| break | A statement that immediately exits the innermost loop |
| continue | A statement that skips the rest of the current iteration and moves to the next |
| pass | A null statement that does nothing — used as a placeholder |
Detailed Concepts
1. Conditional Statements
Conditional statements let a program choose different paths based on conditions.
The if Statement
Executes a block only when the condition is True.
# Syntax
if condition:
statement(s)
# Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote")
Important: The colon : after the condition is required. The indented block (4 spaces) is the body that runs when the condition is True.
The if-else Statement
Provides two paths: one for True, one for False.
# Syntax
if condition:
statement(s) # runs when condition is True
else:
statement(s) # runs when condition is False
# Example
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
The if-elif-else Statement (Chained Conditionals)
Checks multiple conditions in order. The first True condition's block executes, and the rest are skipped.
# Syntax
if condition1:
statement(s)
elif condition2:
statement(s)
elif condition3:
statement(s)
else:
statement(s)
# Example: Grading system
marks = int(input("Enter your marks (0-100): "))
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: F")
Key points about elif:
- You can have any number of
elifblocks. - The
elseblock is optional and runs only when no condition is True. - Conditions are checked from top to bottom. Once a True condition is found, its block runs and the entire chain exits.
- The
elsemust always come last.
Nested if Statements
An if statement inside another if statement. Used when you need to check a condition only after another condition is already True.
# Example: Check if a number is positive and then if it is even
num = int(input("Enter a number: "))
if num > 0:
print(f"{num} is positive")
if num % 2 == 0:
print(f"{num} is also even")
else:
print(f"{num} is also odd")
elif num == 0:
print("The number is zero")
else:
print(f"{num} is negative")
# Example: Leap year check
year = int(input("Enter a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
2. The for Loop
The for loop iterates over a sequence (string, list, tuple, range) or any iterable object. Use it when you know how many times to repeat.
Syntax
for variable in sequence:
statement(s)
Iterating with range()
The range() function generates a sequence of integers.
# range(stop) — generates 0, 1, 2, ..., stop-1
for i in range(5):
print(i, end=" ")
# Output: 0 1 2 3 4
# range(start, stop) — generates start, start+1, ..., stop-1
for i in range(2, 7):
print(i, end=" ")
# Output: 2 3 4 5 6
# range(start, stop, step) — with custom step
for i in range(1, 10, 2):
print(i, end=" ")
# Output: 1 3 5 7 9
# Negative step — counting backwards
for i in range(10, 0, -1):
print(i, end=" ")
# Output: 10 9 8 7 6 5 4 3 2 1
Iterating Over Strings
# Print each character
for ch in "Python":
print(ch)
# P
# y
# t
# h
# o
# n
# Print with index using range and len
word = "Hello"
for i in range(len(word)):
print(f"Index {i}: {word[i]}")
Iterating Over Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using index
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
Practical for Loop Examples
# Sum of first N natural numbers
n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print(f"Sum of first {n} natural numbers = {total}")
# Multiplication table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
# Factorial
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"Factorial of {n} = {fact}")
3. The while Loop
The while loop repeats as long as its condition is True. Use it when the number of iterations is not known in advance.
Syntax
while condition:
statement(s)
The condition is checked before each iteration. If it is False from the start, the loop body never executes.
# Print numbers 1 to 5
i = 1
while i <= 5:
print(i, end=" ")
i += 1
# Output: 1 2 3 4 5
# Sum of digits of a number
num = int(input("Enter a number: "))
temp = num
digit_sum = 0
while temp > 0:
digit_sum += temp % 10
temp //= 10
print(f"Sum of digits of {num} = {digit_sum}")
# Reverse a number
num = int(input("Enter a number: "))
temp = num
rev = 0
while temp > 0:
rev = rev * 10 + temp % 10
temp //= 10
print(f"Reverse of {num} = {rev}")
Sentinel-Controlled while Loop
# Enter scores until user types -1 to stop
total = 0
count = 0
score = int(input("Enter score (-1 to stop): "))
while score != -1:
total += score
count += 1
score = int(input("Enter score (-1 to stop): "))
if count > 0:
average = total / count
print(f"Average = {average:.2f}")
else:
print("No scores entered.")
4. Loop Control Statements
break
The break statement immediately terminates the innermost loop. Execution continues with the statement after the loop.
# Find first number divisible by 7 in a range
for i in range(1, 100):
if i % 7 == 0:
print(f"First multiple of 7 is {i}")
break
# Output: First multiple of 7 is 7
# Search for an element in a list
numbers = [3, 7, 12, 5, 9, 21]
target = 9
found = False
for num in numbers:
if num == target:
found = True
print(f"Found {target}!")
break
if not found:
print(f"{target} not found")
continue
The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.
# Print only odd numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=" ")
# Output: 1 3 5 7 9
# Skip vowels in a string
text = "Hello World"
for ch in text:
if ch.lower() in "aeiou":
continue
print(ch, end="")
# Output: Hll Wrld
pass
The pass statement is a null operation — it does nothing. Use it as a placeholder where syntax requires a statement but you have nothing to write yet.
# Placeholder for future code
for i in range(5):
pass # TODO: implement later
# Empty if block
x = 10
if x > 0:
pass # will add logic later
else:
print("Negative")
5. Nested Loops
A loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
# Pattern 1: Right-angled triangle
n = 5
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
# Output:
# *
# * *
# * * *
# * * * *
# * * * * *
# Pattern 2: Number triangle
n = 5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
# Output:
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
# Pattern 3: Inverted triangle
n = 5
for i in range(n, 0, -1):
for j in range(i):
print("*", end=" ")
print()
# Output:
# * * * * *
# * * * *
# * * *
# * *
# *
# Multiplication table (1 to 5)
for i in range(1, 6):
for j in range(1, 11):
print(f"{i * j:4}", end="")
print()
Important: In nested loops, break and continue affect only the innermost loop they are in.
6. Infinite Loops
An infinite loop runs forever because its condition never becomes False. These are usually bugs, but sometimes intentional (event loops, servers).
# Accidental infinite loop — FORGOT to update i
i = 1
while i <= 5:
print(i)
# missing: i += 1
# Accidental infinite loop — wrong update
i = 1
while i <= 5:
print(i)
i -= 1 # i keeps decreasing, never reaches > 5
How to avoid infinite loops: 1. Always update the loop variable inside a while loop body. 2. Make sure the update moves the variable toward the termination condition. 3. Use for loops when the number of iterations is known — they cannot be infinite. 4. Press Ctrl+C in the terminal to stop a runaway program.
Intentional infinite loop with break:
# Keep asking until valid input
while True:
age = int(input("Enter age (1-120): "))
if 1 <= age <= 120:
break
print("Invalid age. Try again.")
print(f"Your age is {age}")
7. else Clause with Loops
Python allows an else block after for and while loops. The else block executes only when the loop completes normally — not when the loop is terminated by break.
# for-else: check if a number is prime
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(f"{n} is not prime (divisible by {i})")
break
else:
print(f"{n} is prime")
# while-else: search with break
numbers = [4, 2, 9, 7, 5]
target = 3
i = 0
while i < len(numbers):
if numbers[i] == target:
print(f"Found {target} at index {i}")
break
i += 1
else:
print(f"{target} not found in the list")
Remember: The else clause does NOT run if break is executed. It runs only when the loop finishes all iterations without hitting a break.
8. Comparison: for Loop vs while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Use when | Number of iterations is known | Number of iterations is unknown |
| Initialization | Handled by range() or sequence | Must be done before the loop |
| Update | Automatic (next item in sequence) | Must be done inside the loop body |
| Can be infinite | No (finite sequence) | Yes (if condition never becomes False) |
| else clause | Supported | Supported |
| Iterates over | Sequences (list, string, range) | Condition (boolean expression) |
| Typical use | Counting, iterating collections | Input validation, sentinel-controlled loops |
Common Mistakes
1. Missing colon after if/elif/else/for/while: Writing if x > 0 instead of if x > 0: causes a SyntaxError.
2. Forgetting to indent the block: After the colon, the block must be indented (4 spaces). Unindented code is not part of the conditional or loop.
3. Using = instead of == in conditions: while x = 5: is a SyntaxError. Use while x == 5: for comparison.
4. Infinite while loop from missing update: Forgetting i += 1 (or equivalent) inside a while loop causes the loop to run forever.
5. Incorrect range boundaries: range(1, 10) gives 1 through 9, NOT 10. Use range(1, n + 1) to include n.
6. Misunderstanding break scope: break exits only the innermost loop, not all loops. In a nested loop, the outer loop continues after the inner loop breaks.
7. Using elif as the first condition: An elif must come after an if. Starting a conditional chain with elif is a SyntaxError.
8. Confusing continue with break: continue skips the rest of the current iteration and goes to the next. break exits the entire loop. They are not interchangeable.
Exam Tips
1. Trace tables are your best friend: For output prediction questions, create a table with columns for each variable and the loop counter. Update values line by line.
2. Know range() inside out: range(n) starts at 0, range(a, b) starts at a, range(a, b, c) uses step c. None of them include the stop value.
3. Practice pattern programs: Star patterns and number patterns are common in exams. Draw the pattern on paper first, then code row by row using nested loops.
4. Understand the else clause with loops: The else after a loop runs when the loop completes without a break. This is tested frequently.
5. Write clean indentation: Use exactly 4 spaces. In the exam, improper indentation loses marks and may change program logic.
6. Check edge cases: What happens if the user enters 0, a negative number, or 1? Test boundary values mentally before writing your answer.
7. Use meaningful variable names: num, count, total are clearer than x, y, z. Examiners prefer readable code.
8. Add comments: Start every program with # Program to ... and comment tricky logic. This earns you marks for documentation.
Quick Revision Notes
- Flow of control determines the order of statement execution: sequential, selection, or repetition.
- if executes a block when the condition is True; if-else provides two paths; if-elif-else chains multiple conditions.
- Nested if checks a condition inside another conditional block.
- for loop iterates over a sequence; best when the number of iterations is known.
- range(start, stop, step) generates integers from start to stop-1 with the given step.
- while loop repeats while a condition is True; best when the number of iterations is unknown.
- break exits the innermost loop immediately.
- continue skips the rest of the current iteration and moves to the next.
- pass does nothing — used as a placeholder.
- Nested loops have a loop inside another loop; inner loop runs fully for each outer iteration.
- Infinite loops occur when the while condition never becomes False; always update the loop variable.
- else with loops executes when the loop finishes normally (no break encountered).
- Use for when iterations are known, while when they depend on a runtime condition.
- Always use a colon after if/elif/else/for/while and indent the block with 4 spaces.
- break and continue affect only the innermost loop in nested loop structures.
