Finding Largest and Smallest in C++

Beginner

Introduction

In this lab, you will learn how to find the largest and smallest of three numbers using the if-else blocks in C++ programming language.

Declare variables

Begin by declaring the variables that will hold the three numbers, as well as the variables that will hold the smallest and largest numbers. Add the following code to declare the variables:

#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";

    // Declare variables
    int n1, n2, n3, smallest, largest;

    // Taking input from user
    cout << " Enter the three numbers :  \n\n\n";
    cin >> n1 >> n2 >> n3;

Set initial values

Set the smallest and largest values to two of the user-entered numbers. We do this because we will be comparing the third number to the current smallest and largest numbers in if statements. Add the following code:

    // Set initial values
    smallest = n1;
    largest = n2;

Compare values and assign new values

Compare each of the remaining numbers to the current smallest and largest variables. If one of the remaining numbers is smaller than the current smallest variable, set the smallest variable equal to that number. If one of the remaining numbers is larger than the current largest variable, set the largest variable equal to that number. Add the following code:

    // Compare values and assign new values
    if (n2 < smallest)
    {
        smallest = n2;
    }

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

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

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

Output smallest and largest numbers

Output the smallest and largest numbers to the console using cout statements. Add the following code:

    // Output smallest and largest numbers
    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;
}

Summary

This lab showed you how to find the largest and smallest of three numbers in C++ using if-else blocks. You learned how to declare variables, set initial values, compare values, and output results to the console. With this knowledge, you can write more complex programs that make decisions based on user input.

Other Tutorials you may like