C program || find the maximum and minimum element of the array

C program to find the maximum and minimum element of the array





Given an array arr[] of N integers, the task is to write the C program to find the maximum and minimum element of the given array iteratively and recursively.

Input: arr[] = {1, 2, 4, -1}
Output:
The minimum element is -1
The maximum element is 4

Input: arr[] = {-1, -1, -1, -1}
Output:
The minimum element is -1
The maximum element is -1


#include <stdio.h>
int main() {
int n, i;
printf("Enter the number of elements in the array: ");
scanf("%d", &n); int arr[n];
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
 } int max = arr[0];
int min = arr[0];
for (i = 1; i < n; i++) { 
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
 } 
printf("Maximum element: %d\n", max);
printf("Minimum element: %d", min); return 0;
 }


This program prompts the user to enter the number of elements in an array and then the elements themselves. It then uses a for loop to iterate through the array and compares each element to the current max and min. If the current element is greater than the current max, it is set as the new max. If the current element is less than the current min, it is set as the new min. Finally, the program prints out the max and min elements of the array.

Post a Comment

0 Comments