If Statement
Explore how to use if statements in C++ to make decisions in your code. Learn the syntax and logic behind condition checks, and understand how to execute code blocks only when certain conditions are met. This lesson provides clear examples and helps you grasp the fundamentals of conditional statements in programming.
We'll cover the following...
Introduction
Suppose you can buy a watch if you get at least $20 in an allowance. Otherwise, you cannot. In C++, how can we make a decision based on a condition?
We can use an if statement to demonstrate this kind of behavior.
The if statement instructs a compiler to execute a particular block of code when the condition evaluates to true.
Syntax
The general syntax of an if statement consists of the if keyword followed by the round brackets ( ). These round brackets hold a condition specified by the programmer. Following the if condition is a block of code encapsulated in the curly brackets. This block of code is called the body of the if statement.
π We can use relational and logical operators for comparison in the condition inside the round brackets.
Flowchart
The flowchart given below will explain how the if statement works:
In the above figure:
-
The condition evaluates to
trueorfalse. -
If the condition is true, the compiler executes the statements inside the
ifbody. -
If the condition evaluates to false, the compiler exits the
ifblock without running it.
π In C++, a zero or null value is considered false, and non-zero values are considered true.
Example program when the condition is true
Letβs convert the above example into a C++ program.
Run the code below and see how the if statement works!
Line No. 7: Sets the value of money to 21.
Line No. 9: Checks if the value of money is greater than or equal to 20. If yes, then the condition returns 1, and the code inside the curly brackets will be executed. The value of money is greater than 20; therefore, the condition returns 1.
Line No. 11: It prints You can buy a watch in the output since the condition in Line No. 9 is true.
π Writing the
ifkeyword in the upper case will generate a syntax error.
Example program when the condition is false
Letβs see what happens if the condition evaluates to false.
Press the RUN button and see the output!
Line No. 7: Sets the value of money to 9.
Line No. 9: The value of money is less than 20; therefore, the condition returns 0.
Line No. 11: The condition in Line No. 9 is false; therefore, the code inside the body of the if statement does not execute.
Quiz
What is the output of the following code?
int main() {
float number = 85.3;
if (number < 85.1) {
cout << "Hey! I am less than 85.1" << endl;
}
cout << "number = " << number;
}
Hey! I am less than 85.1
number = 85.3
number = 85.3
0
Generates an error