Control Structures contd… Selection Dr. Khizar Hayat Associate Prof. of Computer Science
Multiway if…else Example int main() { int day; cout<<"Enter the value for day"<<endl; cin>>day; if(day==1) cout << "Monday"; } else if(day==2) cout << “Tuesday"; if(day==3) cout << “Wednesday"; : if(day==7) cout << “Sunday"; cout << “Invalid input"; }….}} return(0); Example A program that inputs the day number and display the day name’ i.e. 1 for Monday 2 for Tuesday 3 for Wednesday … 7 for Sunday
Multiway if…else Example int main() { int day; cout<<"Enter the value for day"<<endl; cin>>day; if(day==1) cout << “Monday"; } else if(day==2) cout << “Tuesday"; else if(day==3) cout << “Wednesday"; else if(day==4) cout << “Thursday"; : else if(day==7) cout << “Sunday"; else cout<<“Invalid Input"; return(0); Example A program that inputs the day number and display the day name’ i.e. 1 for Monday 2 for Tuesday 3 for Wednesday … 7 for Sunday
Multiway if…else Example int main() { int day; cout<<"Enter the value for day"<<endl; cin>>day; if(day==1) cout << “Monday"; else if(day==2) cout << “Tuesday"; else if(day==3) cout << “Wednesday"; else if(day==4) cout << “Thursday"; else if(day==5) cout << “Friday"; else if(day==6) cout << “Satursday"; else if(day==7) cout << “Sunday"; else cout<<“Invalid Input"; return(0); } Example A program that inputs the day number and display the day name’ i.e. 1 for Monday 2 for Tuesday 3 for Wednesday … 7 for Sunday
The switch structure switch(expression) //The term in ()is called the selector { case constant1: //constant1 also called label Statement(s); break; //needed to skip the rest of the cases case constant2: break; . default //optional part }
The switch int main(void) { int day; cout << "Enter the day of the week between 1 and 7"; cin >> day; switch(day) case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; case 3: cout << "Wednesday"; case 4: cout << "Thursday"; case 5: cout << "Friday"; case 6: cout << "Saturday"; case 7: cout << "Sunday"; default: //optional cout << “Invalid Input"; } return(0); Example A program that inputs the day number and display the day name’ i.e. 1 for Monday 2 for Tuesday 3 for Wednesday … 7 for Sunday
The switch structure The switch keyword. Same as if…else if….else but limited; Can only be used to compare an expression against constants The case labels must have the same type as the selector The case labels must all be different You can associate more than one case labels with the same statement. No need to use the delimiters ‘{}’ in case statement(s); Omitting or forgetting break in a case is not a syntax error but a logical error. It would take you to the subsequent case part No need to write break in the default case but good for readability.
Problems Write a program that takes a character input and tells you whether it is a vowel or not. We may introduce getche() from conio.h displaying a menu in a program.