C++ If ... Else

✅ ساختار پایه

if (شرط) { // اگر شرط درست (true) باشد، این بلاک اجرا می‌شود } else { // اگر شرط غلط (false) باشد، این بلاک اجرا می‌شود }

1️⃣ مثال ساده

#include <iostream> using namespace std; int main() { int number = 10; if (number > 0) { cout << "Positive number" << endl; } else { cout << "Not positive" << endl; } }

🔹 خروجی: Positive number

2️⃣ If بدون Else

int age = 20; if (age >= 18) { cout << "You are an adult." << endl; }

📌 اگر شرط برقرار نباشد، برنامه چیزی چاپ نمی‌کند.

3️⃣ If ... Else If ... Else

برای چندین شرط مختلف:

#include <iostream> using namespace std; int main() { int score = 75; if (score >= 90) { cout << "Grade: A"; } else if (score >= 75) { cout << "Grade: B"; } else if (score >= 50) { cout << "Grade: C"; } else { cout << "Grade: F"; } }

4️⃣ شرط تو در تو (Nested If)

#include <iostream> using namespace std; int main() { int age = 20; bool hasID = true; if (age >= 18) { if (hasID) { cout << "Access granted!" << endl; } else { cout << "ID required!" << endl; } } else { cout << "Too young!" << endl; } }

5️⃣ استفاده از عملگر سه‌تایی (Ternary Operator)

یک شکل کوتاه از if ... else:

#include <iostream> using namespace std; int main() { int x = 5; string result = (x % 2 == 0) ? "Even" : "Odd"; cout << result << endl; // Odd }

6️⃣ نکته: Boolean به عنوان شرط

bool isRaining = true; if (isRaining) { cout << "Take an umbrella!" << endl; } else { cout << "Enjoy the sun!" << endl; }