Comparing two Numbers in C++

0
304
Control structures in C++
A Simple Calculator in C++

Here we are going to look at an example which is able of comparing two numbers in C++. In future we might need a simple code for comparing two integers to be included in our larger codes. Here we will use the “if” conditional structure, and relational operators .So look at this example for comparing two numbersin C++:

  1. //Comparing two numbers
  2. //Using if statements, relational operators
  3. #include <iostream>
  4. using namespace std;
  5. int main()
  6. {
  7.     int num1;
  8.     int num2;
  9.  
  10.     cout << “Enter two integers, and I will tell youn”
  11.     << “the relationships they satisfy: “;
  12.     cin >> num1 >> num2;   // get two integers
  13.  
  14.     //comparing two numbers starts here
  15.     if ( num1 == num2 )
  16.         cout << num1 << ” is equal to “ << num2 << endl;
  17.  
  18.     if ( num1 != num2 )
  19.         cout << num1 << ” is not equal to “ << num2 << endl;
  20.  
  21.     if ( num1 < num2 )
  22.         cout << num1 << ” is less than “ << num2 << endl;
  23.  
  24.     if ( num1 > num2 )
  25.         cout << num1 << ” is greater than “ << num2 << endl;
  26.  
  27.     if ( num1 <= num2 )
  28.         cout << num1 << ” is less than or equal to “<< num2 << endl;
  29.  
  30.     if ( num1 >= num2 )
  31.         cout << num1 << ” is greater than or equal to “<< num2 << endl;
  32.  
  33.     return 0;
  34. }

Let’s explain the code now. first of all we took two variables of datatype “int”, then we asked the user to enter the two integers, then we started the code for comparing two numbers, as we need comparing two numbers so first of all we used “if” structure for “equal”, then for “not equal”, then for “less than”, then “greater than”, then “less than or equal to”, and at the end for “greater than or equal to”. Now while executing the program the condition or conditions that are true will be executed and we will get our answer after comparison. So comparing two numbers in C++ is not so difficult.

 

Control structures in C++
A Simple Calculator in C++

Leave a Reply