switch statement

The switch statment allows us to select or make a decision from multiple given choices based on a given fixed value. The switch statement transfer the control to a chosen statement within its body.

Write a C program to print given value from 1 to 5 in words, if  given value is other than 1 to 5 then print other other than 1 to 5.

#include<stdio.h>
int main()
{

int number;scanf(“%d”,&number);

switch(number)
{

case 1:

printf(“Number is one\n”);
break;

case 2:

printf(“Number is two\n”);
break;

case 3:

printf(“Number is three\n”);
break;

case 4:

printf(“Number is four\n”);
break;

case 5:

printf(“Number is five\n”);
break;

default:

printf(“Number is other than 1 to 5\n”);

}
return 0;

}

Explanatin :-
Suppose you give 2 as input. The compiler jumps to case 2 based on given input and control will come out from switch statement when its encounter with break statement , the output will be :-
$  ./a.out
2
Number is two

Suppose you give 5 as input, the output will be :-
$  ./a.out
5
Number is five

Suppose you give 10 as input, the output will be :-
$  ./a.out
10
Number is other than 1 to 5

Think what will happen, if break statement will not use in above C program, see below.

#include<stdio.h>
int main()
{

int number;scanf(“%d”,&number);

switch(number)
{

case 1:
printf(“Number is one\n”);
case 2:
printf(“Number is two\n”);
case 3:
printf(“Number is three\n”);
case 4:
printf(“Number is four\n”);
case 5:
printf(“Number is five\n”);
default:
printf(“Number is other than 1 to 5\n”);

}
return 0;

}

Explanation :-
Suppose you give 2 as input. The compiler jumps to case 2 based on given input as well as compiler execute all of lines after case 2 because here we are not using any break statement, the output will be :-
$  ./a.out
2
Number is two
Number is three
Number is four
Number is five
Number is other than 1 to 5

Suppose you give 5 as input. The compiler jumps to case 5 based on given input as well as compiler execute all of lines after case 5 because here we are not using any break statement the output will be :-
$  ./a.out
5
Number is five
Number is other than 1 to 5

Suppose you give 10 as input, the output will be :-
$  ./a.out
10
Number is other than 1 to 5

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.