<< Chapter < Page | Chapter >> Page > |
if(expression){
if(expression){statement
}}else{
statement}
Example
#include<conio.h>#include<stdio.h>void main()
{// variable declaration
float a, b;float max;
printf(“ Enter the values of a and b: “);scanf(“%f %f”,&a,&b);
if(a<b) //Assign the greater of x and y to the variable max
max = b;else
max = a;printf(“\n The greater of two numbers %.0f and %.0f is %.0f “,a,b,max);
getch();}
It is used to select one of a number of alternative actions depending on the value of an expression, and nearly always makes use of another of the lesser statements: the break. It looks like this.
switch (expression){
case const1: statements
case const2: statements. . . .
default: statements}
The flowchart of switch statement is shown below:
The expression is evaluated and its value is compared with all of the const etc. expressions, which must all evaluate to different constant values (strictly they are integral constant expressions). If any of them has the same value as the expression then the statement following the case label is selected for execution. If the default is present, it will be selected when there is no matching value found. If there is no default and no matching value, the entire switch statement will do nothing and execution will continue at the next statement.
OK=1;
switch (OP){
case ‘+’:z=x+y;
break;case ‘-’:
z=x-y;break;
case ‘*’:z=x*y;
break;case ’/’:
if (y!=0 )z=x/y;
else OK=0;default :
OK=0;}
The following program writes out the day of the week depending on the value of an integer variable day. It assumes that day 1 is Sunday.
#include<stdio.h>#include<conio.h>void main()
{int day;printf(“Enter the value of a weekday”);
scanf(“%d”,&day);
switch (day){
case 1 : printf( "Sunday");break;
case 2 : printf( "Monday");break;
case 3 : printf( "Tuesday");break;
case 4 : printf("Wednesday");break;
case 5 : printf("Thursday");break;
case 6 : printf("Friday");break;
case 7 : printf("Saturday");break;
default : printf("Not an allowable day number");break;
}getch();
}
If it has already been ensured that day takes a value between 1 and 7 then the default case may be missed out. It is allowable to associate several case labels with one statement. For example if the above example is amended to write out whether day is a weekday or is part of the weekend:
Notification Switch
Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?