Recursion

Jun 14, 2008 at 4:57am
I am having trouble with my assignment that deals with recursion. My assignment is to create a recursive function that will accept a positive number, then print the number backwards to the screen. (ex: input of 123 would output 321 to the screen.) I am not allowed to use strings. I don't really understand how I can begin to do this, as I've only written a few other recursive functions before my attempt at this. I have read several articles online and the chapter on recursion in my textbook, but still no luck. Any help would be appreciated.
Jun 14, 2008 at 9:02am
Try storing the number in a charcter sequence:
char buffer[100];
and writing a recursive function with the arguments:
recursive(char buffer[],int q)
which return an another character sequence,but at the first use give a value of 0 to q and for q, buffer[q]=result[100-q].In the recursive function,q is decreasing at each call.
Jun 14, 2008 at 9:23am
@Nandor
He isn't allowed to use strings.

@djr
Think about what you have to do to separate the powers (or 'digits') of a number:
123 % 10 = 3
123 / 10 = 12

Hope this helps.
Jun 15, 2008 at 6:56pm
@Duoas
Thank you, that helped very much. I didn't understand that I was able to break it down into its digits in that way...
Jun 15, 2008 at 7:49pm
Now that I have that fixed, I'm having trouble on another part of the same program. It's along the same kind of lines I think...


From the assignment:

"Array Totaler: Given an integer array of size 50 (Filled with numbers read in from the file “numbers.txt”, which is assumed to have 50 integer values),
do the following:
1) display the array to the screen (use 5 rows of 10 numbers each),
2) ask the user how many numbers they would like totaled (error trap accepting only numbers between 1 and 50),
3) Traverse the array recursively starting at the first element in the array and display each element in the array up to the number the user entered, and
4) display the total of all the elements traversed. You may NOT use a loop to total the numbers."


I can get all of the steps except for three. What's the thought process for breaking down a problem like this recursively?
Topic archived. No new replies allowed.