Task: Prompt the user to enter two numbers as operands (type double), then print
ID: 3750603 • Letter: T
Question
Task: Prompt the user to enter two numbers as operands (type double), then print a menu to let user know what options are available. Read the user’s selection to determine which operation the user has chosen. Use a switch statement with user input as the switch expression. Your switch has to provide two cases for each operation; for example “ADD” or “+“. For example, if the user enters ADD (in any combination of uppercase or lowercase letters) or a plus sign (+), your program will execute the addition and output the result. You should format your output to two decimal places.
Explanation / Answer
Language: C
Here's the code:
#include <stdio.h>
int main()
{
double a,b;
char c;
printf("Please select an operation from the following options: ");
printf("Press + for addition ");
printf("Press - for subtraction ");
printf("Enter your choice: ");
scanf("%c", &c);
switch(c)
{
case '+':
printf ("Please enter two numbers as operands (double): ");
scanf (" %lf %lf",&a, &b);
printf(" Addition of entered numbers are: %.2lf",a+b);
break;
case '-':
printf ("Please enter two numbers as operands (double): ");
scanf (" %lf %lf",&a, &b);
printf(" Subtraction of given numbers are: %.2lf", a-b);
break;
default:
printf (" Please select a valid option");
printf(" press Enter key to exit"); break;
}
getch();
return 0;
}
Output:
Please select an operation from the following options:
Press + for addition
Press - for subtraction
Enter your choice:
+
Please enter two numbers as operands (double):
210.12
993.114
Addition of entered numbers are: 1203.23
Please select an operation from the following options:
Press + for addition
Press - for subtraction
Enter your choice:
*
Please select a valid option
press Enter key to exit
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.