×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find the difference between the largest and smallest element in the array

Here, we are going to learn how to find the difference between the largest and smallest element in the array in C programming language?
Submitted by Nidhi, on July 11, 2021

Problem statement

Here, we will create an array of integers and find the difference between the largest and smallest element of the array and print the result on the console screen.

Finding difference between largest and smallest element in an array

The source code to find the difference between the largest and smallest element in the array is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

C program to find difference between largest and smallest element in an array

// C program to find the difference between the
// largest and smallest element in the array

#include <stdio.h>

int main()
{
    int arr[] = { 10, 20, 70, 40, 50 };

    int i = 0;
    int j = 0;

    int diff = 0;

    diff = arr[1] - arr[0];

    for (i = 0; i < 5; i++) {
        for (j = i + 1; j < 5; j++) {
            if (arr[j] - arr[i] > diff)
                diff = arr[j] - arr[i];
        }
    }

    printf("Difference is: %d\n", diff);

    return 0;
}

Output

Difference is: 60

Explanation

Here, we created an array arr with 5 elements. And, we also created three variables i, j, diff that are initialized with 0. Then we find the difference between the biggest and smallest elements of the array and store the result into a diff variable. After that, we printed the result on the console screen.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.