Printing squaring numbers using For Loop in C++
This is a C++ program that prompts the user to input a limit, and then calculates and outputs the sum of squares of all natural numbers up to that limit. Here is a brief explanation of the program:
- The program declares three integer variables: n, tot, and i, and initializes tot to 0.
- The program prompts the user to input the limit, and reads it from the standard input using the cin object.
- The program enters a for loop that iterates n times, from 1 to n inclusive. In each iteration, the loop body is executed.
- In the loop body, the program adds the square of the current value of i to the variable tot. The square is calculated by multiplying i with itself.
- After the loop terminates, the program outputs the final value of tot, which is the sum of squares of all natural numbers up to the limit n. The output is sent to the standard output using the cout object.
- Finally, the program returns 0 to the operating system, indicating successful execution.
Source Code
#include<iostream>
using namespace std;
int main()
{
int n,tot=0,i;
cout<<"\n Enter the Limit:";
cin>>n;
for(i=1;i<=n;i++)
{
tot+=i*i;
}
cout<<"\n "<<tot;
return 0;
}
To download raw file
Click Here
Output
Enter the Limit:10
385