Apart from arithmetic operations computers are good at logical operations as well. In this lesson we will write a program to accept two numbers from a user then compare and print the largest of both.
You must be aware of mathematical operators such as (+, -, /, *). Similarly there are comparison or logical operators. These operators are used for comparison purposes. A list of the few operators are given below:
a==b
: The Equal to operatora!=b
: The Not Equal to operatora > b
: The Greater Than operatora < b
: The Less Than operatora <= b
: The Greater Than or Equal To operatora <= b
: The Less Than or Equal to operator
Purpose
Write a program to accept two numbers from user input then compare and print the biggest of the two numbers.
This is a very basic C++ program. In this code example we'll use the comparison operators discussed above to compare the number from the user's input.
#include <stdio.h>
#include <conio.h>
using namespace std;
int main()
{
float num1, num2, biggest;
printf("------------------------------------------------\n");
printf("Program to compare two numbers and print the biggest number \n");
printf("------------------------------------------------\n");
printf("Enter the first number: ");
scanf("%f", &num1);
printf("Enter the second number: ");
scanf("%f", &num2);
if (num1 > num2)
{
biggest = num1;
}
else
{
biggest = num2;
}
if (num1 == num2)
{
printf("Both the numbers are equal \n");
}
else
{
printf("The biggest of both number is : %f", biggest);
}
getch();
return 0;
}
Explanation
In this example code, we accept a user input using scanf()
function, you may use cout
cin
as well but remember to include the iostream
header file. We then compare both the numbers and whichever is the biggest we store it in a variable named biggest
. We then just check whether the numbers are equal or not, incase they are we then print the message saying The numbers are equal otherwise we print the biggest number. We could also have used a simple ternary operator instead of if/else
and have achieved the same result.