While writing code in any language, you will have to control the flow of your program - you will want to execute a certain piece of code if a condition is satisfied, and some different code in case it is not.
If
statements are used to make these decisions in code. The keyword if
tells C++ to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as boolean
conditions and they may only be true or false.
When the condition evaluates to true, the program executes the statement inside the curly braces. When the boolean condition evaluates to false, the statement inside the curly braces will not execute. But what will happen then?
Normally nothing would happen. But with an else
statement, an alternate block of code can be executed.
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
When writing if
statements, we usually compare two values using one or more comparison operators:
Operator | Name | Examples |
---|---|---|
== | Equal | x == 5, x == y |
!= | Not equal | x != 3, x != y |
> | Greater than | x > 5, x > y |
< | Less than | x < 8, x < y |
>= | Greater than or equal to | x >= 4, x >= y |
<= | Less than or equal to | x <= 3, x <= y |
We can also combine multiple conditional statements with the help of logical operators:
Operator | Name | Description | Examples |
---|---|---|---|
&& | And | Returns true if both statements are true | x < 5 && x < 10 |
|| | Or | Returns true if one of the statements is true | x < 5 || x < 10 |
! | Not | Reverses the result, returns false if the result is true | !(x < 5 && x < 10) |
Let's go through some examples together to better understand how if-else statements work:
# Declare 2 variables and initialize them
int a = 2;
int b = 3;
// Prints "a equals 2"
if(a == 2) {
cout << "a equals 2" << endl;
}
// Prints nothing
if(b != 3) {
cout << "b is not equal to 3" << endl;
}
// Prints "b equals 3"
if(a == 2 && b - a == 1) {
cout << "b is equal to 3" << endl;
}
// Prints "a = 2, b = 3"
if(a != 2 || b != 3) {
cout << "Inside if" << endl;
}
else {
cout << "a = 2, b = 3" << endl;
}
// Prints "a + b equals 5"
if(!(a + b == 5)) {
cout << "a + b is not equal to 5" << endl;
}
else {
cout << "a + b equals 5" << endl;
}
// Prints "a is even, b is odd"
if(a % 2 == 0) {
if(b % 2 == 0) {
cout << "Both a and b are even" << endl;
}
else {
cout << "a is even, b is odd" << endl;
}
}
else {
if(b % 2 == 0) {
cout << "a is odd, b is even" << endl;
}
else {
cout << "Both a and b are odd" << endl;
}
}
Assignment
Follow the Coding Tutorial and let's write some if-else statements.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of if
statements in C++. These statements are fundamental in controlling the flow of a program based on certain conditions. Understanding how to use if
statements effectively is crucial for making decisions in your code, which is a common requirement in many programming scenarios.
The if
statement allows you to execute a block of code only if a specified condition is true. If the condition is false, you can use an else
statement to execute an alternative block of code. This is essential for making decisions in your programs.
Here is a simple example:
int x = 10;
if (x > 5) {
// This block will execute because x is greater than 5
cout << "x is greater than 5" << endl;
} else {
// This block will not execute
cout << "x is not greater than 5" << endl;
}
Let's delve deeper into the key concepts and techniques involved in using if
statements:
==
(equal), !=
(not equal), >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to).&&
(and), ||
(or), and !
(not).Here is an example that combines comparison and logical operators:
int a = 3;
int b = 5;
if (a < b && b < 10) {
cout << "Both conditions are true" << endl;
} else {
cout << "At least one condition is false" << endl;
}
Let's look at some practical examples to understand how if
statements can be used in various contexts:
int age = 20;
if (age >= 18) {
cout << "You are an adult." << endl;
} else {
cout << "You are a minor." << endl;
}
int score = 85;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
When using if
statements, it's important to avoid common mistakes and follow best practices:
=
instead of comparison operator ==
.if
and else
blocks, even for single-line statements.Once you are comfortable with basic if
statements, you can explore more advanced techniques such as nested if
statements and the ternary operator:
int num = 10;
if (num > 0) {
if (num % 2 == 0) {
cout << "Positive even number" << endl;
} else {
cout << "Positive odd number" << endl;
}
} else {
cout << "Non-positive number" << endl;
}
// Ternary operator
string result = (num > 0) ? "Positive" : "Non-positive";
cout << result << endl;
Here is a well-commented code snippet demonstrating the correct use of if
statements:
#include <iostream>
using namespace std;
int main() {
int a = 2;
int b = 3;
// Check if a equals 2
if (a == 2) {
cout << "a equals 2" << endl;
}
// Check if b is not equal to 3
if (b != 3) {
cout << "b is not equal to 3" << endl;
}
// Check if a equals 2 and b - a equals 1
if (a == 2 && b - a == 1) {
cout << "b is equal to 3" << endl;
}
// Check if a is not equal to 2 or b is not equal to 3
if (a != 2 || b != 3) {
cout << "Inside if" << endl;
} else {
cout << "a = 2, b = 3" << endl;
}
// Check if a + b is not equal to 5
if (!(a + b == 5)) {
cout << "a + b is not equal to 5" << endl;
} else {
cout << "a + b equals 5" << endl;
}
// Check if a is even and b is odd
if (a % 2 == 0) {
if (b % 2 == 0) {
cout << "Both a and b are even" << endl;
} else {
cout << "a is even, b is odd" << endl;
}
} else {
if (b % 2 == 0) {
cout << "a is odd, b is even" << endl;
} else {
cout << "Both a and b are odd" << endl;
}
}
return 0;
}
Debugging and testing are crucial for ensuring your if
statements work as expected:
Example of a simple test case:
#include <iostream>
using namespace std;
void testIfStatements() {
int a = 2;
int b = 3;
if (a == 2) {
cout << "Test 1 Passed" << endl;
} else {
cout << "Test 1 Failed" << endl;
}
if (b != 3) {
cout << "Test 2 Failed" << endl;
} else {
cout << "Test 2 Passed" << endl;
}
}
int main() {
testIfStatements();
return 0;
}
Here are some strategies for approaching problems related to if
statements:
if
statements with different types of conditions.In this lesson, we covered the basics of if
statements in C++, including comparison and logical operators, common pitfalls, best practices, and advanced techniques. Mastering these concepts is essential for making decisions in your code and writing efficient, maintainable programs. Keep practicing and exploring further applications to solidify your understanding.
For further reading and practice problems, check out the following resources: