reverse the digits of elements of array

Q.
Write a program which reads 5 integer elements, stores them, reverse them all and store in a separate array. Print both arrays at the end.

my code:
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>
using namespace std;
int main(){
	int i,j;
	int max_size;
	cin>>max_size;
	int arr[max_size];
	int new_arr[max_size];
	int number,store=0;
	for(i=0;i<max_size;i++){
		cout<<"enter the 5-digit element of array : ";
		cin>>number;
		arr[i]=number;
		for(j=0;j<max_size;j++){
			store=store*10+(number%10);
			number=number/10;
		}
		new_arr[i]=store;
	}
	cout<<"the 5 digit element array is : "<<arr[0]<<" "<<arr[1]<<" " <<arr[2]<<" "<<arr[3]<<" "<<arr[4]<<endl;
	cout<<"the 5 digit element reverse order array is : "<<new_arr[0]<<" "<<new_arr[1]<<" "<<new_arr[2]<<" "<<new_arr[3]<<" "<<new_arr[4]<<endl;
	return 0;
}
it runs true for the first arr[max_size] but gives garbage values for output array new_arr[max_size]
Last edited on
line 3: main must be type int.

line 7,8: This is not standard C++. In C++, array sizes must be known at compile time (a const expression). Some compilers do allow this as a non-standard extension.

gives garbage values for output array new_arr[max_size]

You're initializing store to 0 only once (line 9). You need to set store to 0 each time through the outer loop. Your inner loop (for j) assumes that store has been initialized to 0 for each element.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Thanks AbstractionAnon
!!!
Not only are lines 7 & 8 non-standard C++, but they are also not part of the assignment. The assignment says that there are 5 integers, so you can replace lines 5 and 6 with const int max_size = 5;

You code will work fine but it's good design to make size of the array depend only on max_size. In other words, if someone changes max_size to 13, the program should work. Right now that won't happen because lines 20-21 print the first 5 elements only.

Those two lines are a good opportunity for a function. There are only two differences between them: the string that you print at first, and the array that's getting printed, so those two things become the arguments to the function:
1
2
3
4
5
6
7
void printArray(const char *header, int array[], size_t size)
{
    cout << header;
    for (size_t i = 0; i < size;++i) {
        cout << ' ' << array[i];
    }
}
Last edited on
Topic archived. No new replies allowed.