Use pseudocode to write: a ''CASE'' structure

Resources | Subject Notes | Computer Science

CASE Structure in Pseudocode

11.2 Constructs: CASE Structure

Objective

This section focuses on using pseudocode to represent a CASE structure, a control flow construct used for multi-way branching.

What is a CASE Structure?

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.

Pseudocode Syntax

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

Example: Grading System

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:

  • Score 90 or above: A
  • Score 80 to 89: B
  • Score 70 to 79: C
  • Score 60 to 69: D
  • Score below 60: F

Pseudocode Implementation

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

Explanation

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.

Advantages of using CASE

  • More readable and organized than nested if-else statements, especially for multiple possible outcomes.
  • Can improve code clarity and maintainability.