Home > OS >  Getting the sum for loop factorial
Getting the sum for loop factorial

Time:12-02

Could I please get advice. I am trying to get the sum of the values labelled 'calculation'. My code is currently outputting the values for every pass through the loop but I would just like 1 value which is the sum of all these values.

Thank you for your advice in advance.

#include<stdio.h>

int i, f = 1;
float calculation = 0;
int main() 
{
    for (i = 1; i <= 19; i  ) 
    {
        f = f * i;
        //printf("Factorial of %d is: %d\n",i,f);// just for me to check//
        calculation = 1.00 / f;
        printf("Factorial calculation is %d! = %f\n", i, calculation);
    }
    return 0;
}

CodePudding user response:

You have to store a sum value for every calculation in the for loop.

#include<stdio.h>

int i, f = 1;
float calculation = 0;
int main() 
{
    for (i = 1; i <= 19; i  ) 
    {
        f = f * i;
        //printf("Factorial of %d is: %d\n",i,f);// just for me to check//
        calculation  = 1.00 / f;
    }
    printf("Factorial calculation is %d! = %f\n", i, calculation);
    return 0;
}
  • Related