Saturday, April 19, 2025

C++ Comparing Numbers

This will be easy one. Using If statements we will compare values in variables to see if they are equal or not using multiple if checks:

First we will create two variables that will hold integers:

int a = 43;
int b = 23;

Then If check to see if a and b are equal using double equal symbols:

if (a == b) {
        cout << "Numbers are Same" << endl;
    }

To check if they are not equal the exclamation mark and equal symbol are used together (no space between them):

if (a != b) {
        cout << "Numbers are NOT Same" << endl;
    }

This is full source: 

#include <iostream>

using namespace std;

int main() {

    int a = 43;
    int b = 23;

    if (a == b) {
        cout << "Numbers are Same" << endl;
    }
    if (a != b) {
        cout << "Numbers are NOT Same" << endl;
    }
	
	return 0;

}

Result:

Numbers are NOT Same

Process returned 0 (0x0)   execution time : 0.066 s
Press any key to continue.

Comparing Values taken from Keyboard

Run this code and then we will explain: 

#include <iostream>

using namespace std;

int main() {

    int a;
    int b;

    cout << "Please enter number in a: " << endl;
    cin >> a;
    cout << "Please enter number in b: " << endl;
    cin >> b;

    if (a == b) {
        cout << "Numbers are Same" << endl;
    }
    if (a != b) {
        cout << "Numbers are NOT Same" << endl;
    }
	
	return 0;

}

Result using numbers 10 and 255 as input:

Please enter number in a:
10
Please enter number in b:
255
Numbers are NOT Same

Process returned 0 (0x0)   execution time : 8.171 s
Press any key to continue.

First we are creating two variables that will be populated with keyboard input:

int a;
int b;

Then we grab first number using cin:

cout << "Please enter number in a: " << endl;
cin >> a;

Time to get second number:

cout << "Please enter number in b: " << endl;
cin >> b;

If checks to compare values in a and b variable:

if (a == b) {
        cout << "Numbers are Same" << endl;
    }
if (a != b) {
        cout << "Numbers are NOT Same" << endl;
    }

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...