C Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C Switch

C Switch

shape Description

C Switch Case is another way of deciding a condition which is an alternative for nested-if statements. To overcome the complexity drawback of nested-if, switch case statements are used. It allows variable or expression value to change the control flow of program execution. Although most Switch statements can be rewrited with if statements, it tends to be easier for the compiler to optimize a large Switch statement than a long chain of if statements.

shape Syntax

switch(expression) { case value1: //statements; break; case value2: //statements; break; case value3: //statements; break; . . case value n: //statements; break; default : //statements; break; }

shape Flow Chart

shape More Info

In the above syntax, "break" is the keyword used to end the case statements. First, the expression is compared with case 1, if case 1 meets the criteria, then the corresponding statements gets executed until the break is reached.Otherwise (If it does not satisfy the condition then) switch goes to next case and the process continues. If neither case is satisfied then switch executes statements of "default case".

shape Example

[c] #include<stdio.h> main() { int a; printf("Please enter a no between 1 and 5: "); scanf("%d",&a); switch(a) { case 1: printf("You chose one"); break; case 2: printf("You chose two"); break; case 3: printf("You chose Three"); break; case 4: printf("You chose Four"); break; case 5: printf("You chose Five."); break; default : printf("Invalid Choice.Enter a number between 1 and 5"); break; } } [/c] Output: [c]Please enter a no between 1 and 5: 4 You chose Four[/c]

goto() statement:

shape Description

goto() statement alters the normal execution of program and shifts the flow of program to some other part of program.

shape Syntax

goto label_name; . . . label_name: statements;

shape Example

[c] #include<stdio.h> int main() { float num,average,sum; int i,n; printf("Maximum no. of inputs: "); scanf("%d",&n); for(i=1;i<=n;++i) { printf("Enter n%d: ",i); scanf("%f",&num); if(num==0) goto jump; /* control of the program moves to label jump */ sum=sum+num; } jump: average=sum/(i-1); printf("Average: %.2f",average); return 0; } [/c] Output: [c]Maximum no. of inputs: 3 Enter n1: 2 Enter n2: 3 Enter n3: 8 Average: 4.33[/c]

Summary

shape Key Points

  • Switch case helps to decide when multiple conditions exist in the program.
  • break keyword stops the execution if the condition is true.
  • If no condition is true, default block is executed.

shape Programming Tips