In this article, we will write a C program to find the largest element of an array. For example, if an array contains these elements [4, 6, 1, 12, 2] then program should print largest element 12 as output.
C Program to print largest element of an array
In this program, user is asked to enter size and elements of array. A variable largest
is initialized with first element of array. It is then compared with all other elements of array on by one, if an element is found greater than largest
, then largest
variable is updated with that element. This process goes on until whole array is traversed.
The step by step explanation of how this program works is provided at the end of this program.
#include <stdio.h>
int main() {
int n, i;
// Prompt user to enter the number of elements in the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n); //store the entered value in variable n
// Declare an array of size n to store array elements
int array[n];
// Prompt user to enter elements of the array
printf("Enter the elements of the array:\n");
for(i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &array[i]);
}
// Initialize the largest variable with first element
int largest = array[0];
/* Here we are comparing largest with
* all other elements of array. If any element is found
* greater than largest, then value of largest is updated to
* to contain this element. This way whole array is traversed
* and the largest variable contains largest element of array
*/
for(i = 1; i < n; i++) {
if(array[i] > largest) {
largest = array[i];
}
}
// Print the largest element
printf("The largest element in the array is: %d\n", largest);
return 0;
}
Output:
Enter the number of elements in the array: 5
Enter the elements of the array:
Element 1: 3
Element 2: 7
Element 3: 2
Element 4: 9
Element 5: 5
The largest element in the array is: 9
Step-by-Step Execution:
- User input:
- User enters number of elements:
5
- Program reads this value using
printf
and and stores it in variablen
usingscanf
statement.
- User enters number of elements:
- Input Array Elements:
- User enters each element of the array, one by one.
- Elements entered by user are:
3
,7
,2
,9
,5
- Program stores these values in the array
array[]
.
- Initialize Largest variable:
largest
variable is initialized to the first element(array[0]
) of array:3
- Find Largest Element in array:
- Compare
3
with7
(7 is greater, updatelargest
to 7) - Compare
7
with2
(7 is still greater, no update tolargest
) - Compare
7
with9
(9 is greater, updatelargest
to 9) - Compare
9
with5
(9 is still greater, no update tolargest
)
- Compare
- Print Largest Element:
- Print the value of
largest
variable which contains 9. This is our output.
- Print the value of
Leave a Reply