w3resource

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:

C++ Exercises: Calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)

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:

Flowchart: Calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)

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?



Follow us on Facebook and Twitter for latest update.