if, else if, else

Tests if a condition is TRUE or FALSE.

 

If the test condition equates to boolean TRUE, the code block following the condition parentheses is executed.

 

Syntax:

if(test condition) {

//do this code if TRUE

}

//otherwise condition is FALSE, so continue

 

Optional else if conditions can follow, as well as optional else statements:

 

#include <iostream>
using namespace std ;

int main () {

	int myVar;

	cout << "Please enter your favourite number:" << endl ;
	cin >> myVar ;

	if (myVar < 20) {
		cout << myVar << " is less than 20!" << endl ;
	} else if (myVar < 100) {
		cout << myVar << " is less than 100!" << endl ;
	} else {
		cout << myVar << " is greater than 100!" << endl ;
	}

	return 0;
}

Compile & Run:

Please enter your favourite number:
66
66 is less than 100!

Leave a Reply