C program to find maximum and minimum element in array

Write a C program to enter elements in an array from user and find maximum and minimum elements in array. C program to find biggest and smallest elements in an array.

Example: If the elements of the array are: 10, 50, 12, 16, 2
Maximum = 50
Minimum = 2

Required knowledge

Basic C programming, For loop, Array

Logic to find maximum/minimum in array

Step 1: Read element in array.
Step 2: Let's suppose the first element of array as maximum. Set max=array[0]
Step 3: Set i=0
Step 4: If array[i] > max then Set max=array[i]
Step 5: Increment i by 1. Set i=i+1
Step 6: Repeat Step 4-5 till i<size (Where size is the size of array).

Increase your skills by leaning this program using recursive approach - C program to find maximum/minimum in array using recursion.

Program to find maximum/minimum element in array

 * C program to find maximum and minimum element in array

#include <stdio.h>

int main()
    int arr[100];
    int i, max, min, size;

     * Reads size array and elements in the array
    printf("Enter size of the array: ");
    scanf("%d", &size);
    printf("Enter elements in the array: ");
    for(i=0; i<size; i++)
        scanf("%d", &arr[i]);

    /* Supposes the first element as maximum and minimum */
    max = arr[0];
    min = arr[0];

     * Finds maximum and minimum in all array elements.
    for(i=1; i<size; i++)
        /* If current element of array is greater than max */
            max = arr[i];

        /* If current element of array is smaller than min */
            min = arr[i];

     * Prints the maximum and minimum element
    printf("Maximum element = %d\n", max);
    printf("Minimum element = %d", min);

    return 0;

Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10
Maximum element = 100
Minimum element = -10

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment