Sum of Numbers C++
Sum of Numbers
Write a function that accepts an integer argument and returns the sum of all the integers
from 1 up to the number passed as an argument. For example, if 50 is passed as
an argument, the function wi ll return the sum of 1, 2, 3, 4, … 50. Use recursion to calculate the sum.
Answer:
// Sum of Numbers #include <iostream> using namespace std; // Function prototype int sum(int); int main() { // Let's get the sum of the integers // 1 through 50... cout << sum(50) << endl; return 0; } //******************************************* // The sum function returns the sum of the * // integers 1 through max. * //******************************************* int sum(int max) { if (max > 0) return max + sum(max - 1); else return 0; }
Leave a reply