How do we find the lowest? | Sololearn: Learn to code for FREE!

0

How do we find the lowest?

For example int x[4] = { 3, 9, 7 , 10} How do I find which is the smallest number? This is regarding the ticket office question in c++ .

c++

4/17/2021 5:16:37 AM

Kruti

6 Answers

New Answer

+7

C++ has a function for this called std::min_element. See https://www.cplusplus.com/reference/algorithm/min_element/ #include <algorithm> int x[4] = {3, 9, 7, 10}; int min = *min_element(x, x+4); cout << min; It is part of the standard template library so works with arrays and container classes.

+6

Kruti Store first value in a variable and compare with next value. If next value is less than 1st value then that would be smallest number otherwise 1st value will be smallest number. int x[4] = {3, 9, 7, 10}; int min = x[0]; for (int i = 0; i < 4; i++) { if (x[i] < min) min = x[i]; } cout << min;

+2

Kruti Doesn't matter on order just try shared logic.

0

And what if the values are not in increasing order? For example int x[4] = { 12, 7, 20 , 1} Like when four numbers are randomly selected by the user?

0

Kruti if values are not in sorting or then u can use any sorting techniques to sort the values u can easily find min max or u can use STL library std::min() , std::max()

0

#include <iostream> using namespace std; int main() { int k[5] = {7, 2, 8, 1, 4}; int min = *k; for (int i=0;i<5;i++) { if (k[i] < min) min = k[i]; } cout << min; return 0; } // Hope this helps