05 Control Structure Looping With The While Statement
05 Control Structure Looping With The While Statement
__
Control Structure – Looping with the “while” Statement
I. INTRODUCTION
There are instances wherein a certain task has to be repeated when a given condition is
satisfied. This repetitive task or iterative task is known as loop.
In c++, there are 3 statements that are used to accomplish a loop: while, do-while and for
statements. These statements are categorized as control structure statements.
The more general structure for looping is the while statement. The syntax is straight-forward
and easy to comprehend. Its flow of execution is very similar to the if statement. However, in the case of
the while statement, the flow goes back to the testing of the condition instead of finishing the execution
of the statement. It keeps on looping as long as its test condition is true. The following diagrams show
the comparison between the if statement and the while statement.
II. OBJECTIVES
1. To learn how to loop works
2. To use the while statement in solving repetitive task
3. To write a program that uses the while statement to solve a problem that requires input
validation
III. MATERIALS/APPARATUS/EQUIPMENT
1. Computer unit
2. Codeblock IDE with gcc mingw c++ compiler
IV. PROCEDURE
1. Turn on the computer unit and run Codeblock IDE.
2. Create a new file and save it with the filename “InputValidationUsing_while.cpp.”
3. Write the following program code, compile (build) and run.
Output:
Declare your variables as String so that you can easily compare the variable to a string literal like
ngalan == “Admin” as well as sekreto == “Delgado0229”. Use a variable name related to the data it
holds. As a general rule, use a variable name germane to its purpose.
The while loop is, as its name suggests, a loop, while the if is a one-time branching action. Meaning that
an if statement provides you the choice of doing something or not once (or something else). While a
while loop only executes commands while the condition is true.
The variable is set to -1 so that the statement will loop while the variable's value is a negative integer.
By doing this, the user's input will be verified as a positive number before the code is continued.
3. Discuss the test condition you used in securityCodesUsing_while.cpp that guarantees the
validity of both username and password inputs.
while (username != "Admin" || password != "Dennis0106"); It means that if the user or password values
do not match the required input, the code will loop.
VI. CONCLUSION
We focused more on loops. In addition to the last lesson, we learned which is good decision making, we
can apply what we learned into loops. So we can make the program do repetitive tasks like making login
credentials or multiplying numbers.