# Thread: integers in reverse with a function call

1. ## integers in reverse with a function call

Greetings,

I really could use some insight if at all possible. I have to write a little program that has a function and takes a number in as an argurement and then returns it in reverse order, without using arrays. So if I enter "1234" at the prompt, I get back "4321".

Any ideas would be helpful....below is what i have so far and I have been working on this for 6 hours today...pls don't laugh, this is really hard stuff for me.

Thanks in advance for any ideas...

#include <stdio.h>

int reverse(int num)

{
/*reverse function here*/

return num;

}

main()

{

int num;

printf("Enter a four digit number>");
scanf("%d", &num);

reverse(num);

printf("num = %d\n", num);

getchar(); //temporary use for borland
getchar(); //temporary use for borland
}

2. First, you need to get the amount of digits in the number. Since it says "Enter a 4 digit number", I guess you can assume it always have 4 digits (in the other cases it will be undefined).

Second, use a for loop and the modulus operator. N mod 10 (N % 10, expressed in C code) gives the last digit in N. You want to multiply this number with 1000. Then you want to get the second last digit, which you get by doing a truncating division by 10 then using modulus again. Multiply this number with 100 and add it to your last result. Repeat this a total of 4 times.

By gradually multiplying the result by 10 instead of 1000 (the first time) you can do this algorithm with a variable number of digits, not just 4. See the code below:
Code:
int ReverseDigits(int Number)
{
int Result = 0;

while(Number > 0)
{
Result *= 10;
Result += Number % 10;
Number /= 10;
}

return Result;
}

3. I have to write a little program...

4. ## thanks....

wow, I actually get it! Thank you, all I had to do was perform some arithmatic functions to retun the value overall backwards...You just have to break these things down I guess. Thank you so much for your time and help...I'm going to play with it so I fully understand.

thanks again...