C++ Exercises: Prints three highest numbers from a list of numbers in descending order
C++ Basic: Exercise-63 with Solution
Write a C++ program that prints the three highest numbers from a list of numbers in descending order.
Visual Presentation:
Sample Solution:
C++ Code :
#include <iostream> // Including input-output stream header file
#include <vector> // Including vector header file
#include <algorithm> // Including algorithm header file for sort function
using namespace std; // Using the standard namespace
int main() { // Start of the main function
vector<int> nums; // Declaring a vector to store integers
int n;
while (cin >> n) { // Loop to read integers from input until the end of input (Ctrl+D in terminal)
nums.push_back(n); // Storing the read integers in the vector
}
sort(nums.rbegin(), nums.rend()); // Sorting the vector in descending order
for (int i = 0; i != 3; ++i) { // Looping three times to print the first three elements of the sorted vector
cout << nums[i] << endl; // Printing the elements
}
return 0; // Indicating successful completion of the program
}
Sample Output:
Sample input : 2 5 3 7 29 1 Sample Output: 29 7 5
Flowchart:
C++ Code Editor:
Previous: Write a C++ program to which reads an given integer n and prints a twin prime which has the maximum size among twin primes less than or equals to n.
Next: Write a C++ program to compute the sum of the two given integers and count the number of digits of the sum value.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics