C also provides a special control structure that allows us to handle such cases effectively, rather than using a series of if statements.
Case Control Structure
The control structure in C, which allows as to make a selection out of a number of choices is called a switch. It consists of three keywords switch - case - default.Syntax : switch (<expression>) <statement>
case <constant expression>
default;
switch <expression>
{
case <constant expression>:
do this;
case <constant expression>:
do this;
default :
do this;
}
switch Causes control to branch to one of a list of possible statements in the block defined by <statement>
case The list of possible branch points within <statement> is determined by preceding sub statements with case <constant expression>; where <constant expression> must be an int and must be unique.
Once a value is computed for <expression>, the list of possible <constant expression> values determined from all case statements is searched for a match. If a match is found, execution continuous until a break statementis encountered or the end of <statement> is reached.
default If a switch is not found and "default : " statement prefix is found within <statement>, execution continues at this point. Otherwise<statement> is skipped entirely.
The loop control structure
The programs so far we have discussed followed either a sequential or a decision control structure. In the sequential structure the execution of statements was carried out in a fixed order while in the selection structure the execution of statements was carried out depending on the outcome of a condition being over, with variations in the details each time. The structure that meets this need is the Repetitive Control Structure and its action is termed 'looping'.Repetition
The versatility of a computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some parts of a program, a specified number of times or until a particular condition is full-filled. This is achieved by using the 'Repititive' or loop control structure./* Day of week */
#include <stdio.h>
#include <conio.h>
int main()
{
int day;
printf(“Enter day of the week : ”);
scanf(“%d”, &day);
switch (day)
{
case 1:
printf(“Today is Sunday \n”);
break;
case 2:
printf(“Today is Monday \n”);
break;
case 3:
printf(“Today is Tuesday \n”);
break;
case 4:
printf(“Today is Wednesday \n”);
break;
case 5:
printf(“Today is Thursday \n”);
break;
case 6:
printf(“Today is Friday \n”);
break;
case 7:
printf(“Today is Saturday \n”);
break;
default :
printf(“Wrong entry! \n”);
}
}
No comments:
Post a Comment