C program to find largest number in an array with simple logic and example and test cases.

Example:
Input Array: 2 6 4 8 9
Output: 9

LOGIC:

• Create an integer variable and store first element of the array into it, assuming this is largest value.
• Traverse the array using for a loop from location 1 to array length -1. 0th location we have already stored in largest variable.
• Check if current element is larger than value stored in largest variable. If it is larger, then assign the largest variable with current array location value.
• Once loop is over, largest variable contains largest/max value.

C Program To Find Largest Number In An Array

/* --------------------------------------------------
* C Program to find largest number in Array
*/
#include<stdio.h>
/* --------------------------------------------------
* C function to find largest element
* in an integer array
*
* @ parameters:
* int*arr : It accept base address of int array
* int len : length of the array
*
*
* @ return : It returns the largest / maximum
* value from array
*/
int findLargest( int *arr, int len){

int largest, i;

//Assume first element is largest
largest = arr;
for(i=1; i<len; i++) {
/* If current element is larger, then assign
* value to largest variable.
*/
if(arr[i] > largest){
largest = arr[i];
}
}

//Return the largest number
return largest;
}

/* --------------------------------------------------
*	C TEST PROGRAM
*/

int main()
{
int largestNumber;
int arr;//you can change the capacity
int index,size;

/* Enter size of the int array */
printf("Enter The Size of array: ");
scanf("%d", &size);

/* Input array elements */
printf("Enter elements: ");
for(index=0; index<size; ++index)
{
scanf("%d", &arr[index]);
}

//Call function to get largest number
largestNumber = findLargest(arr, size);
printf("Largest Element = %d", largestNumber);

return 0;
}

Output:
Test case-1
Enter The Size of array: 5
Enter elements: 2 6 4 8 9
Largest Element = 9

Test case -2: With duplicate elements
Enter The Size of array: 5
Enter elements: 9 2 2 5 6
Largest Element = 9

Published inC Programming Examples