The if-else statement is a fundamental control structure in C++ that helps your program decide which code to run based on conditions. It checks if a condition is true, executes the corresponding code block, otherwise runs an alternative block.
if (condition) { // code runs if condition is true } else { // code runs if condition is false }
true
or false
.condition
is true
, the if
block executes.condition
is false
, the else
block executes (if present).#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; if (age >= 18) { cout << "You are eligible to vote." << endl; } else { cout << "You are not eligible to vote yet." << endl; } return 0; }
- The program asks for your age.
- It checks if your age is 18 or above (age >= 18
).
- If yes, it prints "You are eligible to vote."
- Otherwise, it prints "You are not eligible to vote yet."
else
is optional but allows handling alternate scenarios.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!