Reputation: 164
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
// ex06_18.c
// What does this program do?
#define SIZE 10
// function prototype
void someFunction( const int b[], size_t startSubscript, size_t size );
// function main begins program execution
int main( void )
{
int a[ SIZE ] = { 8, 3, 1, 2, 6, 0, 9, 7, 4, 5 }; // initialize a
puts( "Answer is:" );
someFunction( a, 0, SIZE );
puts( "" );
_sleep(1000*100);
} // end main
// What does this function do?
void someFunction( const int b[], size_t startSubscript, size_t size )
{
if ( startSubscript < size )
{
someFunction( b, startSubscript + 1, size );
printf( "%d ", b[ startSubscript ] );
} // end if
} // end function someFunction
someFunction( b, startSubscript + 1, size )
- can you explain this part please? I debugged it but it is hard to understand how does the recursive part process?
Upvotes: 0
Views: 118
Reputation: 101
One way to display an array in reverse order is the following:
The first bullet is implemented recursively. The recursion ends when the size of the array is 0, in which case you do nothing.
This is exactly what the function someFunction does.
Upvotes: 0
Reputation:
It will re-call the function until the startSubscript
variable will be greater than the size
variable then we can say that the index is on the last value on the a
Array and then it will back to the first call (Which we were on the 0 index).
Calls:
Call # | Function call | Return | Outputs
1 someFunction( a, 0, 10 ) - -
2 someFunction( a, 1, 10 ) - -
3 someFunction( a, 2, 10 ) - -
4 someFunction( a, 3, 10 ) - -
5 someFunction( a, 4, 10 ) - -
6 someFunction( a, 5, 10 ) - -
7 someFunction( a, 6, 10 ) - -
8 someFunction( a, 7, 10 ) - -
9 someFunction( a, 8, 10 ) - -
10 someFunction( a, 9, 10 ) - -
11 someFunction( a, 10, 10) - -
10 < 10 ? False Here we stop the recursive calls and we back again to the first call that was called from the main. :
As we can see that every time we was re-calling the someFunction
there was printf( "%d ", b[ startSubscript ] );
That we could not get to it because of the recursive.
Backing :
Call # | Function call | Return | Outputs (a[startSubscript])
10 someFunction( a, 9, 10 ) - 5
9 someFunction( a, 8, 10 ) - 4
8 someFunction( a, 7, 10 ) - 7
7 someFunction( a, 6, 10 ) - 9
6 someFunction( a, 5, 10 ) - 0
5 someFunction( a, 4, 10 ) - 6
4 someFunction( a, 3, 10 ) - 2
3 someFunction( a, 2, 10 ) - 1
2 someFunction( a, 1, 10 ) - 3
1 someFunction( a, 0, 10 ) - 8
No we can see the array has been "Reversed"
Upvotes: 1
Reputation: 85
The function does always call itself with the parameter startSubscript +1 until the startSubscript is equal then SIZE. Then the function call with the highest number, means this one with size == startsubscript will end. From there on the function call will process to an end in a backwards way. backwards means with a (last in first out logic).
Hint: Alway reproduce recursions with small numbers to see whats going on
Upvotes: 0