Created
June 20, 2019 12:59
-
-
Save manojnaidu619/b2939327b94ad3b13c5623ac8f2d76fe to your computer and use it in GitHub Desktop.
Computing Sum of n Natural numbers using different methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int sum_function(int last){ | |
static int sum = 0; | |
for(int i=1;i<=last;i++){ | |
sum += i; | |
} | |
return sum; | |
} | |
int using_while(int last){ | |
int i=1; | |
static int sum=0; | |
while(i<=last){ | |
sum += i; | |
i++; | |
} | |
return sum; | |
} | |
int using_formula(int last){ | |
return (last)*(last+1)/2; | |
} | |
int using_recursion(int m){ | |
if(m == 0){ | |
return 0; | |
}else{ | |
return using_recursion(m-1) + m; | |
} | |
} | |
int main(){ | |
int n = 9; | |
cout << "Using Sum funtion : " << sum_function(n) << endl; | |
cout << "Using while loop : " << using_while(n) << endl; | |
cout << "Using Formula : " << using_formula(n) << endl; | |
cout << "Using Recursion : " << using_recursion(n) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment