Header Ads Widget

Write a C++ program of sum of n natural number using loop

 Write a C++ program of sum of n natural number using loop

Given a number , write a program to find the sum of n natural numbers .

Sample input

10

Sample output:

55

 Write a C++ program of sum of n natural number using loop

The objective of the code is to find the sum of natural numbers up to n . Value of n is given by user .

Code(C++):-

Using For Loop:-

#include <iostream>
using namespace std;
int main()
{
       int n,i,sum=0;
cout<<"Enter the number ";
cin>>n;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
cout<<"sum is "<<sum;
return(0);
}

Output:-

Enter the number
10
sum is 55

Using While Loop:-

#include <iostream>
using namespace std;
int main()
{
       int n,i=1,sum=0;
cout<<"Enter the number ";
cin>>n;
while(i<=n)
{
sum=sum+i;
i=i+1;
}
cout<<"sum is "<<sum;
return(0);
}

Output:-

Enter the number
10
sum is 55

Note :- Time complexity of these codes are O(n) but we can do this in O(1) by using a simple formula of sum of numbers up to n : check the code now

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

 

Post a Comment

0 Comments