Plz Help (newbie stuff..)

Can anyone please explain to me how does this code work? i mean how did it add up the numbers? isnt numbers+1 always equal to numbers[1]? how did it move on to the next? also, even if it moves on to the next, isnt it there will be one number[0] generated for every running of the sum function?

i just don't get it....thanks a lot

1
2
3
4
5
6
7
8
9
10
11
12
13
  Put the code you need help with here.

#include <iostream>
using namespace std;
int numbers[13]= {2,342,12,3,4,15,322,1234,334,65,5,8,45};
int sum(  int numbers[],  int numbersLen){

return numbersLen==0? 0: numbers[0]+ sum(numbers+1, numbersLen-1);
}
int main(){

cout<<sum(numbers,4);
}
It took me a second to understand this one. Its a bit tricky.

Here's the break down:

This function works via recursion and is exploiting the fact that arrays in C++/C are pointers to the first element in the array. The code is making a recursive call that is incrementing the numbers pointer to the next item each time. By decrementing the numbersLen variable they are ensuring that the function does not run off the end of the array.

They are also using a ternary statement that is checking if numbersLen == 0. If it does, it will return 0. The magic happens in this statement:

sum(numbers+1, numbersLen-1);

At the beginning of execution, numbers is a pointer to the first element in the array and numbersLen = 13.
numbers[0] = 2.

At the second iteration, numbers[0] = 342, because of the numbers+1 statement.

This function's parameters could have been stated as such:

int sum( int *numbers, int numbersLen);

I think the ternary (the question mark thing) makes this a bit more challenging to understand. Here is another version of this same function (I removed the ternary operator):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int numbers[13]= {2,342,12,3,4,15,322,1234,334,65,5,8,45};

int sum(  int numbers[],  int numbersLen ){
	if( numbersLen==0 ){
		return 0;
	}else{
		// Notice that I am dereferencing the array 
		// because it's just a pointer; 
		// as apposed to calling numbers[0]
		return ( *numbers ) + sum( numbers+1, numbersLen-1 );
	}
}
int main( void ){
	cout<<sum( numbers, 4 );
	return 0;
}
Last edited on
Omg, i have been bothering with this program for a whole damn day, thanks a lot!
Topic archived. No new replies allowed.