Cpp - Block If Statements

Introduction

Block statements can be used anywhere that a single statement could be placed.

The if and if-else conditionals often are followed by block statements:

if (my_int == 0) 
{ 
    std::cout << "No more my_int!\n"; 
    score += 5000; 
} 

Any statement can be used with an if conditional, even another if or else statement.

Demo

#include <iostream> 
   //from   w  ww .j  a  va 2  s  .co  m
int main() { 
    int grade; 
    std::cout << "Enter a grade (1-100): "; 
    std::cin >> grade; 
 
    if (grade >= 70) 
    { 
           if (grade >= 90) 
           { 
               std::cout << "\nYou got an A. Great job!\n"; 
               return 0; 
           } 
           if (grade >= 80) 
           { 
               std::cout << "\nYou got a B. Good work!\n"; 
               return 0; 
           } 
           std::cout << "\nYou got a C. Perfectly adequate!\n"; 
    } 
    else 
           std::cout << "\nYou got an F. I failed as a parent!\n"; 
  
    return 0; 
}

Result

Related Topic