Trouble with Functions

Hello , I am learning to Program in C++ and i have hit a wall with functions. I have been working on this program for a while. If i input 1234 for the number i expect to get 4321 but i am only getting 4 and not the rest. It seems that the while loop is not going all the way through. if i put the while loop inside main and initialize rev and num to 0 and cout << rev at the end of the loop i do get 4231 as expected. But i need to do this by calling a function that is outside main. Maybe i don't fully understand how to call functions or something. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 #include <iostream>
using namespace std;

int reverseDigit(int);

int main()
{

	int num = 0; // initial numbeer
	int rev;
	cout << "Please enter a 4 digit integer: ";
	cin >> num; // user input

	rev = reverseDigit(num);
	
	cout << "Your reversed number is " << rev << endl; // user output
	

	return 0;
}

int reverseDigit(int num)
{
	int rev;

	while (num > 0)
	{
		rev = num % 10; 
		num = num / 10; 	
		return rev;
	}
}
Last edited on
your return statement on line 30 needs to be outside the loop. Also rev can hold only one number. Each time rev = num % 10; executes the previous digit is replaced by the new digit.
Last edited on
So i see that when i put the return statement outside the loop it finishes the loop and gives me the last number. in the case 1234 it would give me 1. if i put a cout << rev right after it will display all the numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
int reverseDigit(int num)
{
	int rev;

	while (num > 0)
	{
		rev = num % 10; 
		num = num / 10; 
		
		cout << rev;
	}
	return rev;


But as you noted rev will only hold 1 number and that is where i am stuck since i wish to call the function from main and give me the numbers in reverse. Is this maybe not the right approach? is there a way of maybe storing each result of the loop into a variable? so something like 4 variables since its a 4 digit number and the first digit i would multiply by 1000 , then the next by 100, then the next by 10, then the next by 1 and then add them up ?
I only see one line missing, and thats the one that builds your answer.
1
2
3
4
5
6
7
8
9
10
11
12
13
int reverseDigit(int num)
{
    int rev = 0;
    int temp;

    while (num>0)
    {
        temp = num % 10;
        num  = num / 10;
        rev = (rev*10) + temp;
    }
return rev;
}

Last edited on
thank you jaybob that did it. I was trying to do something very complicated but that makes more sense. Also thanks everyone else for their help!
Topic archived. No new replies allowed.