C Online Compiler
Example: Find Max and Min in Array in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Max and Min in Array #include <stdio.h> int main() { // Step 1: Declare and initialize an array int arr[] = {12, 5, 89, 3, 72, 1, 45}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements // Step 2: Initialize max and min with the first element of the array int max_val = arr[0]; int min_val = arr[0]; // Step 3: Iterate through the array starting from the second element for (int i = 1; i < n; i++) { // Step 3a: Compare current element with max_val if (arr[i] > max_val) { max_val = arr[i]; // Update max_val if current element is greater } // Step 3b: Compare current element with min_val if (arr[i] < min_val) { min_val = arr[i]; // Update min_val if current element is smaller } } // Step 4: Print the maximum and minimum values printf("The given array is: {"); for (int i = 0; i < n; i++) { printf("%d", arr[i]); if (i < n - 1) { printf(", "); } } printf("}\n"); printf("Maximum element in the array: %d\n", max_val); printf("Minimum element in the array: %d\n", min_val); return 0; }
Output
Clear
ADVERTISEMENTS