Signup/Sign In

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

Here, in this tutorial, we will be seeing how to write the program for the given pattern and at the end print the resultant sum of the series formed for the input number of terms by the user.

We can have two different approaches to write the program but based on the time complexity the second method will be much better as it will take a constant amount of time even for the large input whereas the first one will become a little bit slow for higher inputs.

C++ Program For The Sum Of Series (First Method)

#include<iostream>
using namespace std;

int pattern_sum(int n){
    int sum=0;
    for(int i=1;i<=n;i+=2){
      sum+=(i*i);
    }
    return sum;
}

int main(){
    int num;
    cout<<"Enter the number of terms you want:-";
    cin>>num;
    cout<<pattern_sum(num);
    return 0;
}


Enter the number of terms you want:-2
10

C++ Program For The Sum Of Series (Second Method)

Another approach to solve is to use the mathematical formula to find the sum of the series.

#include<iostream>
using namespace std;

int pattern_sum(int n){
    int sum;
    sum = ( ((2 * n) – 1) * (((2 * n) – 1)+ 1) * ( ( 2 * ((2 * n) – 1) ) + 1 ) ) / 6;
    return sum;
}

int main(){
    int num;
    cout<<"Enter the number of terms you want:-";
    cin>>num;
    cout<<pattern_sum(num);
    return 0;
}


Enter the number of terms you want:-3
35

Conclusion

There can be more than these methods to solve the same problem but the second one will be better than all since it takes a constant amount of time.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.