C Example for Beginners: C Program to Find Largest Element in an Array

Hits: 18

(C programming Example for Beginners)

C Program to Find Largest Element in an Array

In this example, you will learn to display the largest element entered by the user in an array.

Find the Largest Element in an array


#include <stdio.h>
int main(){
    int i, n;
    float arr[100];
    printf("Enter the number of elements (1 to 100): ");
    scanf("%d", &n);

    for (i = 0; i < n; ++i) {
        printf("Enter number%d: ", i + 1);
        scanf("%f", &arr[i]);
    }

    // storing the largest number to arr[0]
    for (i = 1; i < n; ++i) {
        if (arr[0] < arr[i])
            arr[0] = arr[i];
    }

    printf("Largest element = %.2f", arr[0]);

    return 0;
}

Output

Enter the number of elements (1 to 100): 5
Enter number1: 34.5
Enter number2: 2.4
Enter number3: -35.5
Enter number4: 38.7
Enter number5: 24.5
Largest element = 38.70

This program takes n number of elements from the user and stores it in arr[].

To find the largest element,

  • the first two elements of array are checked and the largest of these two elements are placed in arr[0]
  • the first and third elements are checked and largest of these two elements is placed in arr[0].
  • this process continues until the first and last elements are checked
  • the largest number will be stored in the arr[0] position

We have used a for loop to accomplish this task.

for (i = 1; i < n; ++i) {
    if (arr[0] < arr[i])
        arr[0] = arr[i];
}

 

C Example for Beginners: C Program to Find Largest Element in an Array

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.