Loop To Compute And Print The Sum Of A Given Number

24-11-17 cheapnisha 0 comment

Loop To Compute And Print The Sum Of A Given Number

Question 1:

Write a C++ program that uses a for loop to compute and print the sum of a given number of squares.  For example, if the user inputs 5, then the program will print 55 which is equal to 12 + 2+ 32 + 42 + 52 .

#include <iostream>

using std::cout; using std::cin; using std::endl;

int main()

{

int n = 0, sum = 0;

cout << “Enter a number: “;

cin >> n;

for ( n; n>0; n– )

{

sum += n * n;

}

cout << “\nSum: ” << sum << endl;

return 0;

}

Download