Resources | Subject Notes | Computer Science
This section focuses on using pseudocode to represent a CASE
structure, a control flow construct used for multi-way branching.
A CASE
structure is a powerful control flow statement that allows a program to execute different blocks of code based on the value of an expression. It provides an alternative to nested if-else
statements, especially when dealing with a large number of possible values.
The general syntax for a CASE
structure in pseudocode is as follows:
CASE expression WHEN value1 THEN // Code to execute if expression equals value1 WHEN value2 THEN // Code to execute if expression equals value2 ... WHEN valueN THEN // Code to execute if expression equals valueN ELSE // Optional: Code to execute if none of the WHEN conditions are met END CASE
Let's consider a simple example of a grading system where a student's score determines their grade.
Suppose a student's score is read from the user. The program should then determine the corresponding grade based on the following ranges:
Here's the pseudocode for this grading system using a CASE
structure:
Line Number | Pseudocode |
---|---|
1 | BEGIN |
2 | INPUT student_score |
3 | CASE student_score |
4 | WHEN student_score >= 90 THEN |
5 | DISPLAY "Grade: A" |
6 | WHEN student_score >= 80 AND student_score < 90 THEN |
7 | DISPLAY "Grade: B" |
8 | WHEN student_score >= 70 AND student_score < 80 THEN |
9 | DISPLAY "Grade: C" |
10 | WHEN student_score >= 60 AND student_score < 70 THEN |
11 | DISPLAY "Grade: D" |
12 | WHEN student_score < 60 THEN |
13 | DISPLAY "Grade: F" |
14 | ELSE |
15 | DISPLAY "Invalid Score" |
16 | END CASE |
17 | END |
The CASE
structure evaluates the student_score
. It then compares this score against each WHEN
condition in order. If a condition is met, the corresponding code block is executed. The ELSE
block is executed if none of the WHEN
conditions are true. It's important to note that the conditions are evaluated sequentially, and only the first matching condition's block is executed.
if-else
statements, especially for multiple possible outcomes.