Explore how to write a C program to find the smallest element in an array. This guide provides a detailed explanation on initializing an array, iterating through its elements, and identifying the smallest value. Perfect for beginners looking to understand array operations and basic programming techniques in C.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 5, 40, 50};
int min = arr[0];
int i;
for (i = 1; i < sizeof(arr)/sizeof(arr[0]); i++) {
if (arr[i] < min)
min = arr[i];
}
printf("Smallest element in array: %d\n", min);
return 0;
}
Explanation:
Inside the main() function:
- An integer array arr is declared and initialized with values.
- An integer variable min is initialized to the first element of the array.
- A for loop is used to iterate through each element of the array, starting from the second element.
- Within the loop, if the current element is smaller than the current minimum, update min to the current element.
- Finally, the smallest element in the array is printed to the console.