Problem 26

author
By Supreme2023-03-15
Problem Statement :
Write a C program to find 1+1/2+1/3+1/4+....+1/n
Code:

#include <stdio.h>

int main(){

//26. Write a C program to find 1/1 +1/2 +1/3 +1/4+....+1/n.

int n,i;
float sum=0;

printf("\n\tEvalute The Series 1/1 +1/2 +1/3 +1/4+....+1/n");
printf("\n===============================================================");
printf("\n\nEnter The Value Of N : ");
scanf("%d",&n);

for(i=1; i<=n; i++){

sum = sum + (1.0/i);
}

printf("\n\n_______________________________________________________________");
printf("\n\nSum Of %d Terms Is : %.2f",n,sum);
printf("\n_______________________________________________________________\n\n");

return 0;
}

Description :
  • The program is written in C language and includes the standard input/output library stdio.h.
  • The program calculates the sum of the series 1/1 + 1/2 + 1/3 + 1/4 + ... + 1/n.
  • The main() function starts with declaring the necessary variables n, i, and sum.
  • The program then prints a message to prompt the user to enter the value of n.
  • The scanf() function is used to read the value of n from the user.
  • The program uses a for loop to calculate the sum of the series. The loop runs from i=1 to n and increments i by 1 after each iteration.
  • Inside the loop, the sum of the series is calculated by adding the reciprocal of i (1/i) to the variable sum.
  • The program then prints the result of the sum using printf() function.
  • The "%.2f" is used to print the floating-point result with two decimal places.
  • Finally, the main() function returns 0, indicating successful completion of the program.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.