Home > database >  i wrote a code for sum of series but i am not getting any output
i wrote a code for sum of series but i am not getting any output

Time:12-10

The question was to add first seven terms of the following series using for loop 1/1! 2/2! 3/3! .... I thought i might be loosing decimal point due to int but i am not even getting wrong answer. I ran the code in terminal but it just keeps running no output. Thanks for helping out.

#include<stdio.h>
int main()
{
    int n;
    float a;
    float v=0.0;
    for(n=1;n<=7;n  )
    {
        a=1.0;
        while(n>0)
        {
            a=a/n;
            n--;
        }
        v=v n*a;
    }
    printf(" sum is %f ",v);
    return 0;
}

CodePudding user response:

#include <stdio.h>

int fact(int n) {
    int product = 1;
    for (int i = 1; i < n 1; i  ) {
        product *= i;
    }
    return product;
}

int main() {
    double sum = 0.0;
    for(int i = 1; i < 7 1; i  ) {
        sum  = double(i) / fact(i);
    }
    printf("Sum is %f\n", sum);

    return 0;
}

CodePudding user response:

The series is 1/1! 2/2! .. n terms can be written as 1 1/1! 1/2! 1/3! ...(n-1) terms .

So it is 1 sum of 1/i! where i=1 to i=n-1 terms.

So I have taken sum=1 as initial value.

#include <stdio.h>

//this is the function for calculating n!
int fact(int n) {
    int product = 1;
    for (int i = 1; i < n 1; i  ) {
        product *= i;
    }
    return product;
}

int main() {

    int n=5;

    //we are taking sum=1 as initial value
    double sum = 1.0;

    //now we run 1/1!   1/2!   1/3!   1/4! i.e. upto (n-1) terms (here n=5 => so n-1 = 4)
    for(int i = 1; i < n; i  ) 
    {
        sum  = (1.0) / fact(i);
    }

    printf("Sum is %f\n", sum);

    return 0;
}

CodePudding user response:

As @DeBARtha mentioned in the original code i was incrementing and then decreasing n causing to loop to run repeatedly. By using one more variable (m) for the while loop and then decreasing it while increasing the 'n' in the for loop the problem gets resolved.


#include<stdio.h>
int main()
{
    int n,m;
    float a;
    float v=0.0;
    for(n=1;n<=7;n  )
    {
        m=n;
        a=1.0;
        while(m>0)
        {
            a=a/m;
            m--;
        }
        v=v n*a;
    }
    printf(" sum is %f ",v);
    return 0;
}
  •  Tags:  
  • c
  • Related