C / C++ Courses ? 13 (Switch)

6 September 2011 1,730 views No comments Switch

Switch is a selection structure just like if, if/else. It is not a repetition structure. Important points of using switch:

? We use switch while checking one variable with different outcomes with more than one value.

? It should be equality. Comparison (< or >) won’t work with switch.

In switch, only integer can be used, not other types. But character is also acceptable, because as you know, character has also an integer value which is ASCII code. So we can say, every switch can be written with if/else, but every if/else can not!

Example:

#include<stdio.h>
int main(){
int x, y;
printf(“Enter a number: “);
scanf(“%d”, &x);
if(x==1)
y=3+x*5;
else if(x==2)
y=5*x%2;
else
y=0;
printf(“%d”, &y);
return 0;
}

//We can write the same if/else example with switch:

#include<stdio.h>
int main(){
int x, y;
printf(“Enter a number: “);
scanf(“%d”, &x);
switch(x){
case 1:
y=3+x*5;
break;
case 2:
y=5*x%2;
break;
default:
y=0;
break;
}
printf(“%d”, &y);
return 0;
}

After every case of switch, we need to write break statement. If we don’t write, it will be a logical error. For example ; if we don’t write break statement after ‘case 2’, the value of y will be zero.

Example: Write a program that inputs for 10 characters. If the character is ‘y’ print ‘Yes’, if ‘n’ print ‘No’. If anything else, then print ‘Wrong character’.

int x;
char ch;
for(x=1; x<=10; x++){
printf(” Enter ‘y’ or ‘n’ “):
scanf(“%c”, &ch);
switch(a){
case ‘y’:
printf(“Yes”);
break;
case ‘n’:
printf(“No”);
break;
default:
printf(“Wrong Character”);
break;
}
}

See you guys! 😉

Ziynet Nesibe