Sum of n natural numbers || while loop || sum || C++

In this, we are going to see while loop, the program is based on while loop which prints, sum of 'n' natural numbers .

The code given below can be used for TURBO C++ Compiler:-

#include<iostream.h>
#include<conio.h>

void main()
{
    clrscr();
    int n,i = 1;
    int sum = 0;
    cout<<"Enter value of n to find sum upto that number\n";
    cin>>n;
    while (i <= n)
    {
        sum = sum + i;
        i++;
    }
    cout <<"Sum of "<<n<<" natural numbers is "<< sum;
    getch();
}
	
    

The code given below can be used for g++/gcc Compiler:-

#include<iostream>
using namespace std;

int main()
{
    int n,i = 1;
    int sum = 0;
    cout<<"Enter value of n to find sum upto that number\n";
    cin>>n;
    while (i <= n)
    {
        sum = sum + i;
        i++;
    }
    cout <<"Sum of "<<n<<" natural numbers is "<< 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