C++

Finding The Sum Of N Natural Integers Using A C++ Program

The natural numbers 1, 2, 3,…, n are what we refer to as such. This software calculates the sum of the first n natural numbers using the value of n.
As an illustration, if the user enters 5 as the value of n, then the sum of the first n (n=5) natural numbers is: 1+2+3+4+5 = 15.

An example program would total n natural numbers.

You need to be familiar with the while loop in C++ in order to comprehend this program.

#include
using namespace std;
int main(){
   int n, sum=0;
   cout<<"Enter the value of n(should be a positive integer): "; 
   //Storing the input integer value into the variable n
   cin>>n;

   /* If user enters value of n as negative then display an 
    * error message to user that the value of n is invalid 
    */
   if(n<=0){
      cout<<"Invalid value of n";
   }
   else{
      // We are using while loop to calculate the sum
     int i=1;
     while(i<=n){
	 sum=sum+i;
	 i++;
     }
     cout<<"Sum of first n natural numbers is: "<<sum;
   }

   return 0;
}

Output:

Enter the value of n(should be a positive integer): 5
Sum of first n natural numbers is: 15

For this program, a for loop is also an option. Simply replace this component:

int i=1;  
while(i<=n){ 
      sum=sum+i;  
      i++;   
}

with this:

for(int i = 1; i <= n; i++) {
   sum = sum+i;
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button