C program to find the largest number from an array; Through this tutorial, we will learn how to find largest or maximum number in an array using standard method, function and recursion in c programs.
Programs to Find Largest Number in an Array in C
- C Program to Find Largest Number in an Array using Standard Method
- C Program to Find Largest Number in an Array using Function
- C Program to Find Largest Number in an Array using Recursion
C Program to Find Largest Number in an Array using Standard Method
#include <stdio.h>
int main()
{
int a[1000],i,n,max;
printf("Enter size of the array : ");
scanf("%d",&n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
max=a[0];
for(i=1; i<n; i++)
{
if(max<a[i])
max=a[i];
}
printf("\nmaximum of array is : %d",max);
return 0;
}
The output of the above c program; as follows:
Enter size of the array : 5 Enter elements in array : 9 8 7 6 5 9 8 7 6 5 maximum of array is : 9
C Program to Find Largest Number in an Array using Function
#include <stdio.h>
int sumofarray(int a[],int n)
{
int max,i;
max=a[0];
for(i=1; i<n; i++)
{
if(max<a[i])
max=a[i];
}
printf("\nmaximum of array is : %d",max);
}
int main()
{
int a[1000],i,n,sum;
printf("Enter size of the array : ");
scanf("%d", &n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
sumofarray(a,n);
}
The output of the above c program; as follows:
Enter size of the array : 5 Enter elements in array : 1 9 2 8 7 maximum of array is : 9
C Program to Find Largest Number in an Array using Recursion
#include<stdio.h>
#define MAX 100
int getMaxElement(int []); // takes array of int as parameter
int size;
int main()
{
int arr[MAX], max, i;
printf("\n\nEnter the size of the array: ");
scanf("%d", &size);
printf("\n\nEnter %d elements\n\n", size);
for(i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
max = getMaxElement(arr); // passing the complete array as parameter
printf("\n\nLargest element of the array is %d\n\n", max);
return 0;
}
int getMaxElement(int a[])
{
static int i = 0, max =- 9999; // static int max=a[0] is invalid
if(i < size) // till the last element
{
if(max < a[i])
max = a[i];
i++; // to check the next element in the next iteration
getMaxElement(a); // recursive call
}
return max;
}
The output of the above c program; as follows:
Enter the size of the array: 5 Enter 5 elements 5 99 45 65 2 Largest element of the array is 99