Skip to main content

Program to find the sum of first n numbers

C++ program to find the sum of first n numbers.

In this we are going to make the program to find the sum of first n numbers which is vey simple.  For calculating the sum of first n numbers firstly you have to clear about the logic what you make for your program and second thing is you have clear about the mathematical implementation of your program. For example in mathematics for calculating the sum of n numbers we usually implement

1

1+2

1+2+3          

1+2+3+4

1+2+3+4+5.

And we are adding the numbers one by one. Means first we add 2, then 3 and then so on. Like this we have to implement a C++ program to find the sum of first n numbers. But before this make sure that you have some knowledge about the syntax of programming language in which you want to make your program. Because syntax is very necessary for making any of the program. The program is given below :

#include<iostream>
using namespace std;
int main(){
    int n,sum=0;
    cout<<"Enter the value of n"<<endl;
    cin>>n;
    for(int i=0;i<=n;i++){
        sum=sum+i;
    }
    cout<<"The sum of n numbers is : "<<sum;
}

In above program we have first initialize two variables then we have printing one line. Then we have using one loop. You can use any of the loop [ either while or do while loop]  in which you are comfortable. Here I am using the for loop and in the for loop we have just implement our logic. And at last we have just print the sum of first n numbers. Now we have made the simplest C++ program to find the sum of first n numbers.

Program to find the sum of first n numbers



Comments