Printing arrays with pointers

I modified the 2darray A to get array B. I need to use pointers to print both as AAAA BBBB. A has its own rows and columns and B has its own. but I can only print B as ABABABABAB or BBBB below AAAA.here's the code. where do I place cout<<*(ptrb+j);

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
  #include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	//cout<<setprecision(2)<<left<<endl;
	cout<<setw(15)<<"A"<<setw(20)<<"B"<<endl;
	const int sz=4;
	int A[sz][sz]={{10,15,20,25}, {100,200,300,400},{1,2,3,4},{5,6,7,8}};
	int B[sz][sz],i,c,j;
	int *ptra= &A[0][0];
	int *ptrb= &B[0][0];
		for ( j=0; j<(sz*sz); j++){
				if(j%2==0)

	*(ptrb+ j)=*(ptra + j) *10;
else
	*(ptrb+j)=*(ptra+j);
	
if (j%4==0)
	cout<<"\n";
		cout<<setw(5)<<*(ptra+j);
		}

cout<<endl;
cout<<endl;
c=12;
cout<<"**Diagonal Bottom Left"<<endl;
while (c>0){

	cout<<*(ptra+ c)<<"  "<<flush;
c=c-3;

}
    return 0;
}
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
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
	cout << setw(15) << "A" << setw(20) << "B\n";
	const int sz = 4;
	int A[sz][sz] = {{10,15,20,25},{100,200,300,400},{1,2,3,4},{5,6,7,8}};
	int B[sz][sz];
	int *pa= &A[0][0];
	int *pb= &B[0][0];

	for (int i = 0; i < sz * sz; i++) {
		if (i % 2 == 0)
			*(pb + i) = *(pa + i) * 10;
		else
			*(pb + i) = *(pa + i);
	}

	for (int i = 0; i < sz * sz; i += 4) {
		for (int j = 0; j < 4; j++)
			cout << setw(5) << *(pa + i + j);
		cout << "    ";
		for (int j = 0; j < 4; j++)
			cout << setw(5) << *(pb + i + j);
	        cout << '\n';
	}

	cout << "\n\n**Diagonal Bottom Left\n";
	for (int i = 12; i > 0; i -= 3)
		cout << *(pa + i) << "  ";
	cout << '\n';

	return 0;
}

That's not really using pointers, though. That's just using funny array syntax. Using pointers would look more like this:
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>
#include <iomanip>
using namespace std;

int main() {
    cout << setw(15) << "A" << setw(20) << "B\n";
    const int sz = 4;
    int A[sz][sz] = {{10,15,20,25},{100,200,300,400},{1,2,3,4},{5,6,7,8}};
    int B[sz][sz];
    int *pa= &A[0][0], *paend = &A[3][3] + 1;
    int *pb= &B[0][0];

    while (pa < paend) {
    	*pb++ = *pa++ * 10;
        *pb++ = *pa++;
    }

    pa = &A[0][0];
    pb = &B[0][0];
    while (pa < paend) {
        for (int i = 0; i < 4; i++)
            cout << setw(5) << *pa++;
        cout << "    ";
        for (int i = 0; i < 4; i++)
            cout << setw(5) << *pb++;
        cout << '\n';
    }

    pa = &A[0][0] + 12;
    cout << "\n\n**Diagonal Bottom Left\n";
    for ( ; pa > &A[0][0]; pa -= 3)
        cout << *pa << "  ";
    cout << '\n';

    return 0;
}

Last edited on
Topic archived. No new replies allowed.