C++ PROGRAMMING ( USE OF IF, ELSE,ELIF)

 

C++ if, if...else and Nested if...else

In computer programming, we use the if...else statement to run one block of code under certain conditions and another block of code under different conditions.

For example, assigning grades (A, B, C) based on marks obtained by a student.

  • if the percentage is above 90, assign grade A
  • if the percentage is above 75, assign grade B
  • if the percentage is above 65, assign grade C

There are three forms of if...else statements in C++.

  1. if statement
  2. if...else statement
  3. if...else if...else statement

C++ if Statement

The syntax of the if statement is:

if (condition) {
  // body of if statement
}

The if statement evaluates the condition inside the parentheses ( ).

  • If the condition evaluates to true, the code inside the body of if is executed.
  • If the condition evaluates to false, the code inside the body of if is skipped.

Note: The code inside { } is the body of the if statement.

Working of if Statement
How if Statement Works

Example 1: C++ if Statement

// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped

#include <iostream>
using namespace std;

int main() {

  int number;

  cout << "Enter an integer: ";
  cin >> number;

  // checks if the number is positive
  if (number > 0) {
    cout << "You entered a positive integer: " << number << endl;
  }

  cout << "This statement is always executed.";

  return 0;
}

Output 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

When the user enters 5, the condition number > 0 is evaluated to true and the statement inside the body of if is executed.

Output 2

Enter a number: -5
This statement is always executed.

When the user enters -5, the condition number > 0 is evaluated to false and the statement inside the body of if is not executed.


C++ if...else

The if statement can have an optional else clause. Its syntax is:

if (condition) {
  // block of code if condition is true
}
else {
  // block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.

Working of if...else Statement
How if...else Statement Works



Comments

Popular posts from this blog