+ 3
C++ 2d array how to reverse its values
I am having a problem when I reverse the specific row of a 2d array because it displays garbage numbers. Why is it happening and how to fix this.. thanks!! updated: I already figure it out!! thanks to my friends here in sololearn!! Here is my source code: https://code.sololearn.com/c1a68A10a98a
16 Respostas
+ 1
Matthew Tangpus the row reversing code has some problems. Starting in line 68,
count_col = columns;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
my2D_Array[row_Num][j] = my2D_Array[i][count_col];
count_col--;
}
}
I see two problems here:
1. count_col = columns goes out of bounds of the row index. It is 1 too high. Advice: use columns-1.
2. The reversing loop overwrites the first half of the array before the values can be used for the last half of the loop. Advice: before you start the loop, make a copy of the row into a temporary array. Then within the reversing loop copy back from that temporary array.
+ 4
Matthew,
Of course reversing stuffs with loops is possible. I haven't figured out why those strange values, maybe someone watching this thread already have : )
In the meantime, here's how I'd do it using std::reverse of <algorithm>
* Code edited
https://code.sololearn.com/ccIKJd1TucCj/?ref=app
+ 2
Ipang How can you reverse its rows with algorithm library??
+ 2
Matthew,
I have updated my code with functions to reverse row and column wise.
+ 1
thanks folks I already changed my post. You can check my source code and see what is wrong with it.
+ 1
Ipang
An example output for reverse col:
Current 2d Array:
2 4 6
3 6 9
Choose a col to reverse: 2
2 4 9
3 6 6
+ 1
Matthew,
About reversing the row, are you allowed to use C++ facility or are you supposed to do this by yourself? just asking, cause it will be quite simple using atd::reverse from <algorithm>.
Idk why you are using nested loop in reverse row part, don't we already know which row to be reversed provided from user input?
+ 1
Ipang honestly I am new to c++ so I am coding it with fundamental thing i know as possible without the use of libraries..
+ 1
So you are allowed to use C++ facility, but you just wanna try to do it by yourself for learning purposes, is that it?
+ 1
Yup
+ 1
Ipang i do have knowledge in java and we can reverse the value of an array using loop but when I apply this concept to c++, I really had a struggle since it displays Unknown numbers (garbage numbers)
+ 1
Thanks Ipang I trully appreciate your time and effort in fixing my problem..
+ 1
I will study your code
+ 1
thanks!!
0
Matthew,
Just wanna ask something. I see menu option 4 "Reverse a column", how reverse column was supposed to be done? can you give a small example to illustrate a result of a matrix having its column being reversed?
0
Anyways I figure it out how to use loops in reversing rows and columns hehe...
https://code.sololearn.com/c1a68A10a98a