دستور if else در زبان C++
دستور if else در زبان C++ مشابه دستور if می باشد با این تفاوت که در صورت درست نبودن شرط بررسی شده در if کدهای موجود در بلوک else اجرا می شوند.
نحوه نوشتن دستور شرطی if else
در زیر Syntax یک دستور شرطی if else را مشاهده می کنید:
1 2 3 4 5 | if(boolean_expression) { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } |
اگر عبارت بولی true باشد، کدهای موجود در بلوک if اجرا می شوند و در غیر این صورت کدهای موجود در بلوک else اجرا خواهند شد.
دیاگرام دستور if else
مثال
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; } |
زمانی که کد بالا کامپایل و اجرا شود، نتیجه زیر را تولید خواهد کرد:
1 2 | a is not less than 20; value of a is : 100 |
دستور شرطی if else if else در C++
از این دستور شرطی در مواقعی استفاده می شود که قصد ارزیابی چند شرط مختلف را داریم. زمانی که از دستور if else if else استفاده می کنید، باید به نکات زیر توجه داشته باشید:
- یک دستور if می تواند صفر یا یک بخش else داشته باشد و بخش else همیشه باید بعد از else if ها نوشته شود.
- یک دستور if می تواند صفر یا چند بخش else if داشته باشد و بخش else if همیشه باید قبل از بخش else نوشته شود.
- زمانی یکی از else if ها درست باشد و اجرا شود، سایر else if ها و else ارزیابی نمی شوند.
نحوه نوشتن دستور شرطی if else if else
در زیر Syntax یک دستور شرطی if else if else را مشاهده می کنید:
1 2 3 4 5 6 7 8 9 | if(boolean_expression 1) { // Executes when the boolean expression 1 is true } else if( boolean_expression 2) { // Executes when the boolean expression 2 is true } else if( boolean_expression 3) { // Executes when the boolean expression 3 is true } else { // executes when the none of the above condition is true. } |
مثال
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a == 10 ) { // if condition is true then print the following cout << "Value of a is 10" << endl; } else if( a == 20 ) { // if else if condition is true cout << "Value of a is 20" << endl; } else if( a == 30 ) { // if else if condition is true cout << "Value of a is 30" << endl; } else { // if none of the conditions is true cout << "Value of a is not matching" << endl; } cout << "Exact value of a is : " << a << endl; return 0; } |
زمانی که کد بالا کامپایل و اجرا شود، نتیجه زیر را تولید خواهد کرد:
1 2 | None of the values is matching Exact value of a is: 100 |
هیچ نظری ثبت نشده است