+ 1
Hey friends explain me this code and the for loop ?
2 Answers
+ 5
Albert Whittaker :Fan Ofđ Motu Patluđ this should not be done ideally... you have defined 2 rows and four columns where as you are trying to access four rows..
input value is as below:
1 2 3
4 5 0 // zero as you have not fully intialized
output is as below:
1 // first row first element
4
0
0 // fourth row first element
as third and fourth row are not the re in declaration itself, you should not access those values
+ 3
int x[2][3]={1,2,3,4,5};
Array declaration and initialization doesn't match here, you declared a two dimensional array (two rows with 3 columns each), but you are initializing it with a single dimension array values. As you initialized half way (last column of 2nd row is omitted), compiler fills the array as follows:
{{1,2,3},{4,5,0}}
{1,2,3} // first row
{4,5,0} // second row.
int i = 0, j = 0;
Assign zero for value of i and j
for(; i < 4; i++)
cout << x[i] [j]; // output 1400
Run a loop with x, from 0 to 3.
Here's how it goes:
x y {{1,2,3},{4,5,0}}
0 0 => 1 // [0][0]
1 0 => 4 // [1][0]
2 0 => 0 // garbage (invalid row)
3 0 => 0 // garbage (invalid row)
The array only has two rows, by accessing third & forth row you are using garbage values.
Hth, cmiiw