Example HTML page

C Program to find the maximum (or largest) element in an array.

In this article, we are going to write a C Program to find the largest element in a given array.

Coming to mathematics i am giving you a list of elements as follows.

10,20,30,5,55,60,100

Among this, find the largest element. How you can do this. Initially assume that the first element is the maximum element.

Then we go for the second element that is ’20’ here.

we compare this with first element. 10<20, so we assume that the maximum value is now ’20’

Then we go to the next element in the array i.e. 30.

30>20 now the maximum value is 30.

what we are doing here is we have taken the first value as maximum, and we are comparing this element with the other elements in the array and finding the maximum element.

The same thing we are doing in the following program.

#include<stdio.h>
int main()
{
    int arr[10] = {10,5,25,35,45,48,65,100,66,22};
    int i, max;

    max = arr[0];

    for(i = 0; i < 10; i++)
    {
        // if value of current element is greater than previous value
        // then assign new value to max
        if(arr[i] > max)
        {
            max = arr[i];
        }

        }

      printf("Highest value = %d", max);

    // signal to operating system everything works fine
    return 0;
}
Finding the largest element in a given array.

Output:

Command Prompt
Highest value = 100
——————————–
Process exited after 0.164 seconds with return value 0
Press any key to continue . . .

We have taken an array with name ‘arr’ and initialized with ’10’ elements.  we assigned the max value with ‘arr[0]’ i.e. the first element in the array. Now we are comparing each element in the array with this value; if the array element is greater than the ‘max’ value,then ‘max’ is assigned with the array element.

Finally we are printing the largest value, which is in ‘max’ variable.

can you do it for finding the minimum element in a given array. Just replace the condition you are almost finished the program.

Here is a compiler for you and check it.

To find the the minimum element in a given array you may click the below link.

Program to find the minimum element in a given array

#include<stdio.h>


int main()
{
    int arr[10] = {10,5,25,35,45,48,65,100,66,22};
    int i, max;

    max = arr[0];

    for(i = 0; i < 10; i++)
    {
        // if value of current element is greater than previous value
        // then assign new value to max
        if(arr[i] > max)
        {
            max = arr[i];
        }

        }

      printf("Highest value = %d", max);

    // signal to operating system everything works fine
    return 0;
}
Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest