C Programming – HackerRank Solution | Computing series |

(HackerRank) Write a Modular C Programming code to solve the Computing series, Compute the Harmonic progression series (1 + 1/2 + 1/3 + …) up to the nth term.

If inverse of a sequence follows rule of an A.P i.e, Arithmetic progression, then it is said to be in Harmonic Progression.

In general, the terms in a harmonic progression can be denoted as : 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) …. 1/(a + nd).

As Nth term of AP is given as ( a + (n – 1)d).

Hence, Nth term of harmonic progression is reciprocal of Nth term of AP, which is : 1/(a + (n – 1)d)

where “a” is the 1st term of AP and “d” is the common difference.

TASK:

Compute the Harmonic progression series (1 + 1/2 + 1/3 + …) upto nth term.

Input Format

n is number of terms.

Constraints

1 <= n <=10000

Output Format

sum of Harmonic Progression series upto n terms.

Sample Input 0

5

Sample Output 0

Harmonic Progression is 2.283333

Sample Input 1

0

Sample Output 1

Invalid input

Sample Input 2

-10

Sample Output 2

Invalid input

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings

 

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

void harmo(int n)
{
    double sum=0;
    double i;
    for(i=1;i<=n;i++)
    {
        sum=sum+(1/i);
    }
    printf("Harmonic Progression is %lf\n",sum);
}

int main()
{
    int n;
    scanf("%d",&n);
    if(n<1)
    {
        printf("Invalid input");
        exit(0);
    }
    harmo(n);
    return 0;
}


OUTPUT

Congratulations, you passed the sample test case.

Click the Submit Code button to run your code against all the test cases.

Input (stdin)

5
Your Output (stdout)

Harmonic Progression is 2.283333
Expected Output

Harmonic Progression is 2.283333

 

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University







Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

Welcome to FactsPrime

Sorry, We have detected that you have activated Ad-Blocker. Please Consider supporting us by disabling your Ad Blocker, It helps us in maintaining this website. To View the content, Please disable adblocker and refresh the page.

Thank You !!!