Answer to Question #307889 in C for Justin

Question #307889

Write a menu driven program which has the following options:


1. Factorial of a number


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. You may use of an infinite while and


switch statement.

1
Expert's answer
2022-03-09T10:24:39-0500
#include <stdio.h>
#include <stdbool.h>


int menu() {
    char* msg[] = {"Factorial of a number", "Prime or not", 
                   "Odd or Even", "Exit"};
    int i, ans=0;


    for (i=0; i<4; i++) {
        printf("%d. %s\n", i+1, msg[i]);
    }
    printf(">>> ");
    scanf("%d", &ans);


    return ans;
}


long factorial(int n) {
    long res = 1;
    int i;


    for (i=1; i<=n; i++) {
        res *= i;
    }
    return res;
}


bool is_prime(int p) {
    int i;


    if (p < 2) {
        return false;
    }
    if (p == 2) {
        return true;
    }
    if (p % 2 == 0 ) {
        return false;
    }


    i = 3;
    while (i*i <= p) {
        if (p % i == 0) {
            return false;
        }
        i += 2;
    }
    return true;
}


bool is_even(int n) {
    return n % 2 == 0;
}


int main() {
    int ans=0, x;
    long res;


    while (ans != 4) {
        ans = menu();
        switch (ans) {
        case 1:
            printf("Enter an integer: ");
            scanf("%d", &x);
            res = factorial(x);
            printf("Factorial = %ld\n\n", res);
            break;

        case 2:
            printf("Enter an integer: ");
            scanf("%d", &x);
            if (is_prime(x)) {
                printf("THe number is prime\n\n");
            }
            else {
                printf("The number is not prime\n\n");
            }
            break;

        case 3:
            printf("Enter an integer: ");
            scanf("%d", &x);
            if (is_even(x)) {
                printf("The number is even\n\n");
            }
            else {
                printf("The number is odd\n\n");
            }
            break;

        case 4:
            break;
        
        default:
            printf("Incorrect choice\n\n");
        }
    }

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS