Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find largest number of an array.

C Code Example — Array Programs

ADVERTISEMENT

C Program to find largest number of an array.

Objective

Write a C program to find the largest number in an array.

Algorithm / Approach

  1. Read 5 elements into an array a[5].
  2. Assume the very first element is the largest: max = a[0].
  3. Loop through the rest of the array elements.
  4. If any element is greater than the current max (a[i+1] > max), update the maximum: max = a[i+1].
  5. Print the maximum value.
main.c
#include<stdio.h>
int main( ) {
 int i,max;
 int a[5];
 printf("Enter 5 elements : ");
 for(i=0; i < 5; i++) {
  scanf("%d",&a[i]);
 }
 max = a[0];
 for(i=0; i < 5-1; i++) {
  if( a[i+1] > a[i] )
   max = a[i+1];
 }
 printf("Largest Number = %d",max);
 return 0;
}

Expected Output

Enter 5 elements : 10 12 15 23 20
Largest Number = 23

Explanation of the Program

  • This uses a classic Linear Search algorithm to find the maximum value.
  • By temporarily assuming the first element is the largest, we create a baseline. As we walk through the array, we compare each element against our baseline. If we find something bigger, we throw away the old baseline and keep the new champion.

Complexity

Time Complexity O(n)
Space Complexity O(n)
ADVERTISEMENT