if else Statement in C++

if else statement is slection statement that execute one block of statemments in case of true condition, and execute other block of statements in case of false condition. if else satement ever display message or perform some define operation even given condition is false.

Syntax

Syntax of if else statement with single and multiple statements is as.

if (condition) statement; else statement;

Here condition is relational expression that always return either True or False.

if (condition) {

statements;

} else {

statements;

}

Examples

if else statement with single Instructions

Here is the code example that uses single Instructions with if else statement. So that there is no need of curly parentheses.

 

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	int a = 1;
	
	if(a >= 0) 
	cout<<"Positive Number";
        else
        cout<<"Negative Number";
	
	return 0;
}

if else statement with multiple Instructions

Here is another code example that uses multiple Instructions with if else statement. So that these statements are enclosed in curly parentheses (statement block).

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	int a = 1;
	
	if(a >= 0) {
	cout<<"Positive";
	cout<<"Number";
	} else {
	cout<<"Negative";
	cout<<"Number";
        }
	return 0;
}

It is best practice to use if else statement instead of if staement.

Comments
Login to TRACK of Comments.