Answer to Question #313937 in C for Laurente

Question #313937

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.


1
Expert's answer
2022-03-18T12:13:34-0400
#include <stdio.h>
#include <stdbool.h>


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


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


bool is_prime(int n) {
    int i;


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


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


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


int main() {
    int ans=0, n;
    long f;


    while (ans != 4) {
        printf("1. Factorial of a number\n");
        printf("2. Prime or not\n");
        printf("3. Odd or Even\n");
        printf("4. Exit\n");
        printf("> ");
        scanf("%d", &ans);


        switch (ans) {
        case 1:
            printf("Enter an integer: ");
            scanf("%d", &n);
            f = factorial(n);
            printf("The factorial is %ld\n", f);
            break;


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

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