In this tutorial, we will learn how to write a C Program to Find the Largest and Smallest Number in an Array. Before continuing, you should have knowledge of the following topics in C programming.
Program to find Largest and Smallest Element in an Array in C
The programs take user inputs for the size of an array and the values of the elements Then the variables to store the largest and smallest (large, small
) element is initialized to the 0th position of an array.
Then the program is run through the for loop and inside it, two if
statements are present that are executed if the largest or the smallest element is encountered. The literation loops for the size of an array.
Lastly, the small and large value is displayed along with their respective position (starts from 1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #include <stdio.h> int main() { int arr[50], size, i, large, small; int maxPos, minPos; printf("Enter the size for an array: "); scanf("%d", &size); printf("Enter %d elements of an array:\n", size); for (i = 0; i < size; i++) scanf("%d", &arr[i]); //initializing large and small element to 0th position large = small = arr[0]; for (i = 1; i < size; i++) { //for large element if (large < arr[i]) { large = arr[i]; maxPos = i; } //for small element if (small > arr[i]) { small = arr[i]; minPos = i; } } //Display printf("The largest element is %d at %d position.", large, maxPos + 1); printf("\nThe smallest element is: %d at %d position.", small, minPos + 1); return 0; } |
Output:
Enter the size for an array: 5
Enter 5 elements of an array:
66
2
77
9
15
The largest element is 77 at 3 position.
The smallest element is: 2 at 2 position.