🔍 Find Maximum and Minimum of Two Numbers Using If-Else in C++

Find Maximum and Minimum of Two Numbers Using If-Else in C++

🔍 Find Maximum and Minimum of Two Numbers Using If-Else in C++

Finding the maximum and minimum values between two numbers is a fundamental programming task. Using if-else statements in C++ is a straightforward approach to compare two values and determine which one is larger or smaller.

💡 How If-Else Helps Find Max and Min

The if-else structure allows your program to make decisions. By comparing two numbers with conditional operators, you can easily identify the maximum and minimum:

  • If the first number is greater than the second, it is the maximum, and the second is the minimum.
  • Otherwise, the second number is the maximum, and the first is the minimum.

📄 C++ Code Example


#include <iostream>
using namespace std;

int main() {
    int num1, num2;
    int maximum, minimum;

    // Input from user
    cout << "Enter the first number: ";
    cin >> num1;

    cout << "Enter the second number: ";
    cin >> num2;

    // Find maximum and minimum using if-else
    if (num1 > num2) {
        maximum = num1;
        minimum = num2;
    } else {
        maximum = num2;
        minimum = num1;
    }

    // Display results
    cout << "Maximum: " << maximum << endl;
    cout << "Minimum: " << minimum << endl;

    return 0;
}
    

✅ Sample Output

Enter the first number: 25  
Enter the second number: 40  
Maximum: 40  
Minimum: 25
  

📘 Definition: Finding Maximum and Minimum Using If-Else

Finding the maximum and minimum of two numbers using if-else is a fundamental programming technique where conditional statements compare the values and assign the larger and smaller values to variables accordingly. This method is easy to understand, efficient, and widely used in algorithm design, data processing, and problem-solving.

By leveraging if-else logic, programmers can direct the program flow based on comparisons, enabling decision-making capabilities essential for building dynamic and responsive applications.

🧠 Final Thoughts

Using if-else statements to find the maximum and minimum values is a simple yet powerful programming skill. It builds a foundation for understanding more complex decision structures and is perfect for beginners learning C++.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences