0 votes
252 views

# Problem:

Hello Programmers! I am a novice C programmer striving hard to learn as much programming as possible in minimum time. I came across an assignment in which the programmer has to write a program that prints the second largest number in an integer array. I tried writing such a program and I succeeded in finding the largest number but, I am unable to understand how to get the second largest number. I am attaching the code I wrote. If someone could explain to me the changes I have to make to get the second largest number, I would be so thankful.
``````#include <stdio.h>

int main()
{
int i, j, largest = 0,second_largest = 0;
int arr[] = {8,44,6};
for(i = 0; i<3; i++)
{
if(arr[i] > largest)
{
largest = arr[i];
}

}
printf("%d", largest);

return 0;
}``````

Output:

``44``

0 votes

# Solution:

Hi! I appreciate that you at least tried to solve the problem. You only need to make minor changes in your program to get the second largest number in the given array. I am rewriting your code with the changes. Please refer to the comments to understand changes:

``````#include <stdio.h>
int main()
{
int i, j, largest = 0,second_largest = 0;
int arr[] = {6,44,8};
for(i = 0; i<3; i++)
{
//this condition will keep evaluating unless i = 3 or largest number is not found
if(arr[i] > largest) //if(arr[i] > 0)
{
second_largest = largest; //second_largest = 0
largest = arr[i]; //assigning the largest value of array to largest
}
else if(arr[i] > second_largest && arr[i] != largest) //if above condition is false, this one is evaluated
{
second_largest = arr[i];
}
}
printf("Largest: %d \nSecond largest: %d", largest, second_largest); //printing largest and second largest numbers

return 0;
}``````

Output:

``````Largest: 44
Second largest: 8``````

28.4k points
edited