Printing sum of numbers using For Loop in C++


This is a C++ program that calculates the sum of numbers from 1 to a given limit entered by the user. Here's a step-by-step breakdown of the program:

  • The program includes the <iostream> library, which allows it to input and output data through the console.
  • The program begins with the main() function, which is the starting point for any C++ program.
  • Inside the main() function, there are three integer variables declared: i, sum, and n.
  • The program prompts the user to enter a limit by displaying the message "Enter the Limit:" on the console.
  • The user enters the limit, which is stored in the variable n using the cin (console input) statement.
  • The program then enters a for loop that iterates from 1 to n, with i starting at 1 and increasing by 1 on each iteration.
  • Inside the loop, the sum variable is updated by adding the current value of i to it.
  • Once the loop completes, the total sum of numbers from 1 to n is stored in the variable sum.
  • Finally, the program prints the value of sum on the console using the cout (console output) statement.
  • The program returns 0, which indicates that the program has executed successfully.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int i,sum=0,n;
    cout<<"\nEnter the Limit:";
    cin>>n;
    for(i=1;i<=n;i++)
    {
        sum=sum+i;
    }
    cout<<sum;
    return 0;
}
To download raw file Click Here

Output

Enter the Limit:5
15

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples