C++ If Statements

The C++ If statement is a conditional statement. The program executes a block of code only if condition is satisfied or true. This changes the flow of C++ program. The program executes only required blocks and ignore others.

There are two ways to write an if statement.

Advertisements
  • With curly braces
  • Write without curly braces( { } ).

If statement with curly braces

The if statement with curly braces are the default way of writing the if block.

if(expression)
{
    statement 1;
    statement 2;
    statement n;
}

The above block has if statement with an expression. When the expression evaluates to true, the block of statements is executed. This form of if statement is suitable when the program needs to execute more than one statement.

The expression is a logical expression that always result in a Boolean result – true or false.

If statement without a curly brace

Sometimes, you can write if statement without curly braces when only one statement follows the if condition.

Advertisements
if(expression)
  statement1;

There is no other statements to execute except statement1.

Nesting If statements

Nesting if statement means that an if statement contains another if statement within the block. The inner if block is executed first.

Consider the following example,

if (expression)
{
       // there are statements and another if block
    statement1;
     // nested if block
    if(expression)
    {
             statement2;
            statement3;
   }
}

Example Program: if ststatement

// Example program If statements
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    //variable declaration
    
    int top;
    
    //variable initialization
    
    top = 100;
    
    //if block without braces
    
    if(top == 100)
        cout << "Top is equal to 100:" << endl;
        
    //if block with braces
    
    cout << endl;
    
    if(top == 100)
    {
           top = top + 100;
           cout << "Now Top is" << " " << top << endl;
    }
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

Top is equal to 100:
Now Top is 200


Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version