samedi 19 septembre 2020

showing strange output while printing an array

The following program find out the sum of the left diagonal of the matrix. I faced a strange problem regrading the problem.

 #include<stdio.h>
 #include<conio.h>

 int main()
{
     int arr[4][4];
     int i,j,l_sum=0;
     printf("\nENTER THE VALUE IN ARRAY:");
     for(i=0;i<=3;i++)
       {
          for(j=0;j<=3;j++)
          scanf("%d",&arr[i][j]);
      }
    printf("The matrix is :\n");
    for(i=0;i<=3;i++)
       {
            for(j=0;j<=3 ;j++)
            printf("% 4d",arr[i][j]);
            printf("\n");
       }
       l_sum=0;
       for(i=0;i<=3;i++)
          {
                for(j=0;j<=3;j++)
                {
                    if ( i == j)
                    printf("%d\t",arr[i][j]);//This line is problematic**
                    l_sum = l_sum + arr[i][j];
                 }
           }

       printf("SUM OF LEFT DIAGONAL IS :%d\t", l_sum);
       return 0;
  }

If I use the marked line I got wrong answer. But if I do not use this line I got correct result.

Output(correct- without the highlighted line):

The matrix is :

1   0   2   1
0   1   1   0
4   5   2   1
0   3   1   1

Sum of LEFT DIAGONAL IS: 5

Now if I use the specific line ("%d\t",arr[i][j]);

Sum of LEFT DIAGONAL IS: 23

For me this is really surprising.

If anyone guess the reason for this unusual behavior please share the reason with my post.

Thank you.

Aucun commentaire:

Enregistrer un commentaire