Signup/Sign In

C++ Find Largest and Smallest among 3 Numbers Program

Hello Everyone!

In this tutorial, we will learn how to Find the Largest and the Smallest among 3 numbers entered by the user, in the C++ programming language.

This program demonstrates the flow of the if-else blocks in the cpp programming language by making use of this example.

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to find the Largest and the Smallest number among 3 numbers ===== \n\n";

    //variable declaration
    int n1, n2, n3, smallest, largest;

    //taking input from the command line (user) all at once
    cout << " Enter the three numbers :  \n\n\n";
    cin >> n1 >> n2 >> n3;

    //assign initial value for comparison (as the undefined variables store a random value)
    smallest = n1;
    largest = n2;

    //logic to find the Smallest and the Largest number - Remember, each variable stores only the latest value inserted into it.
    if (n2 < smallest)
    {
        smallest = n2;
    }

    if (n3 < smallest)
    {
        smallest = n3;
    }
    if (n3 > largest)
    {
        largest = n3;
    }

    if (n2 > largest)
    {
        largest = n2;
    }

    cout << "\n\n The Smallest number among ( " << n1 << ", " << n2 << ", " << n3 << " ) is : " << smallest;
    cout << "\n\n The Largest number among ( " << n1 << ", " << n2 << ", " << n3 << " ) is : " << largest;

    cout << "\n\n\n";

    return 0;
}

Output:

C++ largest and smallest

We hope that this post helped you develop a better understanding of how to find the smallest and the largest numbers using the if-else blocks in C++. For any query, feel free to reach out to us via the comments section down below.

Keep Learning : )



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.