C Programming

Solved Example

Practice Questions

Exercise Question

Menu driven program to perform factorial, prime number, odd even check and exit the program

Objective

Write a menu driven proram which have the following options:

  • Factorial of a number
  • Prime or not
  • Even or Odd
  • Exit

Program

#include "stdio.h"
#include "math.h"
#include "stdlib.h"

int main() {
	int ch;
	int i,n,result;
	double sqroot;
	do {
		printf("Enter your choice:\n-----------------------\n\n");
		printf("1. Factorial\n");
		printf("2. Prime number\n");
		printf("3. Even or odd\n");
		printf("4. Exit\n");
		printf("Your choice? ");
		scanf("%d",&ch);
		
		switch(ch) {
			case 1:
				printf("Enter any number: ");
				scanf("%d",&n);
				for(i = 1, result = 1; i <= n; i++) {
					result = result * i;
				}
				
				printf("Factorial of %d = %d\n",n,result);
				break;
			case 2:
				printf("Enter any number: ");
				scanf("%d",&n);
				sqroot = sqrt(n);
				result = 1;
				for(i = 2; i <= sqroot; i++) {
					if(n % i == 0) {
						result = 0;
						break;
					}
				}
				if(result) {
					printf("%d is a prime number\n",n);
				}else {
					printf("%d is not a prime number\n",n);
				}
				break;
			case 3:
				printf("Enter any number: ");
				scanf("%d",&n);
				if(n%2) {
					printf("%d is odd\n",n);
				}else {
					printf("%d is even\n",n);
				}
				break;
			case 4:
				exit(0);
				break;
		}
	} while(ch != 4);
	
	return 0;
}

Output

Enter your choice:
-----------------------

1. Factorial
2. Prime number
3. Even or odd
4. Exit
Your choice? 1
Enter any number: 6
Factorial of 6 = 720
Enter your choice:
-----------------------

1. Factorial
2. Prime number
3. Even or odd
4. Exit
Your choice? 2
Enter any number: 13
13 is a prime number
Enter your choice:
-----------------------

1. Factorial
2. Prime number
3. Even or odd
4. Exit
Your choice? 3
Enter any number: 56
56 is even
Enter your choice:
-----------------------

1. Factorial
2. Prime number
3. Even or odd
4. Exit
Your choice? 4