In this example, we’ll write a C program to find maximum and minimum elements in a 3D array.
#include <stdio.h>
int main() {
int arr[3][3] = {{11,2,3},{4,5,6},{1,8,9}};
int min=arr[0][0], max=arr[0][0], i, j;
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
if(arr[i][j]<min) {
min = arr[i][j];
} else if(arr[i][j]>max) {
max = arr[i][j];
}
}
}
printf("Min=%d and Max=%d", min, max);
return 0;
}
- Initially we’ve defined a 3 dimensional array with values
- We’ve also initialized the min and max variables with the first value the array
- We also declare 2 temporary variables to iterate over the array
- We use nested for loop to iterate over the 3 dimensional array
- Within the nested loop, we check if the current element is less than min, if yes, then we reset min with current value
- If the current element is not less than min, then we check if current element is greater than max, if yes, then we reset max with current value
- This way by the end of the iteration we will have the minimum value of the 3 dimensional array in min and maximum value in max