Sunday, April 27, 2014

Menu Driven Factorial Prime Odd Even - C Program

Problem Question


Write a menu driven program which has following options:
1. Factorial of a number.
2. Prime or not
3. Odd or even
4. Exit

Explanation of Problem


Make use of switch statement.

The outline of this program is given below:


/* A menu driven program */
main( )
{
int choice ;
while ( 1 )
{
printf ( "\n1. Factorial" ) ;
printf ( "\n2. Prime" ) ;
printf ( "\n3. Odd/Even" ) ;
printf ( "\n4. Exit" ) ;
printf ( "\nYour choice? " ) ;
scanf ( "%d", &choice ) ;
switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;
}
}
}
Note: The statement while ( 1 ) puts the entire logic in an infinite loop. This is necessary since the menu must keep reappearing on the screen once an item is selected and an appropriate action taken.

Code


#include <stdio.h>
/*Factorial Prime Odd Even.C*
*@Language: ANSI C*
*@Compiler: GNU GCC*
*@IDE: Code::Blocks 13.12*
*@Author: Toxifier*
*@URL: http://letsplaycoding.blogspot.com/*
*@Date: 27-04-2014**/

int main()
{
  while(1)
  {
    int choice, num, i;
    printf("\nChoose an option:\n\t1. Factorial\n\t2. Prime Check\n\t3. Odd or Even\n\t4. Exit\nChoice: ");
    scanf("%d", &choice);
    switch(choice)
    {
      case 1:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int factorial = 1;
        for (i = num; i > 1; i--)
          factorial *= i;
        printf("\nThe factorial is: %d\n", factorial);
        break;
      }
      case 2:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        int flag = 0;
        for (i = 2; i < (num / 2 + 1); i++)
        {
          if ( num % i == 0)
          {
            printf("\nNot Prime\n");
            flag = 1;
            break;
          }
        }
        if (!flag)
          printf("\nPrime\n");
        break;
      }
      case 3:
      {
        printf("\nEnter a number: ");
        scanf("%d", &num);
        if (num % 2)
          printf("\nODD\n");
        else
          printf("\nEVEN\n");
        break;
      }
      case 4:
      {
        exit(0);
      }
      default:
      {
        printf("Wrong Choice");
        break;
      }
    }
  }
  system("pause");
  return 0;
}

Explanation of Code


#include <stdio.h> -> This is the step which occurs before compilation starts. The compiler calls the C Preprocessor to include the STDIO(Standard Input Output) header file into the program, thus letting the use of the standard input/output functions like printf() and scanf() which come from STDIO.H

int main() -> The entry point of the program where the execution starts. This function has to be named main. As per the ANSI specification, the return type has to be int. If you use the traditional C, you may use void as the return type. Since the return type is specified as int in my program, I have to use a return statement at the end of my code. So I use return 0 since zero returned from a function, by convention, implies a correct execution of the program. The return values are used to debug the program.

printf() -> This is a standard output function used to print something on the screen. We have to pass a string to this function which will be displayed on user's terminal.

scanf() -> This is the scanf() function which waits for the user to enter certain value using his/her keyboard. We store the user input at the location in memory which is pointed to by the variable whose address is passed to this function.

switch ( choice )
{
case 1 :
/* logic for factorial of a number */
break ;
case 2 :
/* logic for deciding prime number */
break ;
case 3 :
/* logic for odd/even */
break ;
case 4 :
exit( ) ;


This part of code represents the menu part. The 'switch' is a block that takes an argument 'choice' (the name can be anything, it is a variable), the value of which drives the program flow to one of the 'case' logics. A 'default' case is a case that executes if the value of the 'choice' doesn't match that of any of the cases. So here, if the user enters '1', '1' gets stored in variable 'choice' and upon seeing the switch statement, the program goes to case 1, that is, 'factorial of a number' in our case.

case 1:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int factorial = 1;
for (i = num; i > 1; i--)
factorial *= i;
printf("\nThe factorial is: %d\n", factorial);
break;
}


In this case, we calculate the factorial of a number. The logic is simple, keep multiplying until the number comes down to 1 from it's value 'n'. That's what the loop above does. It decrements the 'num' entered by 1 each time through the loop, and multiplies it with the running product, the factorial, until 'num' has a value 1.

case 2:
{
printf("\nEnter a number: ");
scanf("%d", &num);
int flag = 0;
for (i = 2; i < (num / 2 + 1); i++)
{
if ( num % i == 0)
{
printf("\nNot Prime\n");
flag = 1;
break;
}
}
if (!flag)
printf("\nPrime\n");
break;
}


In this case, the usr enters a number and the statements check whether the number is Prime or not. How do we acheive this? Simple! If a number is not divisible by any number (less than or equal to half the number itself), it is a prime number. The loop does the same thing. It divides the number by every natural number except 1, till the counter reaches half the number. As soon as the number is found to be divisible, we break out of the loop and print 'NOT PRIME' on the screen. Once the program is out of the loop, the 'flag' value is tested if the program came out of the loop normally, or the break made it to come out of the loop. If the former is tha case, we print 'PRIME' on the screen.

case 3:
{
printf("\nEnter a number: ");
scanf("%d", &num);
if (num % 2)
printf("\nODD\n");
else
printf("\nEVEN\n");
break;
}


In this case, the user enters a number, and we divide it by 2. If the number is divisible by 2, it is even, else odd and we print the result.

case 4:
{
exit(0);
}
default:
{
printf("Wrong Choice");
break;
}


Case 4 represents the case when the user wants to exit the program. In such a scenario, we call the 'exit()' function, with a value '0' which represents a normal exit status. The defaul case, represents the case when the yser enters a choice for which no case is defined in the switch block. In my program, I just print 'Wrong Choice' on the screen.

system("pause") -> This statement is used to pause the program, until user presses a key. This function is not necessary in your program, I use it to see my outputs paused. If you use cmd to run your programs, you might not need this. If you use linux/unix you might not need this. Depending on your compiler, this function may or may not work. Moreover, removing this line of code from this program, doesn't affect the functionality of the program.

Output(s)



No comments:

Post a Comment

Need help?