sort three numbers in c++

We can sort three numbers in C++ using the following steps:

  1. Declare three variables to hold the numbers, let's call them num1, num2, and num3.

  2. Read the three numbers from the user and store them in the respective variables.

  3. Use conditional statements (if-else) to compare the values of the variables and rearrange them in ascending order.

  4. Start by comparing num1 with num2. If num1 is greater than num2, swap their values using a temporary variable.

  5. Next, compare num2 with num3. If num2 is greater than num3, swap their values using the temporary variable.

  6. Finally, compare num1 with num2 again to ensure that they are in the correct order. If num1 is greater than num2, swap their values using the temporary variable.

  7. After these steps, the values of num1, num2, and num3 will be sorted in ascending order.

Here is an example code snippet to illustrate the steps:

#include <iostream>
using namespace std;

int main() {
    int num1, num2, num3;
    int temp;

    cout << "Enter three numbers: ";
    cin >> num1 >> num2 >> num3;

    if (num1 > num2) {
        temp = num1;
        num1 = num2;
        num2 = temp;
    }

    if (num2 > num3) {
        temp = num2;
        num2 = num3;
        num3 = temp;
    }

    if (num1 > num2) {
        temp = num1;
        num1 = num2;
        num2 = temp;
    }

    cout << "Numbers in ascending order: " << num1 << ", " << num2 << ", " << num3 << endl;

    return 0;
}

This code will prompt the user to enter three numbers, perform the sorting process, and then display the sorted numbers in ascending order.