Program to find largest array element in C

Finding largest 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 largest. See the below program.


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

   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


Let's now see the pseudocode of this algorithm −

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]
   Display largest

end procedure


This pseodocode 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, 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;

The output should look like this −

Largest element of array is 9
Kickstart Your Career

Get certified by completing the course

Get Started