Uploaded by stampyfck

W6-Module-What about Ifs

advertisement
Module 006 What about Ifs
“It is in your moments of decision that your destiny is shaped.”
–Tony Robbins.
Our Programming adventure does not proceed as planned. Sometimes, we
need to make a decision and perform a series of actions depending on our
chosen decision. Sometimes, we come up with a series of choices and we
need to select an option. Whatever that may be, we encounter them in life.
We experience them and they completely change our outlook in life. The
same applies in programming. We do not perform a one-way instruction. We
perform depending on the needs of the user. Hence, we introduce
conditionals – our portal to enable our application to perform a set of actions
based on the presented scenario.
At the end of this module, you will be able to:
1.
2.
3.
4.
5.
Argue the importance of code blocks
Identify the impacts of using code blocks with variables
Identify the two conditionals in C++
Argue the importance of having different conditional statements
Construct a sound conditional statements
Again, researching beyond the coverage of this module is highly encouraged
to supplement your understanding of the topics covered. And as always,
think and see beyond the box.
So what are we waiting for? Let us continue our exploration of the world of
Computer Programming.
Course Module
Recall
In the previous module, we identified variables and data types. We also
enumerated the classifications of variables, namely:
a) Explicit Variables
b) Implicit Variables
c) Anonymous Variables
We also enumerated the classifications of data types, namely:
1. By Value
a. Explicit Data Types
b. Implicit Data Types
2. By Construct
a. Primitive Data Types
b. Referenced Data Types
Lastly, we identified the data types within C++, namely:
1. Integer Values
a. Signed Integers
i.
[singed] int
ii.
[singed] short
iii.
[signed] long
b. Unsigned Integers
i.
unsigned int
ii.
unsigned short
iii.
unsigned long
2. Floating-point Values
a. float
b. double
3. Boolean Values
a. bool
4. Character Values
a. char
b. string
Introduction to Code Blocks
Now that we are introducing different variations of our application
depending on selected scenarios, we need to discuss about code blocks.Code
Blocks are a series of programming statements that are grouped together.
They are located within the curly brackets/braces, opened by { and closed by
}.
Notice that we have been using code blocks since we started our
Programming adventure. Let us look at Figure 1, a sample of our Hello World
example from Week 004.
Figure 1. Hello World! Source Code
We have enclosed actual code logic inside a code block. This code block
belongs to “int main( )” function. It means everything inside belongs only to
the code block of “int main( )” function.
Variables
Since we are talking about code blocks, we need to discuss various things
about variables and how they are affected by code blocks. We have global
variables and local variables. Global variables are variables declared outside
of the “int main( )” function. They are usable anywhere in the same line of the
declaration, and within the code blocks like the “int main( )” function code
block. Local variables are variables declared within a specific code block and
is accessed and used only within the said code block.
Course Module
Figure 2. Global and Local Variables! Source Code
In Figure 2, we have two variables, globalA and localA. In this example,
globalA is a global variable. It means globalA is usable anywhere in the
source code. Our localA variable is a local variable which means that it is only
usable within “int main( )” function.
We only have covered the declaration and retrieval part of variables, but how
about assignment? We can always assign values to our variables as long as
we can retrieve their value. In addition, the value we stored in that variable
stays with the variable even if the code block where it was done is exited.
These scenarios will be clearer once we have written our first non-standard
code block, a conditional.
Introduction to Conditionals
Conditionals are the means to set a different set of statements based on
conditions. They let us expand the capabilities of our applications through
scenarios or states. In C++, we have two (2) conditionals, namely: the ifs and
the switches.
If Statements
Ifs statements are used when we have an undefined conditional expressions,
may it be a single expression or multiple expressions.
Figure 3. If Statement
In Figure 3, we placed an IF conditionals between lines 12 to 16, inclusively.
Line 12 shows the actual if statement wherein the condition we set is a
constant. Remember that positive-valued integers are treated as always true.
Therefore in this case, lines 13 to 15 will always be executed. For example, in
line 12 we have the value 0 instead of 1, then the lines 13 to 15 will never be
executed. Therefore it is imperative that the conditions within the IF
conditional evaluate to true in order for the statements within the code block
to be executed.
Again in Figure 3, we introduced another local variable localB in line 13.
Variable localB is only accessible within the IF code block (lines 12 to 16).
Therefore since we called the localB variable in line 20, the application when
compiled will return an error. The code block of “int main( )” function does
not know about localB.
Lastly, again in Figure 3, we assigned a value of 20 to localA. As discussed
above, the value 20 will retain to localA as long as the IF statement in line 12
is executed. Therefore should the application run, the value to be displayed
for localA will be 20 and not its initial value of 2.
Course Module
Now, what if we want to handle a scenario wherein our initial if statement
evaluates to false? We can use the If…Else statements.
Figure 4. If-Else Statement
In Figure 4, we introduced the else statement in line 17. The else code block,
from line 16 to 18, will only be taken in consideration should the if statement
evaluates to false. In this specific example since line 12 is always true, lines
16 to 18 will never be executed.
Again if we modify our line 12 to always evaluate to false (e.g. “if(0) {” ), then
our line 16 to 18 will always be executed. Just remember that the “else”
statements will only be executed if the “if” statements before them are not
executed.
Lastly, how about if we have more than one condition to consider? Then we
can use a compound if statements.
Code optimization helps developers create a seamless application execution.
You may learn more about the topic through the course about “Assembly”
languages.
Figure 5. If-Else If-Else Statement
Figure 5 introduces to how to use the compounded “if” statements. In
addition, we have modified our original source code to something more
meaningful. What we did here is we declared two local variables, namely: “a”
and “b”. Variable “a” is initialized as an integer with a value of 123. Variable
“b” is initialized as an integer with a value of 1. In this example, we have
three statements for our conditional in lines 11, 13 and 15.
Now let us evaluate our application, in line 13 we evaluate whether the value
of variable “b” is equal to exactly 1. Since this is always true, the value of
variable “a” will be multiplied by 1. Therefore come line 19, the value of
variable “a” is still 123.
If we modify our application and changed the initial value of variable “b” to 2,
and execute the application, we will have:






Line 11 will evaluate to false since variable “b” is not equal to 1.
Line 12 will not be executed.
Line 13 will evaluate to true since variable “b” is equal to 2.
Line 14 will be executed.
Line 15 will not be passed by since line 13 is already executed.
Line 16 will not be executed.
If we modify our application and changed the initial value of variable “b” any
value except 1 and 2 (e.g. “int b = 3”), and execute the application, we will
have:
Course Module






Line 11 will evaluate to false since variable “b” is not equal to 1.
Line 12 will not be executed.
Line 13 will evaluate to false since variable “b” is not equal to 2.
Line 14 will not be executed.
Line 15 will be executed since lines 11 and 13 evaluated to false.
Line 16 will be executed.
Noticed how the value of variable “a” is affected by what the value of var iable
“b” is? This is a simple demonstration of the power of using conditionals.
Switch Statements
Another of the conditionals are the switch statements.Switch is a conditional
that compares one specific variable against a set of defined constants or
values.
Figure 6. Switch Statement
A switch statement is started with the “switch(variableName) {” syntax and
ended with a closing bracket “}”. In between are the possible values for the
“variableName” preceded with a “case” statement and ended by a colon “:”.
For example, in line 12, variable “b” has a possible value of “1” so we wrote
“case 1:”. Followed by it are the statements that will be executed only when
the value of “b” is “1”. That may be any number of statements. Notice that
almost all “case” statements are ended by a “break;” statement. This is
because, in switch, breaks ends the execution of that specific value.
Let us take lines 18 and 19 as our example. “case 3:” does not have any
“break;” statements, therefore if the value of the variable “b” is 3, it will
execute all the statements under it and proceed to the next case statement,
the “case 4:”. The execution of “case 3:” does not end at “case 3:”, it proceeds
to “case 4:” and executes it regardless if the value of variable “b” is not 4.
For this to make more sense, let us change the value of variable “b” to 3. What
will be the displayed value of variable “a”?
a.
b.
c.
d.
123
246
369
1230
The answer is “C”. The switch statement will jump to “case 3:” since the value
of variable “b” is 3. However since there are no break statements under “case
3:”, the statements under “case 4:” will be executed. Hence, we have variable
“a” multiplied by 3 resulting to the value to be 369.
The last thing we need to consider under SWITCH statements is the
DEFAULT statement. It is an optional statement under SWITCH which is
executed should all of the CASE statement evaluate to false. If we set the
value of variable “b” to 5, the statements under DEFAULT will be executed.
SWITCH statements are two-folds faster than IF statements. This is because of
how compilers translates SWITCH statements to machine code. If you reverse
engineer a SWITCH and an IF statement, you will notice the switch evaluates to
JMP statements whereas the IF evaluates to one of the comparison IF
statements in Assembly.
Nesting of Conditionals
It is possible to create a nested conditionals depending on the need. You can
create an IF within an IF statement. You can create a SWITCH within a
SWITCH statement. You can also create a hybrid of IF within a SWITCH, or a
SWITCH within an IF. These combinations mainly depend on your need as a
developer.
Course Module
Figure 7. Nested Conditionals
Consider this example in Figure 7, we used a SWITCH statement within an IF.
Let us dissect this source code:





In lines 8 and 9, we initialized two variables with their corresponding
values.
Line 11, we checked the value of variable “b” if it is between 0 and 3
exclusive.
If it is:
o In line 12, we change the value of variable “a”.
o In line 13, we place the variable “b” in a switch statement which
multiplies the variable “a” with a multiplier (line 15 and 18)
depending on the value of variable “b”.
If it is not:
o In line 21, we multiple the variable “a” with 4 and store it back to
variable “a”.
In line 25, we finally display the value of variable “a”.
In lines 30 to 32, we conclude our application.
Noticed how the value of variable “a” is again dependent on the value of
variable “b”? In this example, we forced the value of variable “b” to be either
1 or 2 before we proceed to the SWITCH statement. Hence, we did not need
to add a DEFAULT statement.
In choosing which approach will be used, consider the number of paths that the
code will go through before finalizing your approach. This helps you make a
more optimized application resulting to a more efficient processing
Glossary
Case Statements: Part of a SWITCH statement which defines the constant
where the variable-under-parameter is being compared.
Code Block: A series of related statements that are enclosed within curly
brackets/braces.
Conditionals: Code blocks that are executed only when the specified
conditions are met.
Default Statements: Part of a SWITCH statement which defines an
alternative execution should all of the CASE statements fail.
Else If Statements: Part of an IF statement that extends possibilities to cover
other scenarios not under the original IF.
Else Statements: Part of an IF statement that presents an alternative
execution should all of the conditions under the IF and ELSE IF statements
fail.
Global Variables: Variables that are declared outside of the “int main( )”
function that are usable anywhere within the source code.
If Statements: Conditional that execute the statements within if a series of
non-constant conditions are met.
Local Variables: Variables that are declared inside a code block that are only
usable within the code block.
Switch Statements: Conditional that compares one specific variable against
a set of defined constants or values.
Course Module
References and Supplementary Materials
Books and Journals
2014; Learn C++ Programming Language; India; Tutorial Point
Richard Halterman; 2017; Fundamentals of C++ Programming; United States
of America; Southern Adventist University
Online Supplementary Reading Materials
Conditional Control Structures Tutorial: if, if-else, and switch-case
Statements; http://www.dreamincode.net/forums/topic/36256-conditionalcontrol-structures-tutorial-if-if-else-and-switch-case/; June 19, 2017
EXP19-CPP. Do not perform assignments in conditional expressions;
https://www.securecoding.cert.org/confluence/display/cplusplus/EXP19CPP.+Do+not+perform+assignments+in+conditional+expressions; June 19,
2017
std::conditional; http://en.cppreference.com/w/cpp/types/conditional/;
June 19, 2017
Download