Contact Learn C
Copy Program Share Program

Program 179:Sum of Series 1+1/2+1/3+1/4....+1/N

Program 179:
 
#include<stdio.h>
main()
{ 
int i,n;
float sum=0;
printf("Enter value of n\n");
scanf("%d",&n);


for(i=1;i<=n;i++)
{
 sum+=(float)1/i;
}
printf("The value of\n");
for(i=1;i<=n;i++)
{
 if(i<n)
 {
  printf("1/%d+ ",i);
 }
 else
 {
  printf("1/%d= ",i);
 }
 
}
printf("%f\n",sum);

}


Explanation:
Formula for this series: sum=1+1/2+1/3+1/4....+1/N

  1. This program starts with initializing :
    • n → To store input from user
    • i →Used as helping variable
    • sum → To store output sum
  2. printf("Enter value of n\n");
    scanf("%d",&n);
    
    Taking input from user
  3. for(i=1;i<=n;i++)
    {
     sum+=(float)1/i;
    }
    For loop iterates from 1 to 'n'(say from example 8). Sum is initialized to zero
    • Iteration 1:i=1;1<=8(which is true so loop will execute)
      • sum+=(float)1/i →sum+(1/i)→0+1/1→sum=1
      • (float) is used to type cast*
      • Final values are sum= 1,i will be incremented to 2 so i=2.
    • Iteration 2:i=2;2<=8(which is true so loop will execute)
      • sum+=(float)1/i →sum+(1/i)→1+(1/2)→sum=1.5
      • Final values are sum= 1.5,i will be incremented to 3 so i=3.
    • Iteration 3:i=3;3<=8(which is true so loop will execute)
      • sum+=(float)1/i →sum+(1/i)→1.5+(1/3)→sum=1.83333
      • Final values are sum= 1.8333,i will be incremented to 4 so i=4.
    • This iteration continues till iteration 8 and after that i will become 9 which terminates the loop.Finally sum will be 2.717857
  4. for(i=1;i<=n;i++)
    {
     if(i<n)
     {
      printf("1/%d+ ",i);
     }
     else
     {
      printf("1/%d= ",i);
     }
     
    }
    The previous loop will just obtain the sum and won't print 1/1+1/2+1/3+1/4...+1/8.To Print that the above for loop is used as the above loop iterates 8 times and if i<n then 1/i+ is printed and if i is not less than n which means the final value is printed with 1/i= at the end 
  5. And finally  sum is printed.
*Note:-Type casting is used to convert value of one datatype to another.For example if 1/2 is int then output is 0 whereas if it is float the output will be 0.5 
While we are calculating 1/i it will give integer output as i is declared as integer(i.e. int i) but in our program it should give float value so to convert output from int to float we use typecasting.
So when we use (float)1/i, it will generate a float type output
Output:

Sum of Series 1+1/2+1/3+1/4....+1/N




 

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide