C Program to find smallest number of an array.
Objective
Write a C program to find the smallest number in an array.
Algorithm / Approach
- Read 5 elements into an array
a[5]. - Assume the very first element is the smallest:
min = a[0]. - Loop through the remaining elements.
- If an element is strictly less than the current minimum, update it:
min = a[i+1]. - Print the minimum value.
main.c
#include<stdio.h>
int main( ) {
int i,min;
int a[5];
printf("Enter 5 elements : ");
for(i=0; i < 5; i++) {
scanf("%d",&a[i]);
}
min = a[0];
for(i=0; i < 5-1; i++) {
if( a[i+1] < a[i] )
min = a[i+1];
}
printf("Smallest Number = %d",min);
return 0;
}
Expected Output
Enter 5 elements : 10 12 15 23 20 Smallest Number = 10
Explanation of the Program
- This logic is identical to finding the maximum, just with the comparison operator flipped from
>to<. - Note on the provided code: the loop uses
a[i+1]whileigoes up to 3 (sincei < 5-1). This correctly checks indices 1 through 4 against the baseline, but the standard way is to loopifrom 1 to 4 and just checka[i].
Complexity
Time Complexity
O(n)
Space Complexity
O(n)