查找 C 中数组最小元素的程序



在数组中查找最小值是经典的 C 数组程序。此程序让你深入了解迭代、数组和条件运算符。我们迭代检查数组的每个元素,以了解它是否是最小的。请参见以下程序。

算法

让我们首先了解此程序的分步操作过程 −

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

伪代码

让我们现在了解此算法的伪代码 −

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

实施

此伪代码现在可以按如下所示在 C 程序中实施 −

#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;
}

输出应如下所示 −

Smallest element of array is 0
array_examples_in_c.htm
广告