Page Rank Checker

Monday 7 July 2014

Menu Driven Program Using Switch Program In C


This article is from solution of Let Us C by Yashwant Kanetkar. I also posted many another articles regarding solutions of Let Us C. If you have any problem regarding solution then give comment, I will surely reply your question.

Q. Write a menu driven program which has following options:
    1. Factorial of a program
    2. Prime or not
    3. Odd or even
    4. Exit
      Once a menu item is selected the appropriate action should be taken and once this action is finished, the menu should reappear. Unless the user selects the 'Exit' option the program should continue to work.
      Hint: Make use of an infinite while and a switch statement.

Ans.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
    clrscr();
    int num, selc, fact=1, loop_count, remn;
    while(1)
    {
        clrscr();
        printf("1. Factorial of a number\n2. Prime or not\n3. Odd or even\n4. Exit\nSelect the menu item you want ");
        scanf("%d",&selc);
        switch(selc)
        {
            case 1:
                fflush(stdin);
                fact=1;
                clrscr();
                printf("Enter any number ");
                scanf("%d",&num);
                for(loop_count=1;loop_count<=num;loop_count++)
                {
                    fact=fact*loop_count;
                }
                printf("\nFacorial value of the number is %d",fact);
                getch();
                break;

            case 2:
                clrscr();
                printf("Enter any number ");
                scanf("%d",&num);
                for(loop_count=2;loop_count<num;loop_count++)
                {
                    remn=num%loop_count;
                    if(remn==0)
                    {
                        printf("\nIt is not a prime number");
                        break;
                    }
                    if((remn!=0) && (loop_count==num-1))
                    {
                        printf("It is a prime number");
                    }
                }
                getch();
                break;

            case 3:
                clrscr();
                printf("Enter any number ");
                scanf("%d",&num);
                remn=num%2;
                if(remn==0)
                    printf("\nIt is a Even Number");
                else
                    printf("\nIt is a Odd Number");
                getch();
                break;

            case 4:
                if(selc==4)
                    exit(1);
                break;
        }
    }
    getch();
}