الـ
else if هي عبارة شرطية تسمح لك بتنفيذ مجموعات مختلفة من التعليمات البرمجية بناءً على سلسلة من الشروط. بناء الجملة العام لـ else if هو كالتالي:if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// code to execute if condition1 and condition2 are false and condition3 is true
} ...
else {
// code to execute if none of the conditions are true
}
الـ else if يتم المرور عليها وتنفيذها بالترتيب، حيث أن أول جملة else if تكون صحيحة true يتم تنفيذها. وإذا لم تكن أي واحدة من جمل else if ذات قيمة صحيحة trueيصل البرنامج إلى جملة else سيتم تنفيذها.
هذا مثال على جملة else if الشرطيّة:
#include <iostream>
using namespace std;
int main()
{
int mark = 0;
cin >> mark;
if (mark >= 90)
cout << "A" << endl;
else if (mark >= 80)
cout << "B" << endl;
else if (mark >= 70)
cout << "C" << endl;
else if (mark >= 60)
cout << "D" << endl;
else
cout << "F" << endl;
return 0;
}
مثال إضافي:
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
cout << "Enter 2 numbers" << endl;
cin >> x >> y;
if (x < y)
cout << "y is greater than x" << endl;
else if (x > y)
cout << "x is greater than y" << endl;
else
cout << "Both are equal" << endl;
cout << "C++ is great language!" << endl;
return 0;
}
يُمكن إستخدام جُمَل متداخلة من else if الشرطية لإنشاء جُمَل شرطية أكثر تعقيدًا.
الـ else if تُعَد أداة قوية للتحكم في تدفق البرنامج. باستخدام جملة else if ، يمكنك كتابة كود أكثر تعقيدًا وفعالية.
فيما يلي بعض القواعد العامة لاستخدام جملة else if الشرطيّة:
- الـ
else ifيجب استخدامها بالتزامن مع جملةif. - الـ
else ifيتم المرور عليها وتنفيذها بالترتيب، حيث أن أول جملةelse ifتكون صحيحةtrueيتم تنفيذها - إذا لم تكن أي من جُمَل
else ifذات قيمة صحيحةtrueيصل البرنامج إلى جملةelseسيتم تنفيذها. - يمكنك استخدام جمل شرطية متداخلة داخل جملة
else ifالشرطية لإنشاء جُمَل شرطية أكثر تعقيدًا.
من خلال فهم كيفية إستخدام جملة else if ، تستطيع كتابة كود أكثر كفاءة وفاعليّة.