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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.