two dim array_question


hi i just have created an account and i really want you guys to help me with my assignment..
{
Q-A: Write a method to initialize the array below with the given values.
1 2 3 4
5 6 7 8
9 4 0 1


B: Write a method to interchange two columns, indexed by two int parameters.
}
i already have done with A but when i tried to solve B i got lost
i'd really appreciate it if you guys help me .. any ideas?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
using namespace std;

int row=5;
int col=4;
int main() 
{
	int array[row][col];
	int i,j;
	int num=10;
	
	for(i=0; i<row; i++)
	{
		for(j=0; j<4; j++)
		{
			array[i][j]=num;
			cout<<array[i][j]<<" ";
			num++;
		}
		cout << endl;
	}
        return 0;
}
Last edited on
closed account (48T7M4Gy)
So, you might have to interchange columns 1 and 3. They are your 'two int parameters'

If you want to swap any 2 numbers, forgetting about a 2d array, how do you do it?

Once you know that you just run down the two columns and 'swap the a's and b's'.

Hint: you could do with a temp.
Last edited on
i used a function to change the columns also i used a temp but it did not work

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
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
void change(int c1, int c2);
int row=5;
int col=4;

int main() 
{
	int array[row][col];
	int i,j,c1,c2;
	int num=10;
	
	for(i=0; i<row; i++)
	{
		for(j=0; j<col; j++)
		{
			array[i][j]=num;
			cout<<array[i][j]<<" ";
			num++;
		}
		cout << endl;
	}
	
	change(c1, c2);
	for(i=0; i<row; i++)
	{
		for(j=0; j<col; j++)
		{
			array[i][j]=num;
			cout<<array[i][j]<<" ";
		}
		cout << endl;
	}
	
	return 0;
}
void change(int c1, int c2){
	
	int temp[row][1];
	int array[row][col];
	cout<<"there are 4 columns, enter 2 columns to interchange them: ";
	cin>> c1 >> c2;
	for(int i=0; i<row; i++)
	{
		for(int j=c1; j<col; j++)
		{
		
		temp[row][1]=array[i][c1];
		array[i][c2]=array[i][c1];
		array[i][c1]=temp[row][1];
	    }
	}
}
closed account (48T7M4Gy)
You can make it a little easier to follow once you realise that temp doesn't need to be indexed. It can be a simple temp without [][] dimesions.

temp = array[i][c1];
array[i][c1] = array[i][c2];
array[i][c2] = temp;


Also, remember that the column numbers are fixed and only i is changing.

yes it worked thank you.. kemort :)
Topic archived. No new replies allowed.