Problem solving and programming Assignments
Problem solving and programming Assignments
Roll No.: 09
PRN : 12412991
Class : CSDS-A (FY)
Assignment 3
3. Write a Menu Driven Program to perform the following tasks:
a. Accept the number from the user and print its factorial.
b. Accept the number from the user and print if it is prime or non-
prime.
Solution:
#include <stdio.h>
int main() {
int choice, num, i, factorial = 1, isPrime = 1;
switch (choice) {
case 1: // Calculate Factorial
printf("Enter a number to calculate its factorial: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (i = 1; i <= num; i++) {
factorial *= i;
}
printf("Factorial of %d is %d\n", num, factorial);
}
break;
default:
printf("Invalid choice. Please choose 1 or 2.\n");
}
return 0;
}
Algorithm
1. Start
2. Display menu options:
o 1: Calculate Factorial
o 2: Check Prime Number
3. Take user input for choice
4. If choice is 1 (Factorial Calculation):
o Ask user for a number
o If the number is negative, print "Factorial is not defined
for negative numbers"
o Otherwise, initialize factorial = 1
o Loop from 1 to num, multiplying factorial by the loop
variable
o Print the factorial result
5. If choice is 2 (Prime Number Check):
o Ask user for a number
o If number is ≤ 1, print "Not a prime number"
o Otherwise, check divisibility from 2 to num/2
▪ If divisible, print "Not a prime number" and exit loop
▪ If no divisors are found, print "Prime number"
6. If choice is invalid, print "Invalid choice"
7. End
Example 1: Factorial
Input:
Choose an option:
1. Calculate factorial
2. Check if prime number
Enter your choice (1 or 2): 1
Enter a number to calculate its factorial: 5
Step-by-Step Execution:
Step Action Condition Value/Update Output
1 Start - - -
4 Check choice 1 == 1 - -
9 i=1 - fact = 1 * 1 = 1 -
10 i=2 - fact = 1 * 2 = 2 -
11 i=3 - fact = 2 * 3 = 6 -
12 i=4 - fact = 6 * 4 = 24 -
16 End - - -
1 Start - - -
4 Check choice 2 == 2 - -
9 i=2 7 % 2 == 0 - -
10 i=3 7 % 3 == 0 - -
13 End - - -
OUTPUT
FLOWCHART
Start
Input Choice:
scanf("%d", &choice);
Decision (Choice) :
Case 1: Calculate Factorial
Case 2: Check for Prime
Case 3: Exit
Fact = 1
Check if
i=1
num<= 1 End
isPrime=0,
i=2
Break
i <= num
While
i <= num/2
Fact = Fact * i
i++
If num % i == 0 If isPrime == 1
Print Fact
End