192k views
4 votes
A student developed a program that outputs the name of a fruit that begins with a letter, dependent upon the variable keyPressed, which stores the letter (from A to Z only) a user types on the keyboard. Below is a section of code from her program: Which of the following descriptions below would be a way that this student might have written the rest of her code so that it executes as intended?

1) Using a switch statement with cases for each letter of the alphabet
2) Using if-else statements for each letter of the alphabet
3) Using a for loop to iterate through each letter of the alphabet
4) Using a while loop to iterate through each letter of the alphabet

1 Answer

5 votes

Final answer:

The student's program to output fruit names based on a typed letter can be effectively written using a switch statement or if-else statements. The correct option is B.

Step-by-step explanation:

The student developed a program that outputs the name of a fruit based on the letter typed on the keyboard. Among the options provided, the student might have written her code using one of the following approaches:

  1. Using a switch statement with cases for each letter of the alphabet.
  2. Using if-else statements for each letter of the alphabet.
  3. Using a for loop to iterate through each letter of the alphabet.
  4. Using a while loop to iterate through each letter of the alphabet.

However, since the requirement is to output a fruit name corresponding to a single letter given as input, the use of iterative loops like for loops and while loops is less practical. The most suitable methods would be to use a switch statement or if-else statements, each branching out depending on the value of the variable keyPressed. These methods allow you to associate a fruit name with each possible input letter without repeatedly iterating through the alphabet.

User Generalpiston
by
7.6k points