Pointer with array doubts in the code

Hi i have two doubts in the following code,the doubts are marked..PLs note that the following code is correct .This is a program to read 2d array using pointer ()i.e Dynamic array ,to calculate its rowsum and column sum and display this array along row sum and column sum.
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
#include<iostream.h>
#include<conio.h>

void main()
{ clrscr();
 int *Val,*Rsum,*Csum;
 int MaxR,MaxC,i,j;
  cout<<"Enter dimensions (row col):";
  cin>>MaxR>>MaxC;
 ///key concept
   Val=new int[MaxR*MaxC];   //actual 2D array
   Rsum=new int[MaxR];    //array to hold row sums
   Csum=new int[MaxC];    //array to hold col sums

    for( i=0;i<MaxR;i++)
      { cout<<"Enter elements of row "<<(i+1)<<":";
       Rsum[i]=0;  (CAN ANYONE EXPLAIN THIS LINE?) 
      for(j=0;j<MaxC;j++)
      {	  cin>>Val[i*MaxC+j];
	 Rsum[i]+=Val[i*MaxC+j];(WHY WE USE i*MaxC+j INSIDE Val)
	}
	}
	for(j=0;j<MaxC;j++)
	{ Csum[j]=0;
	  for(i=0;i<MaxR;i++)
	   { Csum[j]+=Val[i*MaxC+j]; }
	   }
	   cout<<"\n\n The given array along with Rowsum and Colsum is :\n\n";
	   for(i=0;i<MaxR;i++)
	   { for(j=0;j<MaxC;j++)
	       { cout<<Val[i*MaxC+j]<<'\t'; }
	       cout<<Rsum[i]<<endl;
	       }

	       for(j=0;j<MaxC;j++)
		{ cout<<Csum[j]<<'\t'; }
		cout<<endl;
	      delete[] Val;
	      delete[] Rsum;
	      delete[] Csum;

		getch();
		}
Last edited on
Line 17: Rsum[i] = 0; sets the value in Rsum[i] to 0. Prior to that Rsum[i] contains some junk value that would not be conducive to generating an accurate sum.

Rsum[i]+=Val[i*MaxC+j];(WHY WE USE i*MaxC+j INSIDE Val)

If we have a one-dimensional array, and wish to treat it as a two dimensional array, we must calculate the one dimensional index from our two dimensional indexes. We do this by multiplying the row index times the number of columns in the two dimensional array and adding the column index.

For instance in this one dimensional array (in which an element is equal to the index for an element:)
[0][1][2][3][4][5][6][7][8]

which we would like to treat as a two dimensional array:
   0  1  2
0 [0][1][2]
1 [3][4][5]
2 [6][7][8]


To calculate the one dimensional index of 1, 2 (row, column), we multiply the row index by 3 and then add the column index which gives us 5: 1 * 3 + 2 = 5

1
2
3
4
5
6
7
8
9
10
11
// http://ideone.com/So484g
#include <iostream>

int main()
{
    const unsigned rows = 3 ;
    const unsigned cols = 5 ;
    for ( unsigned row=0; row < rows; ++row )
        for ( unsigned col =0; col < cols; ++col )
            std::cout << '(' << row << ',' << col << ") = " << row * cols + col << '\n' ;
}
Thanks a lot !!
Topic archived. No new replies allowed.