C # if, if ... else, if ... else if и Nested if Statement (с примери)

В тази статия ще научим как да използваме оператора if, if … else, if … else if в C # за контрол на потока на изпълнението на нашата програма.

Тестването на условие е неизбежно при програмирането. Често ще се сблъскваме със ситуации, в които трябва да тестваме условия (независимо дали е trueили false), за да контролираме потока на програмата. Тези условия могат да бъдат повлияни от въведеното от потребителя, фактора на времето, текущата среда, в която се изпълнява програмата и т.н.

В тази статия ще се научим да тестваме условия, като използваме оператора if в C #.

C # if (ако-тогава) Изявление

Операторът C # if-then ще изпълни блок код, ако даденото условие е вярно. Синтаксисът на оператора if-then в C # е:

 if (boolean-expression) (// изрази се изпълняват, ако boolean-expression е true) 
  • Булевият израз ще върне true или false.
  • Ако булевият израз се върне true, изразите вътре в тялото на if (вътре (… )) ще бъдат изпълнени.
  • Ако булевият израз се върне false, изразите в тялото на if ще бъдат игнорирани.

Например,

 ако (число <5) (число + = 5;) 

В този пример, изявлението

 число + = 5;

ще се изпълни само ако стойността на числото е по-малка от 5.

Помните ли оператора + =?

Как ако операторът работи?

Пример 1: Изявление C # if

 using System; namespace Conditional ( class IfStatement ( public static void Main(string() args) ( int number = 2; if (number < 5) ( Console.WriteLine("(0) is less than 5", number); ) Console.WriteLine("This statement is always executed."); ) ) ) 

Когато стартираме програмата, изходът ще бъде:

 2 е по-малко от 5 Този оператор винаги се изпълнява.

Стойността на числото се инициализира на 2. Така че изразът number < 5се оценява на true. Следователно кодът в блока if се изпълнява. Кодът след оператора if винаги ще се изпълнява, независимо от израза.

Сега променете стойността на числото на нещо по-голямо от 5, да речем 10. Когато стартираме програмата, изходът ще бъде:

 Този оператор винаги се изпълнява.

Изразът number < 5ще се върне false, следователно кодът вътре, ако блокът не се изпълни.

C # if … else (if-then-else) Изявление

Операторът if в C # може да има незадължителен оператор else. Блокът на кода вътре в инструкцията else ще бъде изпълнен, ако изразът е оценен на false.

Синтаксисът на оператора if … else в C # е:

 if (boolean-expression) (// оператори, изпълнени, ако boolean-expression е true) else (// оператори, изпълнени, ако boolean-expression е false) 

Например,

 ако (число <5) (число + = 5;) друго (число - = 5;) 

В този пример, изявлението

 число + = 5;

ще се изпълни само ако стойността на числото е по-малка от 5.

Изявлението

 число - = 5;

ще се изпълни, ако стойността на числото е по-голяма или равна на 5.

Как ако … друго изявление работи?

Пример 2: C # if … else Изявление

 using System; namespace Conditional ( class IfElseStatement ( public static void Main(string() args) ( int number = 12; if (number < 5) ( Console.WriteLine("(0) is less than 5", number); ) else ( Console.WriteLine("(0) is greater than or equal to 5", number); ) Console.WriteLine("This statement is always executed."); ) ) ) 

Когато стартираме програмата, изходът ще бъде:

 12 е по-голямо или равно на 5 Този оператор винаги се изпълнява.

Here, the value of number is initialized to 12. So the expression number < 5 is evaluated to false. Hence, the code inside the else block are executed. The code after the if… else statement will always be executed irrespective to the expression.

Now, change the value of number to something less than 5, say 2. When we run the program the output will be:

 2 is less than 5 This statement is always executed.

The expression number < 5 will return true, hence the code inside if block will be executed.

Ternary operator in C# provides a shortcut for C# if… else statement.

C# if… else if (if-then-else if) Statement

When we have only one condition to test, if-then and if-then-else statement works fine. But what if we have a multiple condition to test and execute one of the many block of code.

For such case, we can use if… else if statement in C#. The syntax for if… else if statement is:

 if (boolean-expression-1) ( // statements executed if boolean-expression-1 is true ) else if (boolean-expression-2) ( // statements executed if boolean-expression-2 is true ) else if (boolean-expression-3) ( // statements executed if boolean-expression-3 is true )… else ( // statements executed if all above expressions are false ) 

The if… else if statement is executed from the top to bottom. As soon as a test expression is true, the code inside of that if ( or else if ) block is executed. Then the control jumps out of the if… else if block.

If none of the expression is true, the code inside the else block is executed.

Alternatively, we can use switch statement in such condition.

Example 3: C# if… else if Statement

 using System; namespace Conditional ( class IfElseIfStatement ( public static void Main(string() args) ( int number = 12; if (number 5) ( Console.WriteLine("(0) is greater than 5", number); ) else ( Console.WriteLine("(0) is equal to 5"); ) ) ) ) 

When we run the program, the output will be:

 12 is greater than 5

The value of number is initialized to 12. The first test expression number < 5 is false, so the control will move to the else if block. The test expression number> 5 is true hence the block of code inside else if will be executed.

Similarly, we can change the value of number to alter the flow of execution.

Nested if… else Statement

An if… else statement can exist within another if… else statement. Such statements are called nested if… else statement.

The general structure of nested if… else statement is:

 if (boolean-expression) (if (nested-expression-1) (// код за изпълнение) else (// код за изпълнение)) else (if (вложен израз-2) (// код за изпълнение ) else (// код за изпълнение)) 

Вложен ако операторите обикновено се използват, когато трябва да тестваме едно условие, последвано от друго. В вложен if оператор, ако външният if оператор връща true, той влиза в тялото, за да провери вътрешния if оператор.

Пример 4: Вложено ако … друго изявление

Следващата програма изчислява най-големия брой измежду 3 числа, като използва вложен оператор if … else.

 using System; namespace Conditional ( class Nested ( public static void Main(string() args) ( int first = 7, second = -23, third = 13; if (first> second) ( if (firstNumber> third) ( Console.WriteLine("(0) is the largest", first); ) else ( Console.WriteLine("(0) is the largest", third); ) ) else ( if (second> third) ( Console.WriteLine("(0) is the largest", second); ) else ( Console.WriteLine("(0) is the largest", third); ) ) ) ) ) 

Когато стартираме програмата, изходът ще бъде:

 13 е най-големият

Интересни статии...