In: Computer Science
In C programming, Thank you
Declare an array that can contain 5 integer numbers.
Use a for loop to ask the user for numbers and fill up the array
using those numbers.
Write a program to determine the 2 largest integers in the array,
and print those numbers.
Hint: You can declare integer variables “largest” and “secondLargest” to keep track as you make comparisons using the if...elseif statement.
The following is an example of how your program should look when you execute it:
Enter a number to store in the array: 10
Enter a number to store in the array: 91
Enter a number to store in the array: 145
Enter a number to store in the array: 94
Enter a number to store in the array: 97
The largest number is 145
The second largest number is 97
#include <stdio.h>
int main() {
int values[5];
// taking input and storing it in an array
for(int i = 0; i < 5; i++)
{
printf("Enter a number to store in the array: ");
scanf("%d", &values[i]);
}
int max1=values[0];
int max2=values[0];
// printing elements of an array
for(int i = 1; i < 5; i++)
{
if(values[i]>=max1)
{
max2=max1;
max1=values[i];
}
else if(values[i]>=max2)
{
max2=values[i];
}
}
printf("the largest number is : %d \n", max1);
printf("the second largest number is : %d \n", max2);
return 0;
}
Explanation of Code
1. First we have declared an array named 'values[5]' which can accomodate 5 integer type values.
2. Then we have used a for loop to enter values in the array.
for(int i = 0; i < 5; i++)
{
printf("Enter a number to store in the array:
");
scanf("%d", &values[i]);
}
3. Then we have made 2 integer type variables 'max1' to store largest value and 'max2' to store second largest value. max1 and max2 are initialized to 0th element of 'values[]'.
int max1=values[0];
int max2=values[0];
4. Then we have made another for loop. Inside the for loop we are checking if the current index value is greater than max1 or not. If current index value is greater than max1 then we are storing the value of max1 in max2 because this value becomes the second largest value now (first largest value is the current index value). Then we are storing the current index value in max1.
if(values[i]>=max1)
{
max2=max1;
max1=values[i];
}
5. Then we have made another else if condition because it is possible that the current index value is not greater than max1 but it might be greater than max2. If current index value is greater than max2 then we store the current index value in max2.
else if(values[i]>=max2)
{
max2=values[i];
}
6. At last we have printed max1 and max2.
printf("the largest number is : %d \n", max1);
printf("the second largest number is : %d \n",
max2);