Switch Statement in C

The switch statement is a multiway decision making statement which selects one of the several alternatives based on the value of integer variable or expression. Switch statement requires only one arguments, which is then checked of case options.Break statement is essential use with switch statement because it stops the execution of succeeding cases and transfers the control out.

 

#include<stdio.h>

#include<conio.h>

void main()

{

int a,i,fact=1,c,n,ch,n1=0,n2=1;

clrscr();

printf("Press No.1 for factorial calculation\n");

printf("Press No.2 for prime number calculation\n");

printf("Press No.3 for fibonacci calculation\n");

printf("Press No.4 for exit\n");

printf("Pls!Press the No \n");

scanf("%d",&ch);

switch(ch)//one argument

{

case 1:

     printf("Enter the number");

     scanf("%d",&a);

     for(i=a;i>0;i--)

                {

                fact=fact*i;

                }

     printf("The factorial of the given number is %d",fact);

     getch();

     break;

case 2:

   printf("Enter the No. to check prime or not");

   scanf("%d",&a);

   for(i=2;i<=a-1;i++)

   {

     if(a%i==0)

       {

                printf("No. is not prime");

                getch();

                exit(0);

                }

   }

   printf("No. is prime");

   getch();

   break;

case 3:

   printf("Enter the number");

   scanf("%d",&n);

   printf("The fibonacci series is\n");

   printf("%d%d",n1,n2);

   for(i=3;i<=n;i++)

   {

     c=n1+n2;

     printf("%d",c);

     n1=n2;

     n2=c;

   }

getch();

break;

case 4:

   exit(0);

}

getch();

}

switch statement in c

Explanation…

Case 1:

                   In case 1,variable I,n,fact is initialized as type integer,Enter the number(a)whose factorial you want to calculate.For loop will start, where it is initialized as i=a and the condition(i>0) is checked.If the condition is true I is decremented by one and again the condition is checked.This process continues until condition become false.

Case 2:

              In case 2, number is entered in ‘a’ and loop starts from 2 and ends when condition become false (i<a-1) .Inside the for loop , if statement is checked (a%i)==0, if the remainder of a%i equals to 0 then the message is displayed(not prime)

Case 3:

               In case 3, Fibonacci Series: In Fibonacci series first two value are initialized n1 and n2 with 0 and 1 then next values are generated by adding previous two terms(numbers n1 and n2) next term c =n1+n2.