Public Group

# how's my recursion?

This topic is 4824 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm just looking for some comments on how I'm handling recursion in these little exercises. Any feedback is appreciated.
Quote:
 (Print an array) Write a recursive function printArray that takes an array and the size of the array as arguments and returns nothing. The function should stop processing and return when it receives an array of size zero.
#include <iostream>

using std::cout;
using std::endl;

void printArray( int a[], int size );

int main()
{
const int arraySize = 10;
int array[arraySize] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

printArray( array, arraySize );

return 0;

}	// end main

void printArray( int a[], int size )
{
if ( size > 0 )
{
printArray( a, size - 1 );
cout << a[size - 1] << endl;
}

}	// end function printArray


Quote:
 (Print a string backwards) Write a recursive function stringReverse that takes a character array containing a string as an argument, prints the string backwards and returns nothing. The function should stop processing and return when the terminating null character is encountered.
#include <iostream>

using std::cout;
using std::endl;

void stringReverse( char a[] );

int main()
{
char string[] = "hello there";

cout << string << endl;
stringReverse( string );

cout << endl;

return 0;
}

void stringReverse( char a[] )
{
static int i = 0;
int x = i;

if ( a != '\0' )
{
++i;
stringReverse( a );
cout << a[x];
}

i = 0;

}	// end function stringReverse



##### Share on other sites
They're simple and they work, so there's not much more to be said, really. Never lose sight of the fact that these are totally artificial exercises, however.

##### Share on other sites
Quote:
Original post by gnomer
Quote:
 (Print a string backwards) Write a recursive function stringReverse that takes a character array containing a string as an argument, prints the string backwards and returns nothing. The function should stop processing and return when the terminating null character is encountered.

void stringReverse( char a[] ){	static int i = 0;	int x = i;		if ( a != '\0' )	{		++i;		stringReverse( a );		cout << a[x];	}	i = 0;}	// end function stringReverse

I imagine that your proffessor (assuming this is for a class) will disagree with your use of a static variable here, especially when there is a much simpler solution to be found. Remember that an array variable can be manipulated just like a pointer...

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 9
• 9
• 9
• 14
• 12
• ### Forum Statistics

• Total Topics
633295
• Total Posts
3011245
• ### Who's Online (See full list)

There are no registered users currently online

×