The smallest element from three
To find the smallest element from three numbers in C++, you can follow these steps:
- Declare three variables to hold the three numbers:
num1
,num2
, andnum3
. - Prompt the user to enter the first number and store it in
num1
. - Prompt the user to enter the second number and store it in
num2
. - Prompt the user to enter the third number and store it in
num3
. - Compare
num1
withnum2
using an if statement. Ifnum1
is smaller thannum2
, compare it withnum3
. Ifnum1
is smaller thannum3
, thennum1
is the smallest number. - If
num1
is not the smallest number, comparenum2
withnum3
. Ifnum2
is smaller thannum3
, thennum2
is the smallest number. - If none of the above conditions are true, then
num3
is the smallest number. - Print the smallest number to the console.
Here is an example implementation of the above steps:
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;
if (num1 < num2) {
if (num1 < num3) {
cout << "The smallest number is: " << num1 << endl;
} else {
cout << "The smallest number is: " << num3 << endl;
}
} else {
if (num2 < num3) {
cout << "The smallest number is: " << num2 << endl;
} else {
cout << "The smallest number is: " << num3 << endl;
}
}
return 0;
}
This program prompts the user to enter three numbers and then compares them to determine the smallest number. The if-else statements are used to handle the comparisons and print the result to the console.