Cpp - Statement if Statement


The following if statement displays a message only when an integer called my_int meets a specific condition:

if (my_int == 0) 
    std::cout << "No more my_int!\n"; 

This code displays the words "No more my_int!" if the my_int variable equals 0. The expression within parentheses is the condition.

If the expression is true, the statement following the if is executed. If it is false, the statement is skipped.

If the my_int variable equals 25 when this code runs, nothing is displayed.

The expression must be true for the conditional code to be executed. Because bool variables can be true or false, one can be used as the condition:

bool run = true; 
if (run) 
    std::cout << "Running\n"; 

This code displays the text "Running" only when the bool variable run equals true.

else Clause

The else keyword identifies the statement to execute when the condition is false:

if (my_int == 0) 
    std::cout << "zero!\n"; 
    std::cout << "not zero!\n"; 

The following code demonstrates the use of conditional statements.


#include <iostream> 
   //from w  w  w .  ja v  a2  s  .  com
int main() 
    int grade; 
    std::cout << "Enter a grade (1-100): "; 
    std::cin >> grade; 
    if (grade >= 70) 
           std::cout << "\nYou passed. Hooray!\n"; 
           std::cout << "\nYou failed. Sigh.\n"; 
    return 0; 


Related Topics