Given 2 numbers, find the minimum of these 2 numbers
Using if-else to find minimum:
if (a < b)
min = a;
else
min = b;
How it works:
a < b
a
is smaller, store it in min
b
is smaller or equal, store it in min
✅ Why learn this approach?
💡 Edge case: When both numbers are equal (a == b), either can be the minimum. Our else
handles this by choosing b
.
Using the built-in min() function:
#include <cmath>
cout << "Minimum is " << min(a, b);
How it works:
The min(a, b)
function takes two values and returns the smaller one.
min(10, 200)
→ Returns 10
min(50, 50)
→ Returns 50
✅ Advantages:
❌ Disadvantage:
Alternative solution using min():
// Commented line in our code:
cout << "Minimum of " << a << " and " << b << " is " << min(a,b);
The <cmath>
library provides mathematical functions and constants.
To use it:
#include <cmath>
Common functions in <cmath>:
min(a, b)
→ Returns minimum of two valuesmax(a, b)
→ Returns maximum of two valuesabs(x)
→ Returns absolute value (removes negative sign)pow(x, y)
→ Returns x raised to power y (x^y)sqrt(x)
→ Returns square root of xceil(x)
→ Rounds up to nearest integerfloor(x)
→ Rounds down to nearest integerround(x)
→ Rounds to nearest integerExamples:
min(5, 10)
→ 5max(5, 10)
→ 10abs(-25)
→ 25pow(2, 3)
→ 8 (2³)sqrt(16)
→ 4ceil(4.2)
→ 5floor(4.8)
→ 4round(4.5)
→ 5Use Logic-Building Approach when:
Use Library Functions when:
💡 Best practice: Learn the logic first (like we're doing!), then use library functions for efficiency. This way you understand what's happening under the hood.
Example with a=10, b=200:
long long a, b, min;
a = 10, b = 200
if (10 < 200)
→ TRUEmin = a;
→ min = 10
"Minimum of 10 and 200 is 10"
Example with a=100, b=20:
long long a, b, min;
a = 100, b = 20
if (100 < 20)
→ FALSEmin = b;
→ min = 20
"Minimum of 100 and 20 is 20"
Example with a=50, b=50:
long long a, b, min;
a = 50, b = 50
if (50 < 50)
→ FALSE (equal, not less)min = b;
→ min = 50
"Minimum of 50 and 50 is 50"
✅You might notice we include <cmath>
but don't use it in the solution.
Reason:
This demonstrates that there are two approaches to solving the problem:
The commented line shows the alternative:
// cout << "Minimum of " << a << " and " << b << " is " << min(a,b);
✅ Including the library prepares you to use min(a, b)
if needed, but we choose the manual approach to build stronger problem-solving skills.
💡 In competitive programming or interviews, showing you can build the logic manually is often more impressive than just using a library function!
💡 Tip: Master the logic first, then leverage library functions for efficiency. Best of both worlds!
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long long a, b, min;
cin >> a >> b;
// cout << "Minimum of " << a << " and " << b << " is " << min(a,b);
if (a < b)
min = a;
else
min = b;
cout << "Minimum of " << a << " and " << b << " is " << min;
}