problem in two dimensional array

hi

help me please , I have a big problem in arrays

i want to exchange rows with rows like this

A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y


to

F G H I J
A B C D E
K L M N O
P Q R S T
U V W X Y


here is 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
25
26
27
28
29
30
31
32
33
34
#include<iostream>
using namespace::std;

int main()
{
	int x;

	char Array[5][5]={{'A','B','C','D','E'},
	                  {'F','G','H','I','J'},
	                  {'K','L','M','N','O'},
                      {'P','Q','R','S','T'},
	                  {'U','V','W','X','Y'}};
	
	for(int row=0;row<5;row++)
	{
	for(int colom=0;colom<5;colom++)
	{
		
		
		x=Array[1][colom];
		Array[0][colom]=Array[1][colom];
		Array[1][colom]=x;

		


		cout<< Array[row][colom] << " ";
	}
	 
		cout<<endl;
	}
	
	return 0;
}


my code give output like this :

F G H I J
F G H I J
K L M N O
P Q R S T
U V W X Y
Your logic at lines 20-22 is messed up. You save array[1][c] into x.
You then overwrite array[0][c] with array[1][c].
You just lost the value you had in array[0][c].

You have the right idea with the temp variable, you're just putting the wrong value in it.
1
2
3
    x=Array[0][colom];  // save the value we're about to overwrite
    Array[0][colom]=Array[1][colom];  // go ahead and overwrite
    Array[1][colom]=x;  // store the saved value 


BTW, you're executing the row swap 5 times. The second and forth times you do it, you're putting the array back the way it was initially. You only need to do the row swap once.

Last edited on
mmmm , but i have same problem
the output is

F G H I J
F G H I J
K L M N O
P Q R S T
U V W X Y

:(
Well, here is another version

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
#include <iostream>


int main()
{
    int x, y, i, j;

    char Array[5][5] = {{'A','B','C','D','E'},
                        {'F','G','H','I','J'},
                        {'K','L','M','N','O'},
                        {'P','Q','R','S','T'},
	                {'U','V','W','X','Y'}};

    // Swap here
    for (i = 0; i < 5; i++)
   {
        x = Array[1][i];
        y = Array[0][i];

  	Array[1][i] = y;
	Array[0][i] = x;
    }

    // Print here
    for (i = 0; i < 5; ++i)
   {
       for (j = 0; j < 5; ++j)
       {
           std::cout << " " << Array[i][j];
       }

           std::cout << std::endl;
       }

    return 0;
}
Last edited on
Thank you very much , :)
Topic archived. No new replies allowed.