Help with program that will print integer digits in reverse with spaces in between

closed account (ozTkSL3A)
Hey guys, I'm currently stuck with trying to have spaces in between the digits of my output. What I have currently will not place the spaces in between the digits. For example, if the input was 12345, the output should be 5 4 3 2 1. Also, I have to use a while loop and have not yet reached arrays yet. Thanks guys!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main() {
	int n, reverse = 0;

	cout << "Enter an integer: ";
	cin >> n;
	while (n != 0) {
		int remainder = n % 10;
		reverse = reverse * 10 + remainder;
		n /= 10;
	}

	cout << "Reversed number = " << reverse;

	return 0;
}
Last edited on
Hi,

Try this :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;
int main() 
 {
	int n;
	cout << "Enter an integer: ";
	cin >> n;

	cout << "Reversed number = ";
 	if(n < 0) cout << "- ";
	do
     {
		int remainder = n % 10;
		cout << remainder << ' ';
		n /= 10;
	}while (n != 0);
 	return 0;
 }
Last edited on
Does that help you? : )
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
#include <iostream>

int main() {

    int n ;
    std::cout << "Enter an integer: ";
    std::cin >> n ;

    std::cout << "\nnumber: " << n << "\nreversed number with spaces in between: " ;

    if( n < 0 ) { // take care of negative numbers

        std::cout << "- " ; // print a leading negative sign
        n = -n ; // and then ignore the negative sign
    }


    do { // change while to do-while to make sure the loop executes at least once
         // (if the number is zero, one zero must be printed).

        std::cout << n % 10 << ' ' ; // print a space after each digit
        n /= 10 ;

    } while( n != 0 ) ;

    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/f450548ea66b66ea
closed account (ozTkSL3A)
Thanks guys for the responses. I got it!
You guys are awesome.
Topic archived. No new replies allowed.