Sum of 'n' Numbers || Taking Value from User || C++

In this, we are going to find the sum of first n natural numbers using for loop in a C++ program.
Eg :
sum of first 5 natural numbers 1+2+3+4+5 = 15
You can find the sum for any other value of n using this method Eg. sum of first 20 natural numbers
   = 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20 
   = 210

We will solve it using the for loop in C++

The Code given below can be used in Turbo C++ Compiler.

// sum of first n natural numbers
#include<iostream.h>
#include<conio.h>

void main()
{
    clrscr();
    int n ;
    cout<<"Enter positive integer value of n to find sum of n natural numbers...\n";
    cin>>n;
    int sum = 0;
    for(int i=1;i<=n;i++)
      sum=sum+i;
    cout<<"Sum of "<<n<<" natural numbers = "<<sum;
    getch();
}

  

The Code given below can be used in g++/gcc Compiler.

// sum of first n natural numbers
#include <iostream>
using namespace std;
int main()
{
    int n ;
    cout<<"Enter positive integer value of n to find sum of n natural numbers...\n";
    cin>>n;
    int sum = 0;
    for(int i=1;i<=n;i++)
      sum=sum+i;
    cout<<"Sum of "<<n<<" natural numbers = "<<sum;
    return 0;
}
  
  
#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post