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 fewer than 20 integers. Ex: If the input is: 5 10 5 3 21 2

Respuesta :

Answer:

Follows are the code to the given question:

#include <iostream>//header file  

using namespace std;

int main() //main method

{

int nums[20];//defining an array

int n,i,k;//defining integer variables

cout<<"Enter total number you want to insert: ";//print message

cin>>n;//input value of n  

cout << "Enter array numbers: " << endl;//print message

for (i = 0;i<n;i++) //defining for loop for input values from user-end

{

   cin >> nums[i];//input values

}

for (i = 0; i < n;i++) //defining for loop for count array values

{

   for (k =i+1;k<n;k++)//defining for loop for arrange value in ascending  order  

   {

       if (nums[i] > nums[k])//checking first and second value

       {

           int t = nums[i];//defining integer variable that hold first element value in t

           nums[i] = nums[k];//holding second element value in first element

           nums[k] = t;//assign value in t

       }

   }

}

cout<<"Two smallest number in list are:";//print message

 for (i = 0; i <2; ++i)//defining for loop that prints first two smallest value  

     cout<<nums[i]<<" ";//print value

   return 0;

}

Output:

Enter total number you want to insert: 6

Enter array numbers:  

5

10

5

3

21

2

Two smallest number in list are:2 3  

Explanation:

In this code, an integer array "nums" is defined, and in the next step multiple integer variable is defined, that uses the for loop input value from the user-end, and in the next step, another two for loop is declared, that uses if block to arrange value into the ascending order at which it stores two smallest value in first and second position in the array element, and in the next step, it uses another for loop to print its element value.