CPP Tutorial



C++ IF ELSE


If-Else Statement in C++

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.

📐 Syntax

if (condition) {
    // code runs if condition is true
} else {
    // code runs if condition is false
}
  

🔎 How It Works

  • condition is a logical expression that evaluates to true or false.
  • If condition is true, the if block executes.
  • If condition is false, the else block executes (if present).

💡 Example

#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;
}
  

⚙️ Explanation

- 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."

Summary

  • if-else controls flow by checking conditions.
  • Useful for decision-making in your programs.
  • else is optional but allows handling alternate scenarios.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review