1// Method 1: Mathematical -> Sum up numbers from 1 to n
2int sum(int n){
3 return (n * (n+1)) / 2;
4}
5
6// Method 2: Using a for-loop -> Sum up numbers from 1 to n
7int sum(int n){
8 int tempSum = 0;
9 for (int i = n; i > 0; i--){
10 tempSum += i;
11 }
12 return tempSum;
13}
14
15// Method 3: Using recursion -> Sum up numbers from 1 to n
16int sum(int n){
17 return n > 0 ? n + sum(n-1) : 0;
18}
1
2#include <iostream>
3
4using namespace std;
5
6int main(){
7 int N,i,sum=0;
8 cin>>N;
9 for(i=0;i<=N;)
10 {
11 sum=sum+N;
12 N--;
13 }
14 cout<<sum;
15}
16