#Help to reverse output

21 messages · Page 1 of 1 (latest)

dense steeple
#

I have function that takes number as parameter and it forms array from digits of number., but it prints out number reversed. How can i fix this?
My code:

void digits_array(int number, int digits[]) {
int i = 0;
while (number != 0) {
digits[i] = number % 10;
number /= 10;
cout << digits[i] << " ";
}

}

regal fossilBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

potent flicker
#

You’re starting with the last digit (least significant) and printing it

#

If you wanted it “in order”, you can print all the digits in reverse order in a separate loop

#

Also, you’re not incrementing i

dense steeple
#

#include <bits/stdc++.h>
using namespace std;

void digits_array(int number, int digits[]) {
int i = 0;
while (number > 0) {
digits[i] = number % 10;
number /= 10;
cout << digits[i] << " ";
}

}

int main() {
int number;
cin >> number;
int digits[0];
digits_array(number, digits);
return 0;

#

Full code

potent flicker
#

Well why is your array of size 0

#

Also don’t use <bits/stdc++.h>

crisp sentinel
dense steeple
crisp sentinel
#

An unhealthy habit of coding in C++

dense steeple
crisp sentinel
crisp sentinel
potent flicker
#

It could compile slower and pollute the global namespace (potentially)

#

Also it doesn’t work on all compilers, very easy fix

dense steeple
#

TY

regal fossilBOT
#

@dense steeple Has your question been resolved? If so, run !solved :)

dense steeple
#

!solved