This program finds the largest and second-largest elements in an array of integers. Here's a step-by-step explanation of the code:
The preprocessor directive #define MAX 100 defines a constant MAX with the value 100, which sets the maximum number of elements in the array.
The main function starts by defining the following variables:
largest
variable will store the largest element in the array.second_largest
variable will contain the second largest element in the array.a
is an array of MAX elements, which will store the input array.len
is a variable that will store the number of elements in the array
The program prompts the user to enter the number of elements in the array.
If the number of elements is less than 2 then the program prints the message Array should have a minimum of 2 elements and exits.
The program then prompts the user to enter the elements of the array and uses a
for
loop andscanf
to read and store the input in the arraya
.largest
is initialized to the first element of the array andsecond_largest
to 0.The program then uses another for loop to iterate over the elements of the array. In each iteration, it checks if the current element is greater than
largest
. If it is, it updatessecond_largest
tolargest
andlargest
to the current element. If not, it checks if the current element is greater thansecond_largest
and not equal tolargest
. If it is, it updatessecond_largest
to the current element.Finally, the program prints the largest and second-largest elements and returns.
Here is the C program.
#include <stdio.h> #define MAX 100 int main() { int largest; int second_largest; int len; int a[MAX]; // Read the array printf("Enter number of elements in the array "); scanf("%d", &len); if (len < 2) { printf("The array should have atleast 2 elements."); return; } printf("Enter array elements:\n"); for (int i=0; i < len; i++) scanf("%d", &a[i]); largest = a[0]; second_largest = 0; for(int i=0; i < len ; i++){ if(a[i] > largest) { second_largest = largest; largest = a[i]; } else if((a[i] > second_largest) && (a[i] != largest) ) { second_largest = a[i]; } } printf("Largest is %d ", largest); printf("Second largest is %d ", second_largest); return 0; }
Sample output
Enter number of elements in the array 5 Enter array elements: 10 10 10 8 5 Largest is 10 Second largest is 8