编程以找到数组的最大元素(Program to find the largest element of an array)

优质
小牛编辑
140浏览
2023-12-01

在数组中查找最大值是经典的C数组程序。 该程序使您可以深入了解迭代,数组和条件运算符。 我们迭代地检查数组的每个元素是否最大。 请参阅以下程序。

算法 (Algorithm)

让我们首先看看该程序的逐步程序应该是什么 -

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

伪代码 (Pseudocode)

现在让我们看看这个算法的伪代码 -

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

实现 (Implementation)

这个pseodocode现在可以在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