Program to Compare & Print The Largest of Two Numbers

A very simple program to compare and print the largest of two given numbers.

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 operator
  • a!=b : The Not Equal to operator
  • a > b : The Greater Than operator
  • a < b : The Less Than operator
  • a <= b : The Greater Than or Equal To operator
  • a <= 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;
}
Output
------------------------------------------------------------
Program to compare two numbers and print the biggest number
------------------------------------------------------------
Enter the first number: 10
Enter the second number: 33
The biggest of both number is : 33.000000
Output
-----------------------------------------------------------
Program to compare two numbers and print the biggest number
-----------------------------------------------------------
Enter the first number: 15
Enter the second number: 15
Both the numbers are equal

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/elseand have achieved the same result.