419 views
0 votes
0 votes
#include <stdio.h>
int main()
{
    int n, i;
    unsigned long long factorial = 1;

    printf("Enter an integer: ");
    scanf("%d",&n);

    // show error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");

    else
    {
        for(i=2; i<=n; ++i)
        {
            factorial *= i;              // factorial = factorial*i;
        }
        printf("Factorial of %d = %llu", n, factorial);
    }

    return 0;
}

Doubt 1 = Why we initialized i=2 and not i=1

Doubt 2 = What if user enter the integer as 0

Thanks!

1 Answer

Best answer
1 votes
1 votes

Doubt 1 = Why we initialized i=2 and not i=1

Multiplying by one will does not change the answer, so you can skip it. However there is no harm in running the loop from one.

Doubt 2 = What if user enter the integer as 0

Factorial of 0 is one, so if the the user inputs zero, the loop will not run and the answer will be $\textit{factorial}$ which is initialized with 1.

selected by

Related questions

0 votes
0 votes
0 answers
3