#include <iostream>
usingnamespace 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 truefor the first arr[max_size] but gives garbage values for output array new_arr[max_size]
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.
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(constchar *header, int array[], size_t size)
{
cout << header;
for (size_t i = 0; i < size;++i) {
cout << ' ' << array[i];
}
}