Hi ever one

i make a function that print the reverse integer e.g if we input 12345 it print 54321
but the problem is that when i use return b; it print 5 4 3 2 1 1 and when remove return b; then it prints 5 4 3 2 1 4469696 why it print 4469696 after 5 4 3 2 1 here is the code

//HEADER FILES
#include<iostream>
#include<conio.h>

using namespace std;

//START OF FUNCTION PROTOTYPE

int reverseDigit(int number);

//END OF FUNCTION PROTOTYPE



//START OF MAIN FUNCTION
int main ()
{


    cout<<"ENTER ANY INTEGER IT WILL REVERSE THE INTEGER AND PRINT IT."<<endl;


    cout<<"The reverse integer is = ";
    cout<<reverseDigit(12345);
    cout<<endl;


    getch();
    return 0;
}//END OF MAIN FUNCTION



//START OF FUNCTION BODY
int reverseDigit(int number)
{
    int b ;
    while(number > 0)
    {


                  b=number%10;
                  number= number/10;

                  cout<<b<<"  ";   



    }

        //return b;

}
//END OF FUNCTION BODY

Edited 3 Years Ago by pyTony: fixed formatting

I changed your reverseDigit() function so it will actually store the answer to a digit using / and % like you have.

The reason why you get an extra 1 at the end of the output when you keep return b is because you have it printing out in the function then returning the final value of b which is 1 in the case of 12345.

When you remove return b it still prints out 5 4 3 2 1 because of your print statements within the function but then it outputs a garbage number when you are printing the return value of the function. (it is garbage because you aren't returning anything)

You have two options.

Use the code that I posted below or change cout << reverseDigit(12345) << endl; to reverseDigit(12345); (remove the print statements)

#include <iostream>
#include <conio.h>
#include <cmath>

using namespace std;

int reverseDigit( int number );

int main()
{
	int inpt;
	cout << "ENTER ANY INTEGER IT WILL REVERSE THE INTEGER AND PRINT IT." << endl;
	cin >> inpt;
	cout << "The reverse integer is = ";
	cout << reverseDigit(inpt) << endl;

	return 0;
}

int reverseDigit( int number )
{
	int b = 0;
	int i = 0, n;

	for( i = -1, n = number; n > 0; i++ )
		n /= 10;

	while( number > 0 )
	{
		b += (number%10)*pow(10,i);
		number = number/10;
		i--;
	}
	return b;
}

Another method would be to use a stringstream.

#include <sstream> //need these headers
#include <algorithm>

int reverseDigit2( int number )
{
	string convert = "";
	stringstream strm;
	strm << number;
	strm >> convert;
	reverse(convert.begin(), convert.end());

	return atoi(convert.c_str());
}
This article has been dead for over six months. Start a new discussion instead.