/* Part 1: declare an integer variable named season whose valid values are 1, 2,
ID: 3604535 • Letter: #
Question
/* Part 1: declare an integer variable named season whose valid values are 1, 2, 3 and 4 which represent the seasons winter, spring, summer and fall respectively, and any other variables you might need for Parts 2 & 3 */
/* Part 2: write a loop that contains a switch statement that prints out an appropriate message for each of the valid values for the variable season and indicate an invalid value otherwise. */
/* Part 3 write a loop that contains a nested if statement that prints out an appropriate message for valid values of the variable season, and indicates an invalid value otherwise. */
*Please write program.
Explanation / Answer
Implemented code as per the requirement. As there is no specific programming laguage mentioned, I've done the coding in Java. Please comment if you need it any other language.(C,C++,C#, Pytho etc..)
Code for switch case usage:
=======================
#include <iostream>
using namespace std;
int main() {
int inp = -1;
while(!(inp>=0 && inp<=4)){
cout<<"Enter a valid season number(1-4) or 0 to stop: ";
cin>>inp;
}
switch(inp){
case 1: //1 for winter
cout<< "Current season is winter.";
break;
case 2://2 for sprin
cout<< "Current season is spring..";
break;
case 3://3 for summer
cout<< "Current season is summer.";
break;
case 4://4 for fall
cout<< "Current season is fall.";
break;
case 0://0 to exit
cout<< "Exiting from the program. Thank you..";
break;
default://default case for invalid input
cout<< "You have entered invalid season number.. ";
}
}
Code with nested if usage:
=============================
#include <iostream>
using namespace std;
int main() {
int inp = -1;
while(!(inp>=0 && inp<=4)){
cout<<"Enter a valid season number(1-4) or 0 to stop: ";
cin>>inp;
}
if(inp==1){
cout<< "Current season is winter.";
}
else if(inp == 2){//2 for sprin
cout<< "Current season is spring..";
}
else if(inp == 3){//3 for summer
cout<< "Current season is summer.";
}
else if(inp == 4){//4 for fall
cout<< "Current season is fall.";
}
else if(inp == 0){//0 to exit
cout<< "Exiting from the program. Thank you..";
}
else{//default case for invalid input
cout<< "You have entered invalid season number.. ";
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.