- 2070 Asar · 5 marks
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)
Related questions
- Pass student array; display passed students · Computer Programming, chapter 7
- Pass array; largest and smallest · Computer Programming, chapter 7
- Pass 2D array; largest and smallest · Computer Programming, chapter 7
- Largest of n numbers in FORTRAN · Computer Programming, chapter 11
- Insert number at position in array · Computer Programming, chapter 11
- Function definition; sum of two numbers · Computer Programming, chapter 6
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- 8086 ALP: largest and smallest, display · Microprocessor, chapter 3
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9