Search⌘ K

More Examples of Multiway if Statements

In this lesson, we will look at some more examples related to multiway if statements.

Example

Let’s consider part of a program that assigns a letter grade—A through F—to an integer exam score ranging from 0 to 100. Grades are assigned as follows:

  • A 90 to 100
  • B 80 to 89
  • C 70 to 79
  • D 60 to 69
  • F Below 60

We offer five different solutions to this problem. Each one uses the variables

int  score;
char grade;

and assumes that score contains an integer ranging from 0 to 100. All solutions are correct, but not all are good, as we will see.

Solution 1

The first solution clearly indicates the range of scores for each letter grade. Run the program with various values of the score.

Java
/** Solution 1 - Clear, efficient logic. */
public class Grader1
{
public static void main(String args[])
{
char grade;
int score = 71; // FEEL FREE TO CHANGE THE SCORE
if ((score >= 90) && (score <= 100))
grade = 'A';
else if ((score >= 80) && (score <= 89))
grade = 'B';
else if ((score >= 70) && (score <= 79))
grade = 'C';
else if ((score >= 60) && (score <= 69))
grade = 'D';
else
grade = 'F';
System.out.println("A score of " + score + " gives a grade of " + grade + ".");
} // End main
} // End Grader1

Solution 2

The second solution is similar to ...