Finding odd even number using a switch case
Finding if the given number is odd or even using a switch-case construct.
Learning Objectives
- Checking for true false condition or 1 or 0 condition in the switch().
- Check for only two cases in switch construct. No default case is there.
Source Code
|
|
Run Output
Code Understanding
switch(n%2)
The condition check here will result in 0 or 1, thus we can check these two cases further.
case 0: cout<<“Even”;break;
n%2 will produce 0 when number is even because no remainder will be left.
case 1: cout<<“Odd”;break;
n%2 will produce 1 when number is odd because remainder will be 1.
Notes
- The alternate method of using if else may be more efficient and direct, but this method gives the use of condition in the switch() check instead of a direct int or char variable, so this example is important for educative purposes.
Suggested Filename(s): oddeven-sc.spp
Created: 31-Dec-2017 02:33 | Updated: 15-Sep-2018 12:00|
