If and Else

A statement can be executed optionally based on variable value. You can use if with condition to do that. Here is the syntax.

  • if(condition)statement;
  • if(condition){statement1;statement2; ...}
First syntax is used if there is only one statement. If there are two or more statements, you need to write those statements between two brackets.
#include <iostream>

using namespace std;

int main(){
    int numr;
	
    cout << "Number : ";
    cin >> numr;
	
    if(numr % 2 == 0){
       cout << "Your number is even number";
       cout << endl;
    }

    cout << "finished";
    return 0;
}
Example :
2
Your number is even number

That code use to print output if variable value is an even number. If the variable have other value, there is nothing executed. If you want to print or do something when condition is false, then you need else.

#include <iostream>

using namespace std;

int main(){
    int numr;
	
    cout << "Number : ";
    cin >> numr;
	
    if(numr % 2 == 0)
       cout << "Your number is even number" << endl;
    else
       cout << "That's odd number" << endl;

    cout << "finished";
    return 0;
}
Example :
3
Your number is odd number

Relational Operator

Above, we use "==" as a relational operator inside parentheses that's used as if condition. There are other relational operators that you can use to compare 2 value.

  • ==
  • !=
  • <
  • >
  • <=
  • >=