C++ Exercises: Calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)
C++ For Loop: Exercise-12 with Solution
Write a program in C++ to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n).
Visual Presentation:
Sample Solution :-
C++ Code :
#include <iostream> // Including the input/output stream header file
using namespace std; // Using the standard namespace to avoid writing std::
int main() // Start of the main function
{
int i, n, sum = 0; // Declaration of integer variables 'i', 'n', and 'sum'
// Display a message to find the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)
cout << "\n\n Find the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n):\n";
cout << "------------------------------------------------------------------------------------\n";
// Prompt the user to input the value for the nth term of the series
cout << " Input the value for nth term: ";
cin >> n; // Read the value entered by the user
for (i = 1; i <= n; i++) // Loop to calculate each term of the series
{
sum += i * i; // Calculate the square of 'i' and add it to the sum
cout << i << "*" << i << " = " << i * i << endl; // Display the current term as i*i
}
// Display the total sum of the series
cout << " The sum of the above series is: " << sum << endl;
return 0; // Indicating successful completion of the program
}
Sample Output:
Find the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n): ----------------------------------------------------------------------- ------------- Input the value for nth term: 5 1*1 = 1 2*2 = 4 3*3 = 9 4*4 = 16 5*5 = 25 The sum of the above series is: 55
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to find the sum of the series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n.
Next: Write a program in C++ to calculate the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n).
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics