Skip to main content

Function returning largest of array

Short answer

Define a function largest(int a[], int n) that sets max = a[0], then loops from index 1 to n-1 updating max when a[i] > max, and returns max. In main, input the array size and elements, call largest, and print the result.

Write a program using a function that returns the largest number from an array of numbers that is passed to the function.

The function largest(int a[], int n) receives the array (its address) and the number of elements. It assumes the first element is the largest, compares it with each other element and returns the maximum.

#include <stdio.h>

int largest(int a[], int n)
{
    int max = a[0];
    for (int i = 1; i < n; i++)
        if (a[i] > max)
            max = a[i];
    return max;
}

int main(void)
{
    int a[50], n;
    printf("How many numbers? ");
    scanf("%d", &n);
    printf("Enter %d numbers: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    printf("Largest = %d\n", largest(a, n));
    return 0;
}

Sample run

Input: 5 12 45 7 89 23

How many numbers? Enter 5 numbers: Largest = 89

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →