Sum of N Numbers in C++ Programming


The program is written in C++ programming language and it calculates the sum of the first "n" natural numbers using a for loop. Here's a step-by-step explanation of the program:

  • #include<iostream> - This is a preprocessor directive that includes the iostream header file in the program. This file provides input and output operations in C++.
  • using namespace std; - This statement tells the compiler to use the standard namespace, which contains the standard C++ library.
  • int main() - This is the starting point of the program. The main() function is the entry point for all C++ programs.
  • int n, i, total = 0; - This statement declares three integer variables "n", "i", and "total". "n" is used to store the limit up to which the sum needs to be calculated, "i" is used as a loop variable, and "total" is used to store the sum of the natural numbers.
  • cout<<"\nEnter The Limit : "; - This statement prints a message to the console, asking the user to enter the limit up to which the sum needs to be calculated.
  • cin>>n; - This statement reads the user input from the console and stores it in the variable "n".
  • for(i=1;i<=n;i++) - This is a for loop that iterates from 1 to the value of "n". The loop variable "i" is initialized to 1 and incremented by 1 in each iteration until it reaches the value of "n".
  • total=total+i; - This statement adds the value of "i" to the variable "total" in each iteration of the loop.
  • cout<<"\nSum of N Number is : "<<total; - This statement prints the sum of the first "n" natural numbers to the console.
  • return 0; - This statement ends the program and returns the value 0 to the operating system. The value 0 indicates that the program executed successfully.

Source Code

//Program to find the sum of n numbers 3=> 1+2+3=>6
#include<iostream>
using namespace std;
int main()
{
    int n,i,total=0;
    cout<<"\nEnter The Limit : ";
    cin>>n;//3
    for(i=1;i<=n;i++)//1 2 3
    {
        total=total+i;//1 3 6
    }
    cout<<"\nSum of N Number is : "<<total;
   return 0;
}
 

Output

Enter The Limit : 10

Sum of N Number is : 55
To download raw file Click Here

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