用于在 C 中查找最大数组元素的程序



查找数组中的最大值是经典的 C 数组程序。此程序可让您深入了解迭代、数组和条件运算符。我们通过迭代的方式依次检查数组中的每个元素,确定其是否为最大值。请参阅以下程序。

算法

让我们首先了解此程序的分步步骤 −

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

伪代码

接下来,我们了解此算法的伪代码 −

procedure largest_array(A)

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

end procedure

实现

此伪代码现可按如下方式在 C 程序中实现 −

#include <stdio.h>

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

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

输出应如下所示 −

Largest element of array is 9
array_examples_in_c.htm
广告