Resources | Subject Notes | Computer Science
This section focuses on using pseudo-code to represent conditional logic using 'IF' statements, including the 'ELSE' clause and nested 'IF' statements. Understanding these constructs is fundamental for creating programs that can make decisions and execute different blocks of code based on specific conditions.
An `IF` statement allows a program to execute a block of code only if a certain condition is true. The `ELSE` clause provides an alternative block of code to execute if the condition in the `IF` statement is false.
Pseudo-code:
IF condition THEN // Code to execute if the condition is true ELSE // Code to execute if the condition is false ENDIF
Example: Determine if a number is positive, negative, or zero.
Step | Pseudo-code |
---|---|
1. Get the number | Let number = input_number |
2. Check if the number is greater than 0 | IF number > 0 THEN |
3. If true, display "Positive" | Display "Positive" |
4. Else, check if the number is less than 0 | ELSE IF number < 0 THEN |
5. If true, display "Negative" | Display "Negative" |
6. Else, display "Zero" | ELSE |
7. Display "Zero" | Display "Zero" |
8. End the IF statement | ENDIF |
Nested `IF` statements allow you to create more complex decision-making structures. This involves placing an `IF` statement inside another `IF` statement. This is useful when you need to evaluate multiple conditions.
Pseudo-code:
IF condition1 THEN // Code to execute if condition1 is true IF condition2 THEN // Code to execute if condition1 and condition2 are both true ELSE // Code to execute if condition1 is true but condition2 is false ENDIF ELSE // Code to execute if condition1 is false ENDIF
Example: Determine the grade based on a student's score.
Step | Pseudo-code |
---|---|
1. Get the student's score | Let score = input_score |
2. Check if the score is greater than or equal to 90 | IF score >= 90 THEN |
3. If true, display "Grade: A" | Display "Grade: A" |
4. Else, check if the score is greater than or equal to 80 | ELSE IF score >= 80 THEN |
5. If true, display "Grade: B" | Display "Grade: B" |
6. Else, check if the score is greater than or equal to 70 | ELSE IF score >= 70 THEN |
7. If true, display "Grade: C" | Display "Grade: C" |
8. Else, display "Grade: D" | ELSE |
9. Display "Grade: D" | Display "Grade: D" |
10. End the IF statement | ENDIF |