Signup/Sign In

C++ Program To Find Sum Of Series 1 + 2 + 3 + 4 + 5 + 6 . . . . . . . . . . . . . . . . n

In this tutorial, we will see how to print the sum of n terms starting from "1" i.e. the sum of n natural numbers starting from 1. There can be many approaches for solving the same problem but the given below are the most common approach that is used by the coders. Out of these two approaches, the better one will be decided by the use of time complexity analysis.

C++ Program To Print The Sum (First Method):-

#include<iostream>
using namespace std;
int findsum(int num){
    int sum=0;
    for(int i=0;i<num;i++){
        sum=sum+i;
    }
    return sum;
}

int main(){
    int n;
    cout<<"Enter the value of n , till which sum is required:-";
    cin>>n;
    cout<<findsum(n);
    return 0;
}


Enter the value of n , till which sum is required:-9
45

C++ Program To Print The Sum (Second Method):-

#include<iostream>
using namespace std;
int findsum(int num){
    int sum=0;
    sum=num*(num+1)/2;
    return sum;
}

int main(){
    int n;
    cout<<"Enter the value of n , till which sum is required:-";
    cin>>n;
    cout<<findsum(n);
    return 0;
}


Enter the value of n , till which sum is required:-5
15

Conclusion

In this tutorial, we have seen how can we print the sum of natural numbers to the given term by using two methods. As for the time complexity point of time, the second method will be far better than the first method because it will always constant amount of time that is approximately not dependent on the value of "n".