Question
Instead of repeating the same code five times (CODE BELOW) , you can use a loop to reduce the code length. Modify the program to
Instead of repeating the same code five times (CODE BELOW), you can use a loop to reduce the code length. Modify the program to use a for loop to ask the user for a character. Use an input function such as getchar() to input the character. You should display a menu to the user such as Menu: d,y,m,t each time the user is supposed to input a character.
Note: 1) for loops are supported in the C99 standard, so you must use the -std=c99 flag in your gcc command to compile a program using a for loop. Also note that C99 supports different functions, so some of your functions may need to be updated to a supported version. 2) You may need to call getchar() and then getc() to flush the newline character left behind by the previous getchar();
CODE:
/* This C program demonstrates the switch statement without using breaks. */
/* The program is tested with GCC and MS Visual C++ platform */
#include
void main() {
int date = 29;
int year = 2018;
int month = 1;
float time = 02.30; // For example: 10.45 So 2 digits for hours, 2 digit for minutes
char ch;
ch = 'd';
printf("ch = %c ", ch);
switch (ch) {
case 'd': printf("Date : %d ", date); break;
case 'y': printf("Year : %d ", year); break;
case 'm': printf("Month : %d ", month); break;
case 't': printf("Time : %02.2f ", time); break;
default: printf("invalid operator ");
}
ch = 'y';
printf("ch = %c ", ch);
switch (ch) {
case 'd': printf("Date : %d ", date); break;
case 'y': printf("Year : %d ", year); break;
case 'm': printf("Month : %d ", month); break;
case 't': printf("Time : %02.2f ", time); break;
default: printf("invalid operator ");
}
ch = 'm';
printf("ch = %c ", ch);
switch (ch) {
case 'd': printf("Date : %d ", date); break;
case 'y': printf("Year : %d ", year); break;
case 'm': printf("Month : %d ", month); break;
case 't': printf("Time : %02.2f ", time); break;
default: printf("invalid operator ");
}
ch = 't';
printf("ch = %c ", ch);
switch (ch) {
case 'd': printf("Date : %d ", date); break;
case 'y': printf("Year : %d ", year); break;
case 'm': printf("Month : %d ", month); break;
case 't': printf("Time : %02.2f ", time); break;
default: printf("invalid operator ");
}
ch = 'D';
printf("ch = %c ", ch);
switch (ch) {
case 'd': printf("Date : %d ", date); break;
case 'y': printf("Year : %d ", year); break;
case 'm': printf("Month : %d ", month); break;
case 't': printf("Time : %02.2f ", time); break;
default: printf("invalid operator ");
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started