Introduction
In this lab, we will write a C++ program that will take three numbers as input from the user and find the maximum among them using if/else statements.
In this lab, we will write a C++ program that will take three numbers as input from the user and find the maximum among them using if/else statements.
Create a new file in the ~/project
directory named main.cpp
.
touch ~/project/main.cpp
We need to include the iostream
library to allow input and output.
#include <iostream>
We will write a function that will take three numbers as input and return the maximum number among them. We will use if/else statements to compare the three numbers and find out the maximum number.
int findMax(int num1, int num2, int num3) {
int max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
return max;
}
In the main function, we will prompt the user to enter three numbers and then call the findMax
function to find the maximum number.
int main() {
int num1, num2, num3;
std::cout << "Enter the three numbers: ";
std::cin >> num1 >> num2 >> num3;
std::cout << "The maximum number is: " << findMax(num1, num2, num3) << std::endl;
return 0;
}
To compile the program, open the terminal and navigate to the ~/project
directory. Then, run the following command:
g++ main.cpp -o main && ./main
You will see the following output:
Enter the three numbers: 10 20 30
The maximum number is: 30
Here is the full code for the main.cpp
file:
#include <iostream>
int findMax(int num1, int num2, int num3) {
int max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
return max;
}
int main() {
int num1, num2, num3;
std::cout << "Enter the three numbers: ";
std::cin >> num1 >> num2 >> num3;
std::cout << "The maximum number is: " << findMax(num1, num2, num3) << std::endl;
return 0;
}
In this lab, we learned how to create a C++ program that can find the maximum among three given numbers using if/else statements. We also learned how to write a function to find the maximum number and how to use input/output statements to prompt the user to enter the numbers and display the result.