Monday, 9 January 2017

Write a program in C++ that accepts a list of values as command line arguments and prints the sum of all the values. Make sure that the logic of the program contains a recursive method recurseAdd that accepts these list of values as the input to it and returns the sum of all the values.

#include <iostream>
#include <cstdlib>
using namespace std;

int recurseAdd(int *,int);
int main(int argc, char **argv)
{
   if (argc < 2) // the program's name is the first argument
   {
      std::cerr << "Not enough arguments!\n";
      return -1;
   }
 
   int *inArray = new int[argc-1];

   for(int i=0;i<argc-1;i++)
    inArray[i]=std::atoi(argv[i+1]);
   
   
   
    int result=recurseAdd(inArray,argc-1);
    cout<<result;  
   

   return 0;
}
int recurseAdd(int *arr, int size)
{
if(size==0)
return 0;
else
{
return (*(arr +0) + recurseAdd((arr+1),size-1));
}
}

No comments:

Post a Comment