if Statement in C++
In our previous lessons, we wrote programs that ran sequentially—one line after another. But to build smart software, your program needs to make choices. This is where the if statement comes in, allowing your code to be “selective” rather than just “sequential”.
Simple Definitions
Topic |
Simple Definition |
| if Statement | A C++ keyword used for decision-making; it checks a condition before running a piece of code. |
| Condition | A requirement inside parentheses that the computer evaluates as either True or False. |
| Relational Operator | Symbols (like > or ==) used to compare two values to create a condition. |
How the if Statement “Thinks”
The if statement acts as a gatekeeper. When the program reaches an if line, it looks at the condition inside the parentheses.
- If the condition is True, the program enters the gate and runs the code below it.
- If the condition is False, the program skips that code entirely and moves to the next part of the script.
Relatable Example: Imagine a bank account. You can set a rule: If the currentBalance is less than (<) the limit, then send a “Low Balance” alert to the customer. If the balance is above the limit, the alert code is skipped.
General Syntax:
if (condition)
{
// This code runs only if the condition is True
}
If the condition evaluates to True, the code inside the block executes. If it is False, the compiler skips that entire section and moves to the next part of the program.
-
Why Braces { } Matter
If you only have one line of code after an if statement, braces are optional. However, if you want multiple lines to be controlled by the if statement, you must use braces.
Without braces, only the very first line after the if is protected; all subsequent lines will run regardless of whether the condition was true or false.
Examples:
Pass or Fail
# include <iostream>
using namespace std;
int main(){
int marks=0;
cout<<"Enter your obtained marks: ";
cin>> marks;
if(marks>=50){
cout<<"Hurray! You are pass!!🎉🎉🎉";
}
if(marks<50){
cout<<"Oops! You are fail!😭😭😭";
}
return 0;
}
Try It Yourself Challenges:
Mastering the if statement is your first step into “intelligent” coding. Practice by creating conditions for your own real-life scenarios!
- Expression Check: Look at this expression: (10 <= 5). Will this result in True or False?
- No Condition: What happens if we leave the condition section blank (i.e., if(){//statements})?
- The “Not Equal” Test: If you write if (5 != 4), will the code inside the braces run?
- The Braces Test: Write a small program with an if statement but without braces. Add two cout lines. Change the condition to False. Which line still prints?
- Think about a daily routine, like setting an alarm. How would you write that as an “if” statement? (e.g., “If time is 7:00 AM, then ring bell”).
- Write a program that checks if a user is old enough to vote (age >= 18).
