Question 3: modify a program [7.5]
Re-write the program below so that it does not use the switch statement but the behaviour appears the same to the user (i.e. use an appropriate collection of if/else statements).
#include <cstdio> int main() { int userChoice, valuesRead; printf("Please enter an integer in the range 1-5\n"); valuesRead = scanf("%d", &userChoice); if (valuesRead > 0) { printf("That was not an integer\n"); return 0; } switch(userChoice) { case 2: case 4: printf("An even number chosen\n"); break; case 3: printf("Middle value chosen\n"); break; case 1: case 5: printf("Boundary value chosen\n"); break; default: printf("Invalid value chosen\n"); break; } return 0; } |
SAMPLE SOLUTION // replacing just the switch if ((userChoice == 2) || (userChoice == 4)) { printf("An even number chosen\n"); } else if (userChoice == 3) { printf("Midle value chosen\n"); } else if ((userChoice == 1) || (userChoice == 5)) { printf("Boundary value chosen\n"); } else { printf("Invalid value chosen\n"); } |