
C program to check the smallest and largest element in an array
Algorithm
Input: Input size of the array, elements of the array
output: Displays the largest and smallest element in an array
- Start
- Input the size of the array say n and enter the elements of the array a[n]
- small = a [ 0 ], large = a [ 0 ] , i = 0
- while ( i < n )
4.1 if ( small > a [ i ] )
4.1.1 small = a [ i ]
4.2 if ( large < a [ i ])
4.2.1 large = a [ i ]
4.3 i++ - Print "The largest elements in the array is " large
- Print "The smallest elements in the array is " small
- Stop
C Program
# include <stdio.h>
int main()
{
//Enter the size and elements of the array
int n,small,large;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements one by one: \n");
for (int i =0; i < n; i++)
scanf("%d", &a[i]);
small = a[0];
large = a[0];
for ( int i = 0; i < n; i++){
//checks for the smallest element in the array
if (small > a[i])
small = a[i];
//checks for the largest elements in the array
if (large < a[i])
large = a[i];
}
//prints the result
printf("The largest element in the array is %d\n", large);
printf("The smallest element in the array is %d\n", small);
return 0;
}
Note: This Program was created using visual studio code. The Program file can be downloaded by clicking here
Comments