In this example, we’ll learn how to compare two numbers using if else if statements.
We use the following operators for comparison in C #. In this example we will perform a simple comparison process.
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream> #include<stdlib.h> #include <cmath> using namespace std; int main() { int num1,num2; cout<<"Number 1: "; cin>>num1; cout<<"Number 2: "; cin>>num2; if (num1 > num2) { cout<<"Number1 is greater than Number2"; } else if (num1 < num2) { cout<<"Number1 is less than Number2"; } else { cout<<"Number1 is equal to Number2"; } } |
This code is written in C++ and it compares two numbers entered by the user and prints the result of the comparison.
- The code includes the standard input/output library and the cmath library.
- In the main function, two variables “num1” and “num2” are declared to store the input numbers.
- The program prompts the user to enter two numbers, “num1” and “num2”. The input is stored in the respective variables using the “cin” statement.
- An “if-else” statement is used to compare “num1” and “num2”. If “num1” is greater than “num2”, the program prints “Number1 is greater than Number2”.
- If “num1” is less than “num2”, the program prints “Number1 is less than Number2”.
- If “num1” is equal to “num2”, the program prints “Number1 is equal to Number2”.
- The program ends with the return statement.