write a c program to find out the difference between the largest and the smallest element present in an array. in this blog, we will focus on finding the maximum and minimum quantity in an array and find out their difference
Sample Input and Output
Array is [14,45,85,96,52]
the largest element is 96 and the smallest is 14
and the difference between 96 and 14 is 82
Algorithm to the difference between the largest and smallest element of an array
- Creating an array
- Finding out largest and smallest elements from the array
- Calculating the difference between them
- Print the output
C program to find the difference between the largest and smallest element of an array
#include<stdio.h> void main(){ int arr[100],a,i,max,min,diff; printf("size of array is:"); scanf("%d",&a); printf("enter the element "); for(i=0;i<a;i++){ scanf("%d",&arr[i]); } printf("the array is \n"); for(i=0;i<a;i++){ printf("%d ",arr[i]); } printf("\n"); min= max=arr[0]; for(i=0;i<a;i++){ if(max<arr[i]){ max=arr[i]; } } for(i=0;i<a;i++){ if(min>arr[i]){ min=arr[i]; } } printf("%d is smaller then %d\n",min,max); diff=max-min; printf("the difference between them is %d",diff); }
Explanation of the code
Step 1 at first we include library
Step 2 declaring the main method with void as its return type
Step 3 declaring the array and other variables for further use
Step 4 command for user
Step 5 scanf method to take input of the size of the array
Step 6 another command for the user
Step 7, Step 8, Step 9 taking the input according to the size, using the loop, closing the scope of the loop
Step 10, Step 11, Step 12, Step 13 printing the inputted array using for loop, closing the scope of the loop
Step 14 breaking the line here for our convenience
Step 15 as we created two-variable above min and max, stores the first element of the array
Step 16 for loop to access the element one by one, this loop is for to find the greatest value in the array
Step 17 checking the condition whether the first element is smaller or greater than the next element
Step 18 if the condition is true then we update the value of the max variable to a new variable which is accessed
Step 19, Step 20 closing both the scopes
Step 21 for loop to access the element once again this loop is for to find the smallest value in the array
Step 22 checking the condition whether the first element is smaller or greater than the next element
Step 23 if the condition is true then we update the value of the min variable to a new variable which is accessed
Step 24, Step 25 closing both the scopes
Step 26 printing the max and min we a message
Step 27 calculating difference between largest and smallest elements
Step 28 printing the difference
Step 29 closing the scope of the main method
Output
In this blog, we have learned how to create a c program to find out the difference between the largest and smallest elements of an array