The if Statement

One of the single most important statements in every programming language is the if statement. Being able to set up conditional blocks of code is a fundamental principal of writing software. In C#, the if statement is very simple to use. If you have already used another programming language, chances are that you can use the if statement of C# straight away. In any case, read on to see how it’s used. The if statement needs a boolean result, that is, true or false. In some programming languages, several datatypes can be automatically converted into booleans, but in C#, you have to specifically make the result boolean. For instance, you can’t use if(number), but you can compare number to something, to generate a true or false, like we do later on.

In the previous chapter we looked at variables, so we will expand on one of the examples to see how conditional logic can be used.

The Code:

New Project.png

The Output of Your Program:

New Project (1)

 

Relational Operators

Use relational operators to evaluate conditions. In addition to the less than (<) and greater than (>) operators, the following operators are available:

New Project (64)

 

The Code:

New Project (65)

The Output of Your Code:

New Project (66)

 

The else Clause

 

An optional else clause can be specified to execute a block of code when the condition in the if statement evaluates to false.

The Code:

New Project (67)

The Output of Your Program:

 

New Project (68)

Nested if Statements

You can also include, or nest, if statements within another if statement.

The Code:

New Project (69)

The Output of Your Program:

New Project (70)

The if-else if Statement

The if-else if statement can used to decide three or more condition.

The Code:

New Project (71)

The Output of Your Program:

New Project (72)

if_Audio_-_Video_-_Game_26_2298369 (1)       if_Audio_-_Video_-_Game_27_2298366 (1)

Leave a comment