Forum

Learn C++ If Then E…
 
Notifications
Clear all

Learn C++ If Then Else statements

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

In C++, if-else statements are the backbone of decision-making logic—they let your program choose between different paths based on conditions 🧠🔧


🧪 Basic if Statement

int x = 10;

if (x > 5) {
    std::cout << "x is greater than 5";
}
  • If the condition inside () is true, the code inside {} runs.
  • If false, it’s skipped.

🔄 Adding else and else if

int x = 3;

if (x > 5) {
    std::cout << "x is greater than 5";
} else if (x == 5) {
    std::cout << "x is equal to 5";
} else {
    std::cout << "x is less than 5";
}
  • else if lets you check another condition.
  • else runs if none of the previous conditions are true.

🧠 Real-Life Example

int score = 85;

if (score >= 90) {
    std::cout << "Grade: A";
} else if (score >= 75) {
    std::cout << "Grade: B";
} else if (score >= 65) {
    std::cout << "Grade: C";
} else {
    std::cout << "Grade: D";
}

This mimics how you’d assign grades based on score ranges.


❗ Syntax Tips

  • Always use lowercase if, else, and else if.
  • Curly braces {} are optional for single-line blocks, but recommended for clarity.
  • Conditions must evaluate to a Boolean (true or false).

 


   
Quote
Share: