Arrays
Mar 13, 2013 at 4:05am UTC
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?
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 34 35 36 37 38
#include <iostream>
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;
}
}
Mar 13, 2013 at 4:29am UTC
@mrantonresch
Here's one way. I'm sure others will show you more elegant answers, but this is how I would do it..
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 34 35 36 37 38 39 40 41
// Reverse Digits.cpp : main project file.
#include <iostream>
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;
}
}
Mar 13, 2013 at 4:51am UTC
Thank you so much, I finally understand it, ive been stuck for 2 days now.
Mar 13, 2013 at 4:55am UTC
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
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.