Monday, 24 February 2014

Sum of harmonic series - C++ Program Source Code

The aim is to find the sum of the harmonic series with the limit 'n' specified by the user.
The harmonic series is as such:

Code:
//Please Comment, share, follow and visit often! :)
#include<iostream.h>
#include<conio.h>
void main()
{
    int i,n;
    double answer;
    cout<<"Enter 'n'\n";
    cin>>n;
    answer=0;
    if(n!=0)
    {
         for(i=1;i<=n;i++)
         {
            answer = answer + (1.0/i);
         }
         cout<<"Answer is "<<answer<<"\n";
    }
    else
    {
         cout<<"Answer not defined! :(\n";
    }
}


For newer IDEs, visit this page.
Working:

The program is remarkably simple. First we input 'n' from the user. A variable 'answer' is initialized with a value 0. Now inside a for loop, with limit 'n', we add '1/i' to the answer. This for loop runs n times, after which the variable answer will have the required value. Also, if the input number is 0, sum cannot be defined since series becomes 1/0, which is not defined. So the if-statement.
IF the input number is NOT 0, the increment process is done, else, an error message is displayed. 

Happy Coding!
:)

No comments:

Post a Comment

You might also like