Switch statement
This is a branch (multiple) statement which provides easiest way to execute different parts of the code leased on the value of the expression.
it is a central statement that allows a value to change control of execution.
Rules -
- The expression/condition provided in the switch should return in a constant value otherwise it would not be valid.
switch(n) // n = ( int,char,n=10,n=a+b+c [where a,b,c = constant ] ,n=5+3+2 )
{ case 1:
statements;
break;
case 2 :
statements;
break ;
default;
}
- Duplicate case values are not allowed.
- 'default' is totally optional.
E.g. -
Program to print week days according to their number -
#include <stdio.h>
int main()
{
int a;
printf("Enter the no. for the week day ");
scanf("%d",&a);
switch(a)
{
case 1 :
printf("Monday");
break;
case 2 :
printf("Tuesday");
break;
case 3 :
printf("Wednesday");
break;
case 4 :
printf("Thursday");
break;
case 5 :
printf("Friday");
break;
case 6 :
printf("Saturday");
break;
case 7 :
printf("Sunday");
break;
}
return 0;
}
output -
Enter the no. for the week day 5
Friday
syntax -
Expression 1? Expression 2 : Expression 3
{
Expression 1 tells the condition
Expression 2 is executed if the condition is satisfied.
Expression 3 is executed if conditions is false or not satisfied.
}
E.g. -
program to compare greater of 2 numbers.
#include <stdio.h>
int main()
{
int a,b,c;
printf("Enter the numbers ");
scanf("%d %d",&a,&b);
c=a>b?a:b;
printf("%d",c);
return 0;
}
Conditional statement -
This is known as ternary statements. It can be used in place of if-else statements. This is used to compare the results . Just it has a different syntax.syntax -
Expression 1? Expression 2 : Expression 3
{
Expression 1 tells the condition
Expression 2 is executed if the condition is satisfied.
Expression 3 is executed if conditions is false or not satisfied.
}
E.g. -
program to compare greater of 2 numbers.
#include <stdio.h>
int main()
{
int a,b,c;
printf("Enter the numbers ");
scanf("%d %d",&a,&b);
c=a>b?a:b;
printf("%d",c);
return 0;
}
output -
Enter the numbers 4
5
5
0 Comments