In: Computer Science
Using C++, find the sum of the squares of the integers from 1 to MySquare, where MySquare is input by the user. Be sure to check that the user enters a positive integer.
Code with explanation in comments:
#include<iostream>
using namespace std;
int main()
{
//unsigned long variable will let
//user to enter only positive value only.
unsigned long MySquare,i,sum=0,dummy;
cout<<"Enter a positive number:";
cin>>MySquare;
//find the sum of the squares of the +ve
integers
//from 1 to MySquare
for(i=1;i<=MySquare;++i)
{
//store the sqaure of i in dummy variable
dummy=i*i;
//store the sum of square of +ve integers from 1 to
MySquare in sum variable.
sum+=dummy;
}
//print the sum of squares of the +ve integers
//from 1 to MySquare
cout<<"\nSum = "<<sum;
return 0;
}
-------------------------------------------------------------------------------------
Snapshot of Code and the output:
Output:
----------------------------------------------------------------------------------------
It will let the user to enter only positive value else it will throw error: