Program to find smallest array element in C


Advertisements

Finding smallest value in an array is a classic C array program. This program gives you an insight of iteration, array and conditional operators. We iteratively check each element of an array if it is the smallest. See the below program.

Algorithm

Let's first see what should be the step-by-step procedure of this program −

START
   Step 1 → Take an array A and define its values
   Step 2 → Declare smallest as integer
   Step 3 → Set smallest to 0  
   Step 4 → Loop for each value of A
   Step 5 → If A[n] < smallest, Assign A[n] to smallest
   Step 6 → After loop finishes, Display smallest as smallest element of array
STOP

Pseudocode

Let's now see the pseudocode of this algorithm −

procedure smallest_array(A)

   Declare smallest as integer
   Set smallest to 0
   FOR EACH value in A DO
      IF A[n] is less than smallest THEN
         smallest ← A[n]
      ENDIF
   END FOR
   Display smallest

end procedure

Implementation

This pseudocode can now be implemented in the C program as follows −

#include <stdio.h>

int main() {
   int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
   int loop, smallest;

   smallest = array[0];
   
   for(loop = 1; loop < 10; loop++) {
      if( smallest > array[loop] ) 
         smallest = array[loop];
   }
   
   printf("Smallest element of array is %d", smallest);   
   
   return 0;
}

The output should look like this −

Smallest element of array is 0
array_examples_in_c.htm
Advertisements