a shot of dev knowledge

RELATED TAGS

How to use the if statement in C++

Overview

The if statement in C++ is used to specify a block of code that will be executed if a condition provided is true.

Syntax

if (condition){
  statement
}

The statement or command will execute provided the given condition is true.

Example

Let’s write a code using the if statement:

#include <iostream>
using namespace std;

int main() {
  // creating a condition 
  if (2 > 1) {

    // creating a statement/block of code to be executed
    cout << "2 is greater than 1";
    
  }  
  return 0;
}
Implementing the if statement

Explanation

  • Line 6: We use the if statement. We create a condition, if the number 2 is greater than 1, the block of code or statement in line 9 should be executed.
  • Line 9: we create a statement or block of code to be executed provided that the condition in line 6 is true.

We can also use the if statement to test variables.

Example

#include <iostream>
using namespace std;

int main() {
  // creating variables
  int x = 1;
  int y = 2;

  // creating condition 
  if (x < y) {

    // statement/block of code to be executed 
    cout << "x is less than y";
  }  
  return 0;
}
Using the if statement to test variables

Explanation

  • Line 6 and 7: We create integer variables x and y.

  • Line 10: We compare the values of x and y. If y is greater than x then the condition is true.

  • Line 13: We create a statement or block of code to execute provided the condition given in line 10 is true.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring