my C program to find factorial is not giving me my desired result

Viewed 80

Here's my code:

#include <stdio.h>

void main() {
    int n, f = 1;
    printf("enter any number: ");
    scanf("%d", &n);
    while (n > 0) {
        f = f * n;
        n = n - 1;
    }
    printf("factorial of %d is %d", n, f);
}

And it gives me a result:

enter any number: 5
factorial of 0 is 120
6 Answers

Just save the original input:

#include<stdio.h>
void main()
{
    int n,n1,f=1;
    printf("enter any number: ");
    scanf("%d",&n1);
    n = n1;
    while(n>0)
    {
        f=f*n;
        n=n-1;
    }
    printf("factorial of %d is %d",n1,f);
}

I'd prefer to use a for loop for this. It lets you declare a local variable for the loop which you can initialise to n without affecting the value of n:

#include <stdio.h>

int main(int argc, char *argv[]) {
    int n, f=1;

    printf("enter any number: ");
    scanf("%d",&n);

    for (int i=n; i>0; i--)
        f *= i;

    printf("factorial of %d is %d\n", n, f);
}

C has syntax which lets you define a new variable for your loop, which will be gone after your loop finishes. This lets you run a loop without changing user input inside the loop.

scanf("%d",&n);
for (int i = n; i > 0; i--)
{
    f=f*i;
}

Some people like for loops more than while loops, because they have more "structure" - all code related to loop organization is in one line of code.

what you are doing is " n=n-1;" because of this line the n value is becoming zero at the end so save the n value in some variable and then print in the last

#include<stdio.h>
void main()
{
int n,f=1, k;
printf("enter any number: ");
scanf("%d",&n);
k=n;// do this
while(n>0)
{
    f=f*n;
    n=n-1;
}
printf("factorial of %d is %d",k,f);
}

Since you need the value of n after the loop, you should not modify n in the while loop, but use a temporary variable i to enumerate the factors.

Also note that main() has a return type of int and return 0 on successful exit.

Here is a modified version:

#include <stdio.h>

int main() {
    int n, f = 1;
    printf("enter any number: ");
    if (scanf("%d", &n) == 1) {
        int i = n;
        while (i > 1) {
            f = f * i;
            i = i - 1;
        }
        printf("factorial of %d is %d", n, f);
    }
    return 0;
}

n will always be 0 at the end of while loop. You can't print the old value if you use n as a counter. Make a separate variable and use it as a counter in your while loop.

Related