Write a C program to find the largest element in an array

Description: Take 5 numbers in an array and print the largest one.

Hint:

  • Assume the first element is the largest. Then compare the others, and update the value if a bigger one is found.

C program to find the largest element in an array

#include <stdio.h>

int main(void) {
    int a[5], max;

    printf("Enter 5 numbers: ");
    for (int i = 0; i < 5; i++) {
        scanf("%d", &a[i]);
    }

    max = a[0];
    for (int i = 1; i < 5; i++) {
        if (a[i] > max) {
            max = a[i];
        }
    }
    printf("Largest = %d\n", max);
    return 0;
}

Output:

Output of the above program is

Enter 5 numbers: 23
91
45
67
12
Largest = 91

How it works

  • max starts as 23. When 91 is found, it is bigger, so max becomes 91. No later value is bigger.
  • For the smallest element, change > to <.

Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?