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

In this blog, we will create a program to find the difference between the largest and smallest element of an array.

Algorithm to create the respective code

The program takes an array and prints the largest and smallest element in the array.
1. The program takes over a number of elements.
2. Use the for loop to find the largest and smallest element.
3. The result will be printed.
4. The end.

C++ code to print the difference between the largest and smallest element of an array

#include<iostream>
using namespace std;
int main ()
{
    int arr[10], n, i, max, min, diff;
    cout << "Enter the size of the array : ";
    cin >> n;
    cout << "Enter the elements of the array : ";
    for (i = 0; i < n; i++)
        cin >> arr[i];
    max = arr[0];
    for (i = 0; i < n; i++)
    {
        if (max < arr[i])
            max = arr[i];
    }
    min = arr[0];
    for (i = 0; i < n; i++)
    {
        if (min > arr[i])
            min = arr[i];
    }
    cout << "Largest element : " << max ;
    cout << "\nSmallest element : "<< min;
    diff= max-min;
    cout<<"\ndifference is :"<< diff;
    return 0;
}

Output of the above code

Explanation of the above code

1. The user is first asked to enter the size of the array and it is stored in the variable ‘n’.
2. The array ‘arr’ of data type integer is declared with a size of 10.
3. Array elements are asked to be entered and stored in “arr” using a for a loop.
4. The value at index 0 arr is assigned to the variable ‘max’.
5. Using a for loop and initializing ‘i’ to 0, the largest element is found.
6. If max is less than arr[i], then the value of arr[i] is assigned to the max. i is incremented in each iteration.
7. The loop continues until “i” is less than “n”.
8. Similarly, the smallest element is found.
9. The value at index 0 arr is assigned to the variable ‘min’.
10. Using a for loop, the smallest element is assigned to min.
11. The result will then be printed.