C++ if else statement – C# Programming Example
C++

C++ if else statement

It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:

 

where condition is the expression that is being evaluated. If this condition is truestatement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:

 

If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:

 

We can additionally specify what we want that happens if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is:

 

For example:

 

prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the present value stored in x is positive, negative or none of the previous, that is to say, equal to zero.

 

Remember that in case we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: