I encountered the below question in a C test:
Do the following two programs have the same output:
Program 1:
#include <stdio.h>
int main(){
float p[3][2];
int j=0;
for(int i=0; i<3; i++){
printf("Enter x%d y%d :", i+1, i+1);
scanf("%f %f", &p[i][j], &p[i][++j]);
j=0;
}
printf("%f %f\n", p[0][0], p[0][1]);
printf("%f %f\n", p[1][0], p[1][1]);
printf("%f %f", p[2][0], p[2][1]);
return 0;
}
Program 2:
#include <stdio.h>
int main(){
float p[3][2];
for(int i=0; i<3; i++){
printf("Enter x%d y%d :", i+1, i+1);
scanf("%f %f", &p[i][0], &p[i][1]);
}
printf("%f %f\n", p[0][0], p[0][1]);
printf("%f %f\n", p[1][0], p[1][1]);
printf("%f %f", p[2][0], p[2][1]);
return 0;
}
While writing the test, for obvious reason I reasoned that, In runtime j
and j++
(line 10 program 1) will get replaced by 0 and 1, So both programs will have the same output. But when I checked it in my computer output for both programs was as follows:
Output of Program 1:
Enter x1 y1 :1 1
Enter x2 y2 :3 2
Enter x3 y3 :4 1
-0.000000 1.000000
-0.000000 2.000000
0.000000 1.000000
Output of Program 2:
Enter x1 y1 :1 1
Enter x2 y2 :3 2
Enter x3 y3 :4 1
1.000000 1.000000
3.000000 2.000000
4.000000 1.000000
I think, in program 1 the values for p[0][0], p[1][0], p[2][0] are garbage values. I want to know why p[0][0], p[1][0], p[2][0] did'nt received the input values 1, 3, 4 respectively.