136k views
0 votes
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.Ex: If the input is 5 10 5 3 21 2, the output is:2 3 You can assume that the list of integers will have at least 2 values.To achieve the above, first read the integers into a vector.Hint: Make sure to initialize the second smallest and smallest integers properly.

1 Answer

4 votes

Answer:

Following are the program in the C++ programming Language.

//header files

#include <iostream>

#include <vector>

using namespace std;//name space

// define main method

int main()

{

//set integer variables

int size, num;

//get input the size of the list

cout<<"Enter size of list: ";

cin >> size;

//set integer type vector variable

vector<int> vecs;

//Set the for loop

for (int index = 0; index < size; ++index)

{//get elements of the list from the user

cout<<" :";

cin >> num;

//push back the elements of the list

vecs.push_back(num);

}

//storing the first two elements in variable

int n = vecs[0], n1 = vecs[1], current , temp;

//set if conditional statement

if (n > n1)

{

//perform swapping

temp = n;

n = n1;

n1 = temp;

}

//Set for loop

for (int index = 2; index < size; ++index)

{

//store the value of the vector in the variable

current = vecs[index];

//set if conditional statement

if (current < n)

{

//interchange the elements of the variable

n1 = n;

n = current;

}

else if(current < n1)

{

n1 = current;

}

}

//print the value of first two smallest number.

cout <<"\\" <<n << " " << n1 << endl;

return 0;

}

Output:

Enter size of list: 5

:10

:5

:3

:21

:2

2 3

Step-by-step explanation:

Here, we define the required header files and namespace then, we define "main()" function inside the main function.

  • Set two integer data type variable "size", "num".
  • Print message and get input from the user in variable "size".
  • Then, we set integer vector type variable "vecs".
  • Set the for loop to get the number of input in the variable "num" from user.
  • Then, we push back the elements of the list and store first two elements of the list in the variable "n", "n1".
  • Set the conditional statement to perform swapping.
  • Define the for loop to store the list of the vector in the integer type variable "current".
  • Finally, we print the value of the two smallest numbers of the list.
User ManoDestra
by
4.5k points