### Arrays

I have created a program that the user enters in 3 digits and the program reverses the digits and prints it out.
Except in my reverse function it seems to only send out the last of the 3 digits (i.e if you were to enter 1, 2, 3) it will only printout 3,3,3.
How do I make it print out all the digits?

 1234567891011121314151617181920212223242526272829303132333435363738 #include using namespace std; int reverse (int a[]) { int n; int b [3]; int i; i = 0; for(n=2; n>-1; n--) { b[i] = a[n]; i++; } return *b; } int main () { int e [3]; int r; int n; cout << "Please enter 3 numbers: " << endl; for(n=0; n<3; n++) { cin >> e[n]; } r = reverse(e); cout << "The 3 numbers reversed are: " << endl; for(n=0; n<3; n++) { cout << r << endl; } }
@mrantonresch

Here's one way. I'm sure others will show you more elegant answers, but this is how I would do it..

 1234567891011121314151617181920212223242526272829303132333435363738394041 // Reverse Digits.cpp : main project file. #include using namespace std; int reverse (int e[]) { int n; int b [3]; int i; i = 0; for(n=0; n<3; n++) { b[n] = e[n]; } for(n=0; n<3; n++) { e[n] = b[2-n]; } return *e; } int main () { int e [3]; int n; cout << "Please enter 3 numbers: " << endl; for(n=0; n<3; n++) { cin >> e[n]; } reverse(e); cout << "The 3 numbers reversed are: " << endl; for(n=0; n<3; n++) { cout << e[n] << endl; } }
Thank you so much, I finally understand it, ive been stuck for 2 days now.
In the original code, you return only the first element of the local b array, which is why you output the same number 3 times

For kicks:

 123456789101112131415161718192021222324 #include void do_it(int n) { if ( n == 0 ) { std::cout << "The numbers are\n" ; return ; } int input ; std::cin >> input ; do_it(n-1) ; std::cout << input << ' ' ; } int main() { std::cout << "Please enter 3 numbers.\n" ; do_it(3) ; std::cout << std::endl ; }
Topic archived. No new replies allowed.