Write a CPP program to calculate sum of first N natural numbers
// Method 1: Mathematical -> Sum up numbers from 1 to n
int sum(int n){
return (n * (n+1)) / 2;
}
// Method 2: Using a for-loop -> Sum up numbers from 1 to n
int sum(int n){
int tempSum = 0;
for (int i = n; i > 0; i--){
tempSum += i;
}
return tempSum;
}
// Method 3: Using recursion -> Sum up numbers from 1 to n
int sum(int n){
return n > 0 ? n + sum(n-1) : 0;
}
0
0
#include <iostream>
using namespace std;
int main(){
int N,i,sum=0;
cin>>N;
for(i=0;i<=N;)
{
sum=sum+N;
N--;
}
cout<<sum;
}
Thank you!
0
0
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks