If Else Switch Case in C++ Programming
If..Else and Swicth..Case construct
in C++ Programming
When we have multiple conditions to
check and act accordingly, we can use If..Else or Switch..Case.
/*Following Program Displays
Corresponding Day Name. 1 prints Sunday, 2 Prints Monday and so onā¦. */
Line 1.
#include<iostream.h>
Line 2.
void
main()
Line 3.
{
Line 4.
int
a;
Line 5.
cout<<āEnter
A Number between 1 to 7 ā;
Line 6.
cin>>a;
Line 7.
if(a==1)
Line 8.
{
Line 9.
cout<<āSundayā;
Line 10. }
Line 11. if(a==2)
Line 12. {
Line 13. cout<<āMondayā;
Line 14. }
Line 15. if(a==3)
Line 16. {
Line 17. cout<<āTuesdayā;
Line 18. }
Line 19. if(a==4)
Line 20. {
Line 21. cout<<āWednesdayā;
Line 22. }
Line 23. if(a==5)
Line 24. {
Line 25. cout<<āThursdayā;
Line 26. }
Line 27. if(a==6)
Line 28. {
Line 29. cout<<āFridayā;
Line 30. }
Line 31. if(a==7)
Line 32. {
Line 33. cout<<āSaturdayā;
Line 34. }
Line 35. else
Line 36. {
Line 37. cout<<āSorry !!! Wrong Input.ā;
Line 38. }
Line 39. }
Now we can get the same result from
the following program using switch..case
/*Following Program Displays
Corresponding Day Name. 1 prints Sunday, 2 Prints Monday and so onā¦. */
Line 1.
#include<iostream.h>
Line 2.
void
main()
Line 3.
{
Line 4.
int
a;
Line 5.
cout<<āEnter
A Number between 1 to 7 ā;
Line 6.
cin>>a;
Line 7.
switch(a)
Line 8.
{
Line 9.
case
1: cout<<āSundayā;
Line 10. case 2: cout<<āMondayā;
Line 11. case 3:cout<<āTuesdayā;
Line 12. case 4:cout<<āWednesdayā;
Line 13. case 5:cout<<āThursdayā;
Line 14. case 6:cout<<āFridayā;
Line 15. case 7:cout<<āSaturdayā;
Line 16. default: cout<<āSorry !!! Wrong
Input.ā;
Line 17. }
Line 18. }
In Switch Case, default does the work
as of else part in an Ifā¦Else construct. Now if
we run the above program we get some unexpected results. If we enter the value
of a as 2. We get Monday, Tuesday, Wednesdayā¦.Sorry Wrong Input.
Why because in switch case, there is
a behavior called āFALL THROUGHā which means when a matching case is found, it
automatically reaches all the cases defined below the matched case till we get
break or end of switch. So we need to modify the above code to get desired
results:
Line 1.
#include<iostream.h>
Line 2.
void
main()
Line 3.
{
Line 4.
int
a;
Line 5.
cout<<āEnter
A Number between 1 to 7 ā;
Line 6.
cin>>a;
Line 7.
switch(a)
Line 8.
{
Line 9.
case
1: cout<<āSundayā; break;
Line 10. case 2: cout<<āMondayā; break;
Line 11. case 3:cout<<āTuesdayā; break;
Line 12. case 4:cout<<āWednesdayā;
break;
Line 13. case 5:cout<<āThursdayā; break;
Line 14. case 6:cout<<āFridayā; break;
Line 15. case 7:cout<<āSaturdayā; break;
Line 16. default: cout<<āSorry !!! Wrong
Input.ā;
Line 17. }
Line 18. }
Comments
Post a Comment