Computer Programming: Quarter III - Module 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

10

Computer
Programming
Quarter III – Module 5:
Condition – Based Loops

"Designed by macrovector / Freepik"


Computer Programming– Grade 10
Self-Learning Module
First Edition, 2020

Republic Act 8293, section 176 states that: No copyright shall subsist in any work
of the Government of the Philippines. However, prior approval of the government agency or
office wherein the work is created shall be necessary for exploitation of such work for profit.
Such agency or office may, among other things, impose as a condition the payment of
royalties.

Borrowed materials (i.e., songs, stories, poems, pictures, photos, brand names,
trademarks, etc.) included in this module are owned by their respective copyright holders.
Every effort has been exerted to locate and seek permission to use these materials from
their respective copyright owners. The publisher and authors do not represent nor claim
ownership over them.

Published by the Department of Education – Regional Office VIII


Regional Director: Ramir B. Uytico EdD, CESO IV
Assistant Regional Director: Arnulfo M. Balane, CESO V

Development Team of the Module


Writers: Marian A. Valencia
Language Editors:
Content Editors: Martin S. Adora
Illustrators:
Layout Artist:
Management Team:
Rosemarie M. Guino EdD,OIC – Chief, CLMD
Ryan R. Tiu EdD, EPS, CLMD – Science
Joy B. Bihag, EPS, CLMD – LRMS
Name, Chief, CID
Name, EPS, CID – Science
Name. EPS, CID - LRMS

Printed in the Philippines by ________________________

Department of Education –Regional Office VIII

Office Address: Government Center, Candahug, Palo, Leyte


Telefax: 053 - 3233156
E-mail Address: region8@deped.gov
Introductory Message
This Self-Learning Module (SLM) is prepared so that you, our dear learners, can
continue your studies and learn while at home. Activities, questions, directions, exercises,
and discussions are carefully stated for you to understand each lesson.

Each SLM is composed of different parts. Each part shall guide you step-by-step as
you discover and understand the lesson prepared for you.

At the end of each module, you need to answer the test to self-check your learning.
Answer keys are provided for each activity and test. We trust that you will be honest in using
these.

In addition to the material in the main text, Notes to the Teacher are also provided to
our facilitators and parents for strategies and reminders on how they can best help you on
your home-based learning.

Please use this module with care. Do not put unnecessary marks on any part of this
SLM. Use a separate sheet of paper in answering the exercises and tests. And read the
instructions carefully before performing each task.

If you have any questions in using this SLM or any difficulty in answering the tasks in
this module, do not hesitate to consult your teacher or facilitator.

Thank you.

For the learner:

3
Welcome to the Computer Programming – Learning Module 5 on condition – based loops.

The hand is one of the most symbolized part of the human body. It is often used to depict
skill, action, and purpose. Through our hands we may learn, create, and accomplish. Hence,
the hand in this learning resource signifies that you as a learner is capable and empowered
to successfully achieve the relevant competencies and skills at your own pace and time.
Your academic success lies in your own hands!

This module was designed to provide you with fun and meaningful opportunities for guided
and independent learning at your own pace and time. You will be enabled to process the
contents of the learning resource while being an active learner.

This module has the following parts and corresponding icons:

This will give you an idea of the skills or


Explore
competencies you are expected to learn in the
module. A brief drill or review to help you link the
current lesson with the previous one. The new lesson
will also be introduced to you in various ways such
as a story, a song, a poem, a problem opener, an
activity, or a situation.
This section provides a brief discussion of the lesson.
Learn
This aims to help you discover and understand new
concepts and skills.

What’s More This comprises activities for independent practice to


solidify your understanding and skills of the topic.
You may check the answers to the exercises using
the Answer Key at the end of the module.
This includes questions or blank sentence/paragraph
Apply to be filled into process what you learned from the
lesson.

Assess This is a task which aims to evaluate your level of


mastery in achieving the learning competency.

This contains answers to all activities in the module.


Answer Key

This contains the learner’s reflection. Learners are


Reflect
encouraged to think about the lessons particularly
the parts that went well (they have understood) and
the parts that were weak (they have difficulty) and
write about it briefly. Learners can share their
thoughts and feeling about the lessons.

4
At the end of this module you will also find:

References This is a list of all sources used in developing this


module.

The following are some reminders in using this module:

1. Use the module with care. Do not put unnecessary mark/s on any part of the module.
Use a separate sheet of paper in answering the exercises.
2. Read the instruction carefully before doing each task.
3. Observe honesty and integrity in doing the tasks and checking your answers.
4. Finish the task at hand before proceeding to the next.
5. Return this module to your teacher/facilitator once you are through with it.
If you encounter any difficulty in answering the tasks in this module, do not hesitate to
consult your teacher or facilitator. Always bear in mind that you are not alone.

We hope that through this material, you will experience meaningful learning and gain
deep understanding of the relevant competencies. You can do it!

5
Explore

Introduction:

In your previous lesson, we studied about Counting – based loops.


Counting-based loops execute the set of statements for a fixed number of times based on
the definition at the beginning. Most modern programming languages use the For... Next construct
for using this type of loop.
Now we are going to study about Condition – based loops.

This user friendly module will guide in your learning & understanding of the different
parts of a Computer Program. The module will permit you use your different learning in
diverse programming languages. We used the language that is appropriate for your grade
level. The lessons were designed to follow the standard SLM format.
Have you ever wondered about the ever-growing world? Have you been fascinated by
the massive field of Technology? This introductory module will give you insights in the
diversities in the field of the different parts and components of computer software. We will
explore the different paradigms in Software Development and engage you to concepts that will
enable you to study, utilize and master any programming language you will like in the future.

After going through this module, you are expected to:

Sub-Task:
a. understand the concept of condition – based loops in Programming Languages;
b. discuss the need to use condition – based loops in declaring a program;
c. Write a simple control statement/operators that applies condition – based loops.

PRE-ASSESSMENT
Multiple Choice . Choose the letter of the best answer. Write the chosen letter on a separate
sheet of paper.
1. Which type of condition – based loop checked before entering the loop and
execute the statements contained within the block?
a. While Loop b. Condition checked at the beginning
c. Condition checked at the end d. Do While Loop

2. Which type of condition – based loop checked in the last statement of the loop
statement?
a. Do While Loop b. Condition checked at the beginning
c. Condition checked at the end d. While Loop

3. What loop is used when we do not know or cannot know how many times the set
of statements needs to be executed by the computer?
a. Counting – based loops b. Do While loop
b. Condition – based loops d. While loop
4. Which loop statement is the most versatile construct for the loop that checks the
condition at the top of the loop?
a. While Loop b. Condition checked at the beginning
c. Condition checked at the end d. Do While Loop

5. Which loop is almost identical with the WHILE loop except that the condition is
checked at the bottom of the block?
a. While Loop b. Condition checked at the beginning
c. Condition checked at the end d. Do While Loop

Learn

What is a Condition – based Loops

In these loops, the set of statements in the loop block are executed as many times as the
loop condition is either TRUE or FALSE as programmed. This loop is used when we do not
know or cannot know how many times the set of statements needs to be executed by the
computer. One example that readily comes to mind is processing the records from a data file
or a table. We normally would not know the number of records contained in the file or table.
Then we define a loop using a condition. These loops are basically of two types:

These loops are basically of two types:


1. Condition checked at the beginning: In this loop, the condition is checked before
entering the loop and executing the statements contained within the block. If the
condition evaluates to FALSE (or TRUE as the case may be), the statements in the
block do not get executed even once.

2. Condition checked at the end: In this loop, the condition is checked in the last
statement of the loop statement. Therefore, the all the statements in the loop
block get executed at least once in this loop.

WHILE Loop

The While statement is the most versatile construct for the loop that checks the condition at
the top of the loop. Do ... While is the popular construct for the loop that checks the condition
at the bottom of the loop block. Of course, we need to check the programming manual of the
specific programming language we are using when writing the program to know the exact
constructs for these loops. Let us see some examples of the While loop. Let us assume File of
Names as a data file or a table from which we read records and simply print the name.

While EOF != TRUE


Read a record from File of Names
Print the name
Wend

EOF, meaning “end of the file,” is generally a variable to indicate if all the records in the file or
table are processed and that there are no more records in the file or table to be processed.
This is the general notation used by many programming languages to denote the condition
that there is no more data available in the file or table. From the earlier example, we note the
following aspects:

1. As long as there are records in the file or table, the condition evaluates to TRUE. It goes
something like this:

a. When there are records, the answer to the question “is EOF NOT TRUE” would be “Yes,
EOF is NOT TRUE.” The execution falls to the first statement in the loop block.

b. When all the records are exhausted, the answer to the “is EOF NOT TRUE” would be “No,
EOF is TRUE.” The execution falls to the first statement coming after the loop block.

2. When all the records in the file or table are exhausted, the condition in the While statement
evaluates to FALSE and the computer exits the loop and begins execution of the statement
that immediately follows the loop. We can also insert an IF statement in the loop and check
further conditions, along with a BREAK or EXIT statement to exit the loop. Let us consider
another example.

Control Statements

While EOF != TRUE


Read a record from FileofNames
If (name = “John Doe” Then
Print the name, phone_number, address
EXIT
Endif
Wend

In this example, we added a condition to check the name is John Doe, and if it is, then exit the
program. That is, we are trying to locate the contact details of a specific person from the file or
table.

The WHILE loop is a very versatile one, and it can replace the FOR loop. Let us rewrite
the segment of code that we wrote earlier for filling a single-dimensional loop in the section on
FOR loops. Look at the following example:
Control Statements:
i=0
WHILE i < 6
Read m
arr(i) = m
i=i+1
WEND

It will do the same operation as the FOR loop example given in the earlier section on FOR
loops. We had to add two more statements: one to initialize i and one to increment i. But, one
question: why should we use a WHILE loop where a FOR loop is the perfect fit? The answer
is, we need not. I just showed the possibility. I have seen some programmers prefer to only
use the WHILE loop to the exclusion of all other loops. Here are the general rules for writing
WHILE loops:

1. A WHILE loop consists of a minimum of two statements, one to initiate the loop and the
other to end the loop. The keyword WHILE is the construct preferred by most programming
languages; the keyword WEND is not very popular. In the C-family of programming
languages, a closing curly brace “}” is used for ending the loop.

2. The WHILE statement needs to have a relational or logical expression along with it. This
condition sets the rule for stopping the execution of statements within the block and passes on
execution to the statements following the loop block.

3. There can be any number of statements embedded between the WHILE statement and
the WEND statement.

4. There must some statements contained within the loop block that cause the condition to
evaluate to FALSE. Otherwise, the loop becomes infinite and freezes the program and the
computer.

5. Generally, the WHILE loop is not used to branch control to other statements in the program.
The IF statement is the appropriate one for that purpose. But unexpected errors can crop up
that we need to trap using appropriate statements. Only in such cases would we use EXIT or
BREAK to exit the WHILE loop.

Precautions for Using the WHILE Loop

The “WHILE” loop is a very useful construct in computer programming. It is used frequently in
programs. The mistakes often committed by programmers are mainly two.

One is to forget to insert statements that terminate the loop by making the condition evaluate
to FALSE. This causes the loop to execute infinitely. The second mistake is to forget to catch
unexpected errors. If we are careful about these two aspects, we can write impeccable WHILE
loops in our programs.
Example of WHILE Loop:
A.
B. Following program illustrates while loop in C programming example:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

The above program illustrates the use of while loop. In the above program, we have printed
series of numbers from 1 to 10 using a while loop.

C.

While loop in Java

DO ... WHILE Loop


This loop is almost identical with the WHILE loop except that the condition is checked at the
bottom of the block. The syntax of this statement is as follows:
Control Statements:

DO
Statement 1
Statement 2
Statement n
WHILE <relational or logical expression>

As you can see, the WHILE statement is at the bottom of the block. The DO statement does
not require any other supporting keywords or expressions. It indicates the beginning of the
loop. The WHILE statement needs the condition defined by a relational or logical expression.
All other aspects of this loop are same as the ones detailed for the WHILE loop in the
preceding section. Therefore, I am not repeating them here once again.

Other keywords are used in different programming languages. Notable among those keywords
is the REPEAT ... UNTIL set used by the PASCAL programming language. It is also used in
some other languages. As there are now a plethora of programming languages, perhaps there
could be different keywords for this kind of loop. It is also possible that a few differences could
be there between what I described earlier and what those languages prescribe.
Example of Do - While Loop:
A.

B.

The following loop program in C illustrates the working of a do-while loop:

Below is a do-while loop in C example to print a table of number 2:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}

Output:

2
4
6
8
10
12
14
16
18
20

In the above example, we have printed multiplication table of 2 using a do-while loop. Let's
see how the program was able to print the series.

C.

Do –While loop in Java

Engage
ACTIVITY 1: You Complete Me!
Direction: Supply the correct word/s in the blank to complete each statement. Write the
answers on your answer sheet.
1. The DO statement does not require any other supporting ___________or
expressions.

2. This loop is almost identical with the ___________ loop except that the
condition is checked at the bottom of the block.
3. When there are records, the answer to the question “is EOF NOT _____” would
be “Yes, EOF is NOT TRUE.”

4. When all the records are exhausted, the answer to the “is EOF NOT TRUE”
would be “No, ________ is TRUE.”

5. We can also insert an IF statement in the loop and check further conditions,
along with a ________ or EXIT statement to exit the loop.

Apply

Activity 2
INSTRUCTION: Code Me!

1. In your laptop, desktop computer or cell phone, write a simple code that apply condition-
based loop statement;
2. Then write your explanation in a separate paper. Five (5) points each.
3. The activity will be scored using the Rubrics below:
4. You can use any application (example: Notepad++ and atom)

Example:
CODE Programming Language
// Print numbers from 1 to 5
# include <stdio.h>
Int main () C language

int i = 1;
while (i<=5)

printf (%d n,”i);

return 0;

Explanation of the Output:

When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed.
This prints 1 on the screen and the value of i is increased to 2.
Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed
again. This prints 2 on the screen and the value of i is increased to 3.
This process goes on until i becomes 6. When i is 6, the test expression i <= 5 will be false
and the loop terminates.
Output:
1
2
3
4
5

Use the Rubrics in evaluating the code:

Trait 5 4 3 2
Excellent Good Fair Poor
The program works The program works and The program The program is
and meets all of the produces the correct results produces correct producing incorrect
Specifications specifications. and displays them correctly. results but does not results.
It also meets most of the display them
other specifications. correctly.
The code is . The code is The code is poorly
exceptionally well The code is fairly easy to readable only by organized and very
Readability organized and very read. someone who difficult to read.
easy to follow. knows what it is
supposed to be
doing.
The documentation is The documentation consists The documentation The documentation is
well written and clearly of embedded comment and is simply comments simply comments
Documentation explains what the code some simple header embedded in the embedded in the code
is accomplishing and documentation that is code with some and does not help the
how. somewhat useful in simple header reader understand the
understanding the code. comments code.
separating routines.

Assess

Multiple Choice. Choose the letter of the best answer. Write the chosen letter on a separate
sheet of paper.
1. What would be the answer to the question “is EOF NOT TRUE”?
a. “Yes, EOF is NOT TRUE” b. “No, EOF is NOT TRUE”
c. “Yes, EOF is YES TRUE” d. “No, EOF is YES TRUE”

2. What do you call a loop used to construct preferred by most programming languages?
a. Do – While b. WHILE
c. IF d. FOR

3. Which of the following is used in closing the C-family of programming languages?


a. “ “ b. “ “

c. “<” d. “>”
4.What would be the answer to the question “is EOF NOT TRUE”?

a. “Yes, EOF is TRUE” b. “Yes, EOF is FALSE”


c. “No, EOF is TRUE” d. “No, EOF is FALSE”
5. What is the meaning EOF?
a. Exit of the File b. Error of the File
c. Exit of the False d. End of the File

Reflect

Today, I have learned


that_______________________________________
___________________________________________________________
___________________________________________________________
____________
___________________________________________________________
______
I have difficulty in
_______________________________________________
___________________________________________________________
___________________________________________________________
____________.

References
 Computer programming for beginners A step by step guide by Murali Chemuturi
 https://www.google.com/BeginnersBook.com
 https://www.google.com/guru.com/c-loop-statement.html
 https://www.google.com/programiz.com/c-programming/c-do-while-loops
 https://www,google.com/assessment.fiu.edu

For inquiries or feedback, please write or call:

Department of Education –Regional Office VIII – Curriculum and Learning


Management Division (CLMD) - Learning Resources Management Section (LRMS)

Government Center, Candahug, Palo, Leyte, 6501

Telefax: (053) 323-3156; 323-3854; 824-4627

Email Address: *region8@deped.gov.ph


*clmd.region8@deped.gov.ph *lrmds.region8@deped.gov.ph

You might also like