Answer to Question #193423 in C for sai

Question #193423

Write a program to calculate the factorial of an integer entered by the user using:


a. For loop

b. While loop

c. Do while loop


1
Expert's answer
2021-05-16T12:24:16-0400
#include <stdio.h>
//Function declaration for calculating factorial
int forLoopFactorial(int x);
int whileLoopFactorial(int x);
int doWhileLoopFactorial(int x);


int main()
{
    int num, choice; //User number to calculate factorial and choice of loop to use.
    printf("Enter a number you want to calculate the factorial of: ");
    scanf("%d",&num);


    printf("Select the method you want to use to calculate the factorial\n");
    //User to choose which type of loop to use and call appropriate function accordingly
    printf("1 - For Loop \n 2 - While Loop \n 3 - Do..while Loop\n");
    scanf("%d", &choice);


    if(choice == 1)
    {
        printf("==================FOR LOOP================\n");
        printf("Factorial of %d is: %d",num,forLoopFactorial(num));
    }
    else if(choice == 2)
    {
        printf("==================WHILE LOOP================\n");
        printf("Factorial of %d is: %d",num,whileLoopFactorial(num));
    }
    else if(choice == 3)
    {
        printf("==================DO...WHILE LOOP================\n");
        printf("Factorial of %d is: %d",num,doWhileLoopFactorial(num));
    }
    else
    {
        printf("Invalid choice. You can only enter 1, 2 or 3 as your options.");
    }


    return 0;
}
//Function to return factorial calculated using for loop
int forLoopFactorial( int x)
{
    int i, f = 1;
    for(i=1;i<=x;i++)
        f=f*i;
    return f;
}
//Function to calculate factorial using while loop
int whileLoopFactorial(int x)
{
    int i = 1, f = 1;
    while(i<=x)
    {
        f=f*i;
        i++;
    }
    return f;
}


//Function to calculate factorial using do...while loop
int doWhileLoopFactorial(int x)
{
    int i = 1, f = 1;
    do
    {
        f=f*i;
        i++;
    }while(i<=x);


    return f;
}

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