codescracker
c

C Program to Find Largest Number in an Array



« Previous Program Next Program »

In this tutorial, you will learn and get code about finding the largest number from given list (or array) with and without using user-defined function.

Let's first create a program without using any function to find out the largest one from all.

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
int main()
{
    int arr[10], i, large;
    printf("Enter 10 Array Elements: ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    i=0;
    large = arr[i];
    while(i<10)
    {
        if(large<arr[i])
            large = arr[i];
        i++;
    }
    printf("\nLargest Number = %d", large);
    getch();
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample run:

c program find largest element in array

Now supply any 10 numbers and then press ENTER to see the largest one from all the given 10 numbers as shown below:

c find largest number in array

The program is very simple to understand, the only main logic used is:

  1. 0 is initialized to the variable i after getting all the 10 numbers from user
  2. arr[i] (first number) is initialized to large
  3. The second statement is created to assume that the first number is the largest one
  4. Compare this number (value in large) with rest of the 9 numbers
  5. If this number (large's value) is less than any of the number, then initialize that number to large
  6. After exiting from the while loop, we have a large variable that holds the largest number from the given list
  7. So just print its value as output

Using Function

Now let's create the same purpose program using some extra features. The extra feature is, user is allowed to define the size of array. And this program is created using a user-defined function named findLargest()

// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
int findLargest(int [], int);
int main()
{
    int arr[10], i, large, size;
    printf("Enter Array Size: ");
    scanf("%d", &size);
    printf("Enter %d Array Elements: ", size);
    for(i=0; i<size; i++)
        scanf("%d", &arr[i]);
    large = findLargest(arr, size);
    printf("\nLargest Number = %d", large);
    getch();
    return 0;
}
int findLargest(int arr[], int n)
{
    int lrg, i=0;
    lrg = arr[i];
    while(i<n)
    {
        if(lrg<arr[i])
            lrg = arr[i];
        i++;
    }
    return lrg;
}

Here is its sample run:

find largest number in array c

Same Program in Other Languages


« Previous Program Next Program »