Why is this the output?......
Ok, I have 2 array programs here which are examples from the deitel C++ book. I was studying the examples and I just dont know why they produce their certain output. I am lost and stressed. If anyone can tell me why the output is such for these 2 programs, I'd really appreciate it, thanks.
// Ex. 4.21: ex04_21.cpp
// What does this program do?
#include <iostream>
using namespace std;
void someFunction( int [], int, int ); // function prototype
int main()
{
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "The values in the array are:" << endl;
someFunction( a, 0, arraySize );
cout << endl;
return 0; // indicates successful termination
} // end main
// What does this function do?
void someFunction( int b[], int current, int size )
{
if ( current < size ) {
someFunction( b, current + 1, size );
cout << b[ current ] << " ";
}
Why does this code produce the array contents going from 10 to 1 and not the other way around, and why would the array even be initialized to 10 in the first place, isnt the correct manner supposed to be from 0-9?
Here is the other program:
#include <iostream>
using namespace std;
int whatIsThis( int [], int ); // function prototype
int main()
{
const int arraySize = 10;
int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int result = whatIsThis( a, arraySize ); //passing in array and size
cout << "Result is " << result << endl;
return 0; // indicates successful termination
} // end main
// What does this function do?
int whatIsThis( int b[], int size )
{
// base case
if ( size == 1 )
return b[ 0 ];
// recursive step
else
return b[ size - 1 ] + whatIsThis( b, size - 1 );
} // end function whatIsThis
Hmmm the return b[size-1] + whatIsThis(b,size-1) statement baffles me. How does that statement make all the elements in the array add to each other recursively?
*sighs* any help would be highly appreciated. Thanks.