Why is the Output of the code "159"?? Also what is C=z[a] [b] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the Output of the code "159"?? Also what is C=z[a] [b]

#include<stdio.h> #define ROWS 3 #define COLUMNS 4 int z [ROWS][COLUMNS]= {1,2,3,4,5,6,7,8,9,10,11,12}; main() { int a, b, c; for(a=0; a<ROWS; ++a) { c = 999; for (b=0; b<COLUMNS; ++b) if (z[a][b]<c) c=z[a][b]; printf("%d",c); } }

7th Dec 2021, 4:32 AM
Tiziah Vylet Valeroso
2 Answers
+ 4
Your array (z), with proper curly braces looks like; { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} } z[a][b]; Is used to access the elements of the array, where a is the index value for the row and b is the index value for the column. I.E. if a = 0 and b = 2 then the value would be 3. Each iteration of the outer loop c is set to the value 999 and a will be equal to the current index of the row. Then in the 1st iteration of the inner loop it checks if the value at z[a][b] is less than c and if so sets that value to c. So, the 1st iteration of the outer and inner loops, a is equal to 0 and b is equal to 0, giving the value 1. 1 is less than 999 so c is set to 1. None of the other values in this row are less than 1, so it is output at the end of the outer loop after the inner loop finishes. This repeats for the next 2 iterations of the outer loop where a = 1 b = 0 setting c to 5, and then again where a = 2 b =0 setting c to 9.
7th Dec 2021, 5:03 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Code outputs first column's value from each row. So it actually outputs 1, 5 and 9, not 159. You have a 2D array with 3 rows, 4 columns each. { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } } Loop array by the rows Let <c> be 999 Loop sub-array by the columns If element at [row] [column] is less than <c> Assign element [row] [column] to <c> Since your array contains values in ascending order, the `if` block above only evaluates to true when checking the first column of each row. So your code actually print value of first element (column) of each row in the array ...
7th Dec 2021, 4:59 AM
Ipang