Search C Program | nimishsoft@gmail.com

Calculate factorial using for loop

/* Calculate factorial using for loop */

#include<stdio.h>
int main()
{
    int a,f,i;
    printf("Enter a number: ");
    scanf("%d",&a);
    f=1;
    for(i=1;i<=a;i++)
        f = f * i;
    printf("Factorial: %d",f);
    return 0;
}


Related Post:
Calculate factorial using while loo
http://cbasicprogram.blogspot.in/2012/02/calculate-factorial-using-while-loop.html

5 comments:

  1. i used to write

    for(i=2;i<=a;i++)
    f = f * i;

    instead of

    for(i=1;i<=a;i++)
    f = f * i;

    ReplyDelete
    Replies
    1. yes it will save one iteration of loop, thanks :)

      Delete
  2. its not working!!!

    ReplyDelete
  3. if i enter the number 3 its factorial is given as 4 dnt know why plz help

    ReplyDelete
  4. //Factorial of a number using for loop
    #include
    int main()
    {
    int n,i;
    unsigned long long f=1;
    printf("\n Enter Any Number: ");
    scanf("%d",n);
    for(i=1;i<=n;i++)
    {
    f=f*i;
    }
    printf("\n Factorial of %d is %llu",n,f);
    }
    return 0;
    }



    //Factorial of a Number using while loop
    #include
    int main()
    {
    int n,i=1;
    unsigned long long f=1;
    printf("\n Enter Any Number: ");
    scanf("%d",&n);
    while(i<=n)
    {
    f=f*i;
    i++;
    }
    printf("\n Factorial of %d is %llu", n,f);
    }
    return 0;
    }




    //Factorial of a Number using Do while loop
    #include
    int main()
    {
    int n,i=1;
    unsigned long long f=1;
    printf("\n Enter Any Number: ");
    scanf("%d", &n);
    do
    {
    f=f*i;
    i++;
    }
    while(i<=n);
    printf("\n Factorial of %d is %llu", n,f);
    }
    return 0;
    }

    ReplyDelete