Search code examples
cfactorial

How to display sum of numbers divided by their factorial?


I'm a beginner and I am having a really hard time while doing this program.
The question is:

(1/1!)+(2/2!)+(3/3!)+(4/4!)- - - -n

So here are the n number of terms(in which a number is divided by its factorial) and I have to display the output of the sum of any number of terms which are given in scanf function.

Only one thing I know is that this program can be done by using "Nested for" loop but I haven't perfect grip yet on C language. So you guys have to have help me out in this. :)

#include <stdio.h>
#include <conio.h>

void main(void){
    int s,a,b,n,fact=1;
    //clrscr();
    printf("Enter number of terms=");
    scanf("%d",&n);
    for(a=1;a<=n;a++) {
        fact=fact*a;
        b=(a/fact);
        printf("Sum=%d",s);
    }
    getche();
}

P.S It's must for me to do it with "Nested for" loop.


Solution

  • #include <stdio.h>
    
    int main(void) {
        // your code goes here
        int n;
        float sum = 0,d,fact =1,j,i;
        printf("Enter the number:");
        scanf("%d",&n);
        for(i=1;i<=n;i++){
            fact = 1;
            for (j = 1; j <= i; j++){
                fact = fact * j;
            }
    
            d =  (float) i / (float) fact ;
    
            sum = sum  + d;
    
        }
    
      printf("sum = %f", sum);
        return 0;
    }
    

    Its working ..you can check over here :-https://ideone.com/JVXQVX