Exercise:
Write a C Program to find largest element in an array.
Click Here to View the Solution!
#include <stdio.h>
int main() {
int i, num;
float arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &num);
for (i = 0; i < num; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%f", &arr[i]);
}
for (i = 1; i < num; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
Click Here to View the Output!
Enter the number of elements (1 to 100): 3
Enter number1: 50
Enter number2: 20
Enter number3: 79
Largest element = 79.00
Click Here to View the Explanation!
- This program is used to determine the largest element stored in an array.
- In
main()
, the program requests the user to enter the number of elements between 1 and 100 they want to store in the array and stores the number in the variablenum
using thescanf() function
. - A
for loop
is initialized that iterates betweeni = 0
andi < num
. In each iteration, the program requests the user to enter a number and stores these values in a floating-pointarray arr[i]
. - The second
for loop
is used to store the largest number in the array to the 0th index of the array. - The first two elements of the array are compared to find out the largest element between the two and that element is placed at the position
arr[0]
. - Similarly, the first and the third elements are compared and the largest between the two is placed at
arr[0]
. - This process continues the first and the last elements of the array are compared.
- Eventually, the largest element in the array will be placed at the position
arr[0]
and is printed.