Introduction
In this lab, we will learn how to write a C++ program to find the sum of the series 1^2 + 3^2 + 5^2 + ... + n^2 using two different approaches. We will guide you through step-by-step to help you understand the process.
In this lab, we will learn how to write a C++ program to find the sum of the series 1^2 + 3^2 + 5^2 + ... + n^2 using two different approaches. We will guide you through step-by-step to help you understand the process.
First, we need to create a new C++ file. Open the terminal and navigate to the ~/project
directory. Here, we will create a new file named main.cpp
.
cd ~/project
touch main.cpp
Here, we will write the program using the first method. In this method, we will use a for loop to iterate through the odd numbers up to n and add their squares to the sum variable.
#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<<"The sum of the series is: "<<pattern_sum(num)<<endl;
return 0;
}
Code explanation:
pattern_sum
, which takes an integer n
as input and returns the sum of the series.sum
to 0.main()
function, we ask the user to input the number of terms they want and store the value in the num
variable.pattern_sum()
function with the user's input.Here, we will write the program using the second method. In this method, we 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<<"The sum of the series is: "<<pattern_sum(num)<<endl;
return 0;
}
Code explanation:
pattern_sum
, which takes an integer n
as input and returns the sum of the series.sum
variable.main()
function, we ask the user to input the number of terms they want and store the value in the num
variable.pattern_sum()
function with the user's input.Here is the full code for main.cpp, using the second method 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<<"The sum of the series is: "<<pattern_sum(num)<<endl;
return 0;
}
In this lab, we learned how to find the sum of the series 1^2 + 3^2 + 5^2 + ... + n^2 using two different approaches: using a for loop and using a mathematical formula. We also covered how to write a C++ program to solve this problem. Now you should have a clear understanding of how to find the sum of the series using C++.