Here is a sample program, the comments are documented in the code. Enjoy
/* This little snippet is a method of iterating an array without using loops of any kind, rather we can use recusion to do all our work */ #include <stdio.h> int p[] = { 20, 30, 1, 2, 5, 3 }; // our test array int size_ = sizeof( p ) / sizeof ( int ); // determins the array size using // simple maths sizeof the array, divided // by the size of its parts. /* initially pass size_ - 1 to the function ass this is the last element of the array and we wish to move in reverse order towards 0 the first element in the array */ void printArrayReverse( int index ) { if ( index < 0 ) // if we have passed beginning of array return; // must return to terminate the recusion of void func printf( "%i\n", p[index] ); // use recursion to get the previous element // in the array ( current pos - 1 ) printArrayReverse( index - 1 ); } /* initially pass zero to the function call as we wish to begin from zero moving forward through the elements of the array */ void printArray( int index ) { if ( index >= size_ ) // reached end of array return; printf( "%i\n", p[index] ); printArray( index + 1 ); // user recursion to get and print // next element ( current pos + 1 ) } int main() { printArrayReverse( size_ - 1 ); printArray( 0 ); return 0; }
