CPP 05 - If Else Condition

CPP 05 - If Else Condition
Di Posting Oleh : Simple Learning
Kategori : C++



C++ uses the concept of truth and false. Any expression (expression is anything that produces a value) that produces '0' (zero) is false, and a value other than zero is truth:

NOTICE!
Value of 0 = FALSE
Value other than 0 = TRUTH

This comes in handy just like certain true circumstances help us make decisions in life. "If were a rich man, I would spent more time on inventing my own stuff instead of doing what my company think is right".

We can use similar approach in order to execute a piece of code (truth) or ignore it (false). Check the code below:

Pic. 5.1 -

Explanation
The statement that interests us here is:

if (expression_is_true) 
 run_this_code

If there is a block of code (more than one statement to execute we put the code in braces '{}' like in lines 15 through 18.

Another form of this statement is:

if (expression_is_true)
 run_this_code
else 
 run_that_code

The third one is using 'else if' as an extra condition if the previous ones did not work.

Let's run it a number of times and see what happens. While running it, we will change the truth (color) when asked. The results should be self explanatory. If the first condition is true (other than '0'), the code or code in block after if is run. If it is not true (is '0'), the code after else or else if is checked, until true condition is met.

There are two things in the code that require extra explanation. 

The variable type 'string' allows you to save a piece of text in the memory. The text (called string) must be enclosed with either double quotation (" ") or single quotation (' ') marks.

The operator '==' must be interpreted as 'is equal to' as opposed to operator '=' which assigns what's on the right of it to the left of it. If part of our code looks like below:

var1 = 1408;
this means that in the memory we store the number (or string, depending on the type) 1408.

var2 = 1408; 
this means that in the memory we store the number (or string, depending on the type) 1408.

var3 = 45;
this means that in the memory we store the number (or string, depending on the type) 45.

Now, if we try to compare the content of those variables, here is what happens:

var1 == var2;
returns TRUE, since both variables have the same values (or strings are identical).

var1 == var3;
returns FALSE, since the content of these variables is NOT identical.

Now, let's see how the code is executed depending on our answer:
Pic. 5.2 - Result

Homework
Write a code that uses 'if else' statement using different variations with one or more command to execute (then use braces '{}').

0 Response to "CPP 05 - If Else Condition"

Post a Comment