Resources | Subject Notes | Computer Science | Lesson Plan
This section explores the use of nested selection statements (if-else within if-else) and various iteration statements (loops) in programming. Understanding these concepts is crucial for creating programs that can handle complex decision-making and repetitive tasks.
Nested selection allows you to create more intricate decision-making structures. This involves placing an `if` statement inside another `if` or `else` block. This is useful when you need to evaluate multiple conditions.
Example: Determining if a number is within a specific range and also positive.
Consider a scenario where you want to check if a student's score is above a certain threshold and also if they have attended at least 80% of the classes. This requires nesting selection statements.
Syntax:
if (condition1) { // Code to execute if condition1 is true if (condition2) { // Code to execute if condition1 AND condition2 are true } else { // Code to execute if condition1 is true but condition2 is false } } else { // Code to execute if condition1 is false }
The following Python code demonstrates nested selection to determine if a number is within a range and positive.
number = 25 if number > 10: print("The number is greater than 10.") if number > 20: print("The number is also greater than 20.") else: print("The number is between 10 and 20.") else: print("The number is not greater than 10.")
Iteration statements allow you to repeat a block of code multiple times. The main types of iteration statements are for
and while
loops.
A for
loop is used to iterate over a sequence (e.g., a list, a string, or a range of numbers). It executes the code block for each item in the sequence.
Syntax:
for (variable in sequence) { // Code to execute for each item in the sequence }
This Python code uses a for
loop to print numbers from 1 to 5.
for i in range(1, 6): print(i)
A while
loop executes a block of code repeatedly as long as a specified condition is true.
Syntax:
while (condition) { // Code to execute as long as the condition is true }
This Python code uses a while
loop to print numbers from 1 to 5.
i = 1 while i <= 5: print(i) i = i + 1
Feature | Selection | Iteration |
---|---|---|
Purpose | Execute different blocks of code based on conditions. | Repeat a block of code multiple times. |
Types | If-else, Nested If-else | For, While |
Use Cases | Decision-making, branching in programs. | Repetitive tasks, processing collections of data. |
It is common to combine selection and iteration statements to create more powerful and flexible programs. For example, you might use a for
loop to iterate over a list of items and then use an if
statement to perform a different action for each item based on a certain condition.