Introduction
In this lab, we will write a C++ program to find the greatest of three numbers.
In this lab, we will write a C++ program to find the greatest of three numbers.
We will create a new file named main.cpp
in the ~/project
directory using the following command:
touch ~/project/main.cpp
We need to include the iostream
and cstdlib
header files to use the cout
, cin
, and system
functions.
#include <iostream>
#include <cstdlib>
Add the following code to create the main()
function:
int main() {
// code will go here
return 0;
}
We need to declare three float variables to hold the three numbers entered by the user.
float n1, n2, n3;
We will use the cout
function to prompt the user to enter three numbers, and use the cin
function to store those numbers in the variables we just declared.
std::cout << "Enter three numbers: ";
std::cin >> n1 >> n2 >> n3;
We will use a series of if
statements to determine and output the largest number of the three.
if (n1 >= n2 && n1 >= n3) {
std::cout << "Largest number: " << n1;
}
if (n2 >= n1 && n2 >= n3) {
std::cout << "Largest number: " << n2;
}
if (n3 >= n1 && n3 >= n2) {
std::cout << "Largest number: " << n3;
}
Use the following command to compile and run the program:
g++ main.cpp -o main && ./main
Here is the full code for the main.cpp
file:
#include <iostream>
#include <cstdlib>
int main() {
float n1, n2, n3;
std::cout << "Enter three numbers: ";
std::cin >> n1 >> n2 >> n3;
if (n1 >= n2 && n1 >= n3) {
std::cout << "Largest number: " << n1;
}
if (n2 >= n1 && n2 >= n3) {
std::cout << "Largest number: " << n2;
}
if (n3 >= n1 && n3 >= n2) {
std::cout << "Largest number: " << n3;
}
return 0;
}
In this lab, we wrote a C++ program to find the greatest of three numbers. We learned how to use the if
statement to compare values, and prompt the user for input using cout
and cin
. We also learned how to compile and run C++ programs in the terminal.