C Program Learning Part-6 - Engineer Simple

Search This Blog

C Program Learning Part-6

 

Decision Making and Branching

THE SWITCH STATEMENT

The general form of the switch statement is as shown below:

C Program Exercise Part-01


switch (expression)

{

case value-1:

block-1

break;

case value-2:

block-2

break;

………..

………..

default: default-block

break;

}

Statement-x;

 

 

printf(“Travel Guide \n”);              printf(“A air timings \n”);

printf(“T train timings \n”);          printf(“B bus services \n”);

printf(“X to skip \n”);                     printf(“Enter your choice \n”);

character = getchar();

switch (character)

{

case ‘A’ :

air -display();

break;

case ‘B’ :

bus -display();

break;

case ‘T’ :

train -display();

break;

default:

printf(“No choice”);

 

}

The GOTO Statement:

C supports the goto statement to branch unconditionally from one point to another in the program. The goto requires a label in order to identify the place where the branch is to be made. A level is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. 



The general forms of goto and label statements are shown below:

C – continue statement with example

The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.



Example:

#include

int main()

{

int i;

for(i=1;i<=5;i++)

{

if(i==2)

{

continue;

}

printf("%d ",i);

}

}

Break statement in C

The break statement in C programming has the following two usages − 

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.



Example-1:

#include

int main()

{

int i;

for(i=1;i<=10;i++)

{

if(i==8)

{

break;

}

printf("%d ",i);

}

}


Example-2:

#include

int main()

{

double x, y;

int count;

count=1;

printf("Enter five real number in a line. \n");

read:

scanf("%lf",&x);

printf(" \n");

 if(x<0)

{

printf(“Value%d negative”,count);

}

else

{

Y=sqrt(x);

printf("%lf \t %lf \n",x,y);

}

count=count+1;

if(count<=5)

goto read;

printf("End of computation.");

return 0;

}


Next Post Previous Post
No Comment
Add Comment
comment url