Tuesday, 2 February 2016

Recursion in C++ (Example)


C++ Code:

#include<iostream>
using namespace std;
int sum = 0; //Global Variable can be passed by value from main
int sumTotal(int* arr, int size) //Function Definition
{
  if (size > 0) //Base Condition
  {
    sum = sum + arr[size - 1];
    size--;
    sumTotal(arr, size); //Function Call
  }
  return sum;
}
void main()
{
  int size;
  cout << "Please input size: ";
  cin >> size;
  int *arr = new int[size]; //Dynamic Array
  for (int i = 0; i < size; i++) //Input values
  {
    cout << "Please input a number: ";
    cin >> arr[i];
  }
  cout<<"Sum is: " <<sumTotal(arr, size); //Function Call
  system("pause>null");
}

//Source: www.computertrickscity.tk/
//By: Ahsan Mustafa