C++ if statement
In C++ if statement is used to check the truthness of the expression. Condition written inside If statement conconsists of a boolean expression. If the condition written inside if is true then if block gets executed.
Table of content
Syntax :
If statement is having following syntax -
if(boolean_expression) { // statement(s) will execute if the // boolean expression is true }
Example : C++ If Statement
#include <iostream> using namespace std; int main () { // Declaring local variable int num = 5; // check the boolean condition if( num > 4 ) { cout << "num is greater than 4" << endl; } cout << "Given number is : " << num << endl; return 0; }
Output :
Compiled C++ code will produce following output -
num is greater than 4 Given number is : 5
Explanation :
In the above program, In the if condition we are checking the following condition -
if( num > 4 )
If the above condition evaluates to true then the code written inside the if block will be executed. Otherwise code followed by if block will be executed.
Note #1 : Curly braces
Complete if block is written inside the pair of curly braces. If we have single statement inside the if block then we can skip the pair of curly braces -
if( num > 4 ) cout << "num is greater than 4" << endl;