Program 179:
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:
#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
- This program starts with initializing :
- n → To store input from user
- i →Used as helping variable
- sum → To store output sum
printf("Enter value of n\n"); scanf("%d",&n);
Taking input from userfor(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
- Iteration 1:i=1;1<=8(which is true so loop will execute)
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- And finally sum is printed.
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: