Home C Examples C Program to Find Largest Element in an Array

C Program to Find Largest Element in an Array

by anupmaurya

In this tutorial, we will write a C Program to Find Largest Element in an Array. An example program is shown below

#include<stdio.h>

int returnMax(int array[], int n){
    int max=0;
    for (int i = 0; i < n; i++)
    {
        if(array[i]>max){
            max = array[i];
        }
    } 
    array[0] = 999;
    return max;
}

int main(){
    int arr[]= {1,12,3,5455,5,67,654};
    int max = returnMax(arr, 7);
    printf("The maximum element in this array is %d", max);
     for (int i = 0; i < 7; i++)
     {
         printf("The element %d is %d\n", i, arr[i]);
     }
    
    return 0;
}
  1. We created a function “returnMax” which takes two arguments “array[]” and “n”; the parameter “array[]” will receive reference of an array and the parameter “n” will receive the size of an array.
  2. In the function “returnMax” body we created an integer variable “max” to store the maximum value.
  3. The “for” loop will iterate till the length of an array and the “if” will compare the value of each element of the array with the value of “max”; if the value of array element will be greater than the value of max than that value will be stored in the “max” variable.
  4. In the main program, an array of size 7 is initialized.
  5. The function “returnMax” is called and the reference of an array and its size is passed. The return value is stored in the variable “max”.

The main thing to note here is that we are passing the reference of an array to the function and if the user changes the value of array in the function it will also be changed in the main program. For example, we have assigned the value “999” to the index”0” of an array in the function “returnMax”; and shown in figure 1 when we output the array the value at index “0” is changed to “999”

Output of a C Program to Find Largest Element in an Array

The maximum element in this array is 5455
The element 0 is 999
The element 1 is 12
The element 2 is 3
The element 3 is 5455
The element 4 is 5
The element 5 is 67
The element 6 is 654

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.