Please write code in C. Thank you!
Write a program that reads a list of integers, and outputs the two smallest integers in the list, in ascending order. The input begins with an integer indicating the number of integers that follow. You can assume that the list will have at least 2 integers and less than 20 integers.
Ex: If the input is:
5 10 5 3 21 2
the output is:
2 3
To achieve the above, first read the integers into an array.
Hint: Make sure to initialize the second smallest and smallest integers properly.
#include<stdio.h>
#include<limits.h>
void main()
{
// Array to store integers
int arr[20],i,n;
// Two variables to store min values
int min1,min2;
// Getting number of integers that will follow
scanf("%d",&n);
// Input of integers
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
// Initialising min1,min2 to integer maximum
value
min1=min2=INT_MAX;
//Loop through the integers
for (i=0;i<n;i++)
{
//Checking if the integer is the minimum value
if (arr[i]<min1)
{
min2 = min1;
min1 = arr[i];
}
//Checking if the integer is the second minimum value
else if(arr[i]<min2 && arr[i]!=min1)
min2 = arr[i];
}
//Displaying result
printf("%d %d",min1,min2);
}
Sample Runs:
Get Answers For Free
Most questions answered within 1 hours.