switch is like if, but when u have to check for more possibilities, it would be hard, so u use switch
syntax:
switch(a)
{
a_1 : do_1
a_2 : do_2
a_3 : do_3
...
a_n : do_n
}
example, a simple prog (u have to input a number between 1 and 5)
Code:
#include <stdio.h>
int main()
{
int a;
printf("Please input a number (1-5): ");
scanf("%d", &a);
switch(a){
case 1: printf("one\n");
break;
case 2: printf("two\n");
break;
case 3: printf("three\n");
break;
case 4: printf("four\n");
break;
case 5: printf("five\n");
break;
}
return 0;
}
u use break to stop the prog going on checking the other cases in the switch
another example:
Code:
#include <stdio.h>
int main()
{
int a;
printf("Please input a number (1-5): ");
scanf("%d", &a);
switch(a)
{
case 1: printf("one or...");
case 2: printf("...two \n");
break;
case 3: printf("three\n");
break;
case 4: printf("four...");
case 5: printf("...or five \n");
break;
}
return 0;
}
What happens, if someone inputs a number: n<1 or n>5
here another example:
Code:
#include <stdio.h>
int main()
{
int a,b;
char opera;
printf("Calculating \n");
printf(" (number)(operator)(number) no spaces\n");
printf("Input your numbers: ");
scanf("%d%c%d", &a, &opera, &b);
switch(opera){
case '+': printf("%d + %d = %d \n",a ,b ,a+b);
break;
case '-': printf("%d - %d = %d \n", a, b, a-b);
break;
case '*': printf("%d * %d = %d \n", a, b, a*b);
break;
case '/': printf("%d / %d = %d \n", a, b, a/b);
break;
default: printf("%c : no operator\n", opera);
}
return 0;
}
When somebody inputs nothing or something wrong insteads of the operators (+,-,/,*) the prog uses the default case, and outputs an error.
When ur c++ programmer, u can also use cout instead of printf and cin instead of scanf