C++ If Statements

Advertisements
Advertisements

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.

  • 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.

Advertisements

If statement without a curly brace

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

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

Bestseller

Object-Oriented Programming with C++ – 8th Edition

Object-oriented programming with C++, 8th edition is here with some valuable updates. The new edition helps students to assess their learning by answering questions based on learning outcomes. Objective-type questions and dry-run questions are introduced to make students exam ready. A new appendix on interview questions is for those seeking to join the industry. The book is designed for students studying at the undergraduate level. It provides all-inclusive concepts and programs on object-oriented programming with C++ as an implementation language.

  • 150+ multi-choice questions
  • 100+ dry-run exercises
  • 90+ interview questions
  • Two new projects and more

Advertisements
Advertisements
Advertisements