0% found this document useful (0 votes)
44 views13 pages

Nested Loop Structures in QBASIC

Uploaded by

Taneesha G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views13 pages

Nested Loop Structures in QBASIC

Uploaded by

Taneesha G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TechnoSchool Computer Programming

Computer Programming
Loops
Chapter - 8

Loop Structure

L
Loops are the important parts of most programs today. They allow repetitive tasks to be
programmed easily. They also help to reuse old lines of code we have already run.

O
What is a loop?
A loop is used to repeat a block of statements a certain number of times until a condition is met. Each

O
pass through the loop is called an iteration.
There are three ways to execute loops in QBASIC.

H
 The FOR...NEXT statement
 The DO...LOOP statement
 The WHILE...WEND statement
SC
The most popular are the FOR...NEXT and DO...LOOP statements.
The FOR...NEXT and WHILE...WEND statements are entry controlled loop structures i.e. only
if the condition is satisfied the control passes through the body of the loop whereas the DO...LOOP
O
structure is an exit controlled structure i.e. Even if the condition is false the loop gets executed
once and gets terminated.
N

Where are Loops used?


 In solving mathematical problems where you have to print a list of numbers, which are
H

incremented steadily.
 In games where you have to monitor continuously for keyboard input or mouse input.
C

The FOR...NEXT loop structure


The FOR NEXT statement is used to repeat a block of instructions for a specified number of times.
TE

It is an entry controlled loop structure. The loop terminates when the condition is false.
The syntax is as follows:

FOR counter variable = start TO end [STEP increment]


[block of instructions]
NEXT counter variable

New
Regular Series Book 6
87
TechnoSchool Computer Programming

In the FOR...NEXT statement a block of instructions is executed for certain number of times. The value
of the variable counter is incremented by 1 until it equals to the end value. The variable counter, by
default, increases by 1. You can change the rate at which the variable counter increments after each
iteration by using the STEP parameter:

Block diagram of a FOR...NEXT loop structure

L
O
Test FALSE
Condition

O
TRUE

H
Body of the loop
Statements following
the loop
SC
Example 1:
This program prints Integers ranging from 1 to 10
O
DIM counter AS INTEGER
FOR counter = 1 to 10
PRINT counter
N

NEXT
H

In Example1 the instruction PRINT counter is executed 10 times. After each loop the value of the
variable counter is incremented by 1.
C

Example 2:
This program prints odd numbers ranging from 1 to 10
TE

DIM counter AS INTEGER


FOR counter = 1 to 10 STEP 2
PRINT counter
NEXT

Note: The FOR...NEXT loop is the most flexible loop structure. Use the CONTROL-BREAK
key sequence to break an infinite loop.
New
Regular Series Book 6
88
TechnoSchool Computer Programming

The WHILE...WEND loop structure


The WHILE...WEND loop structure is another way of executing statements repeatedly. It is an
entry controlled loop structure. The loop terminates when the condition is not satisfied.
The syntax is as follows:
WHILE (condition)
Block of instructions

L
Counter variable incrementation
WEND

O
In the WHILE...WEND statement, a block of instructions is executed for certain number of times.

O
The value of the variable counter is incremented by 1 manually until it equals to the end value.
The block diagram of WHILE...WEND loop structure is as follows:

H
Block diagram of a WHILE...WEND loop structure
SC
Test FALSE
Condition
O

TRUE
Body of the loop
Statements following
N

the loop
Increment Counter
H
C

Example :
To print integers from 1 to 5
TE

DIM x AS INTEGER
x=0
WHILE x < 5
x=x+1
PRINT x
WEND

New
Regular Series Book 6
89
TechnoSchool Computer Programming

The DO...UNTIL / WHILE loop structure


The DO...LOOP statement executes a block of instructions while or until a condition is true. The
block of instructions gets executed at least once even if the condition is false.
The syntax is:
DO
[List of instructions]
LOOP UNTIL (condition)

L
(OR)
DO

O
[List of instructions]
LOOP WHILE (condition)

O
While a counter is automatically incremented in the FOR...NEXT statement, you will have to
increment the counter yourself with the DO...LOOP statement.

H
The block diagram of DO...LOOP structure is as follows:
Block diagram of a DO...UNTIL/WHILE loop structure
SC
Body of the loop
O

Test FALSE
Condition
N
H

TRUE Statements following


the loop
C

Below is an example, which makes a comparison of the FOR...NEXT and DO...LOOP methods:
The two codes below are equivalent.
TE

Using FOR...NEXT

‘This program displays a sentence 5 times


CLS
DIM counter AS INTEGER
FOR counter = 1 To 5
PRINT “Hello! How are you”
NEXT

New
Regular Series Book 6
90
TechnoSchool Computer Programming

Using DO...LOOP

‘This program displays a sentence 5 times


CLS
DIM counter AS INTEGER
counter = 0
DO

L
PRINT “Hello! How are you”
counter = counter + 1

O
LOOP UNTIL counter = 5

O
Library Functions
Introduction to Library Functions

H
Library Functions are predefined functions, which has a collection of executable code that can be
reused in a program. With the help of these library functions certain tasks can be done easily.
SC
Library functions are otherwise known as Built-in functions. Library functions can be classified
into:
 String Functions
 Numeric Functions
O

String Functions
The functions that manipulate string values are string functions. The string functions are:
N

 LEN()  MID$()
H

 LEFT$()  LCASE$()
 RIGHT$()  UCASE$()
C

LEN (name of string)


The LEN function is used to count the number of characters including the space in the given string.
TE

A$ = “Hello”
PRINT LEN (A$)

The above statement will print number 5 since the word “Hello” has 5 characters.
LEN (A$) - This function is used to find the length of the string A$.
PRINT LEN (A$) prints the value of the string A$ (i.e) the length of the string A$.

New
Regular Series Book 6
91
TechnoSchool Computer Programming

L
O
RIGHT$ (name, # of characters)
This function is used to tell the computer to start reading/printing from the right side of the string to

O
the left side. The number of characters is given after the name of the variable.
RIGHT$(A$, 4) - Return 4 characters starting from the right of the string A$.

H
PRINT RIGHT$(A$, 4) - prints 4 characters starting from the right side of the string A$.
SC
O
N

LEFT$ (name, # of characters)


This function is used to tell the computer to start reading/printing from the left side of the string to
H

the right side. The number of characters is given after the name of the variable.
LEFT$ (A$, 3) - Returns 3 characters starting from the left side of the string A$.
C

PRINT LEFT$ (A$, 3) - prints 3 characters starting from the left side of the string A$.
TE

New
Regular Series Book 6
92
TechnoSchool Computer Programming

MID$ (name, position of starting character, # of characters)


This function is used to read/print information that starts from the middle of the string.
When using this function, you must tell the computer how far from the left it should go in, and how
many characters do you want to read or print.
PRINT MID$(A$, 4, 9) - prints upto 9 characters of A$ starting from the 4th character.

L
Example:

O
O
H
LCASE$(string)
SC
Converts any uppercase letters in a string to lowercase.
LCASE$ ( “ HELLO ” )
Example:
O
N
H

UCASE$(string)
C

Converts any lowercase letters in a string to uppercase.


UCASE$( “ hello ” )
TE

Example:

New
Regular Series Book 6
93
TechnoSchool Computer Programming

Numeric Functions
The functions that manipulate numbers are numeric functions. The numeric functions are:

 ABS (X )  RND (number)


 INT (number)  SQR (X)
 SGN (number)

L
ABS (X) - Absolute value of X.
Example:

O
O
H
SC
SGN (number)
Returns +1 if number is positive, 0 if number is 0, and -1 if number is negative
Example:
O
N
H
C

SQR (X)
Returns square root of a positive number (Only if X > = 0 )
TE

Example:

New
Regular Series Book 6
94
TechnoSchool Computer Programming

INT (number)
It rounds a numeric value down to the next whole number that is less than or equal to the given number.
Example:

L
O
O
H
RND(number)
For any given number, RND returns a number between 0 and 1.
SC
To generate random number between a range you must describe the lowest and highest numbers
desired.
Example 1 :
O
N
H
C

Example 2 :
TE

New
Regular Series Book 6
95
TechnoSchool Computer Programming

Quick Review

 A loop is used to repeat a block of statements a certain number of times until a condition is
met.
 Each pass through the loop is called an iteration.

L
 There are 3 ways to execute loops in QBASIC.
 The FOR...NEXT statement

O
 The DO...LOOP statement
 The WHILE...WEND statement

O
 The most popular looping statements are the FOR...NEXT and DO...LOOP statements.
 The FOR...NEXT and WHILE...WEND statements are entry controlled loop structures.

H
 DO...LOOP statement is an exit controlled loop structure.
 The FOR...NEXT statement is used to repeat a block of instructions a specified number of
times.
SC
 The WHILE...WEND loop terminates when the condition is not satisfied.
 The block of instructions gets executed at least once even if the condition is false in a
DO...LOOP.
O

 Library Functions are predefined functions, which has a collection of executable codes that
can be reused in a program.
N

 Library functions are otherwise known as Built-in functions.


 Library functions can be classified into
H

 String Functions
 Numeric Functions
C

 The functions that manipulate string values are string functions.


 The functions that manipulate numbers are numeric functions.
TE

Formative
Assessment
I. Fill in the blanks.
1. Each pass through the loop is called _______________
2. _______________ and _______________ are entry controlled loop structures.
3. By default, the FOR loop variable is increased by _______________
New
Regular Series Book 6
96
TechnoSchool Computer Programming

4. The _______________ key sequence is used to break an infinite loop.


5. In _______________ loop, the instructions get executed at least once even if the condition is
false.
6. _______________ are predefined functions.
7. _______________ returns a random number between 0 and 1.
8. _______________ converts any lowercase letter in a string to uppercase.

L
O
II. Choose the correct answer.
1. __________________ structure is an exit controlled loop structure.
a. While Wend b. Do...Loop c. For Next

O
2. The parameter used to increase the variable value in For loop is __________________ .
a. Next b. FOR c. STEP

H
3. Library functions are otherwise known as __________________ .
a. String function b. Numeric function c. Built-in function
SC
4. __________________ converts any uppercase letter in a string to lowercase.
a. LCASE$ b. UCASE$ c. LUCASE$
5. __________________ returns the square root of a positive number.
a. SQR(X) b. ABS c. INT(X)
O

III. Try in your Computer and state the output of the following.
Segment 1: Segment 2:
N

CLS DIM x AS INTEGER


DIM counter AS INTEGER x=0
H

FOR counter = 1 to 5 WHILE x < 5


PRINT “Hello! How are you” x=x+1
C

NEXT PRINT x
WEND
TE

Segment 3: Segment 4:
counter = 6 For i = 10 TO 1 step -2
DO PRINT i
PRINT “Hello” NEXT
counter = counter + 1
LOOP UNTIL counter> = 10

New
Regular Series Book 6
97
TechnoSchool Computer Programming

Segment 5: Segment 6:
DIM counter AS INTEGER CLS
FOR counter = 1 TO 10 STEP 3 DIM counter AS INTEGER
PRINT counter counter = 0
NEXT DO

L
PRINT “Hello! How are you”
counter = counter + 1

O
LOOP UNTIL counter = 5

O
IV. Explain the following functions.

1. Left$() function 4. INT() function 7. Len() function

H
2. Right$() function 5. SGN() function 8. ABS() function
SC
3. Mid$() function 6. SQR() function 9. RND() function
O

Summative
Assessment
N

V. Write the syntax for the following loop structures.


1. FOR NEXT
H

2. WHILE WEND.
3. DO UNTIL.
C

4. DO WHILE.

VI. Answer the following.


TE

1. In how many ways loops can be executed? Mention them.


2. Write the classification of Library functions.
3. What is an entry controlled loop structure? Give examples.
4. What is an exit controlled loop structure? Give examples.
5. What is a library function?
6. What is a string function?
7. What is a numeric function?
New
Regular Series Book 6
98
TechnoSchool Computer Programming

VII. Answer the following in briefly.


1. What is a loop? State its use.
2. Draw the block diagram of FOR … Next loop structure.
3. Draw the block diagram of WHILE … WEND loop structure.
4. Draw the block diagram of DO loop structure.

L
5. Mention the different String functions.
6. Mention the different Numeric functions.

O
VIII. Brain Storming.
1. Why do you need loops in programming?

O
...............................................................................................................................................
..............................................................................................................................................

H
2. What is the major difference between entry controlled loop and exit controlled loop.
...............................................................................................................................................
SC
..............................................................................................................................................

TEST FLIGHT
O

1. Write a simple program to display multiples of 11 up to 100 using a FOR loop.


N

2. Write a simple program to display your School name and display the number of characters in it.
3. Write a simple program to display “CONTROL STATEMENT” for 100 times using DO loop.
H

Creative Moments
Write a program to display the sum of the first 10 natural numbers.
C

Glossary
TE

Task - An activity that needs to be completed within a defined time period.


Predefined - Pre-existing value or setting that is assigned to a software application.
Functions - A subroutine that performs a certain task for a single result.
Built-in - Forming an integral and permanent part of a larger structure.
String - A linear sequence of characters, words or other data.
Numeric - Denoting a number.
Manipulation - The process of handling or controlling for advantage.
New
Regular Series Book 6
99

Common questions

Powered by AI

The DO...LOOP structure in QBASIC guarantees at least one execution of its body because the condition is evaluated after the loop body has executed. This is seen in the syntax: DO [List of instructions] LOOP UNTIL (condition) or LOOP WHILE (condition), where the body executes prior to the condition being checked . This design allows the loop to be executed initially without dependance on the condition, making it practical for cases where initialization must occur first.

The FOR...NEXT loop is preferred in situations where the number of iterations is predetermined, as it is designed for counting loops with a known initial and termination condition, offering clear syntax for incrementing the counter . Conversely, DO...LOOP is better suited for scenarios where at least one execution is required before an exit condition typically determined by dynamic runtime inputs, such as reading user input until a valid response is received . The choice between these structures depends on whether the loop count is fixed or conditional on execution.

Entry controlled loops, such as FOR...NEXT and WHILE...WEND, check the condition before executing the loop body . The loop body is executed only if the condition is true, making them suitable for situations where conditions must be met before processing. In contrast, exit controlled loops like DO...LOOP execute the loop body at least once before checking the condition . This ensures that the loop body is executed regardless of the initial condition, which is useful when the first execution must occur unconditionally before any checks.

Library functions, including string and numeric functions, enhance coding efficiency by providing predefined, reusable functionalities which eliminate the need for programmers to write their own code for common operations . For instance, functions like LEN() or SQR() allow for quick access to operations such as string length calculation or square root extraction, respectively, reducing development time and potential errors that could arise from custom implementations. These built-in tools foster cleaner, more maintainable code.

The ABS() function returns the absolute value of a number, removing any sign, which is useful in calculations where only the magnitude is important . The SGN() function returns +1 if a number is positive, 0 if it is zero, and -1 if negative, facilitating decision-making processes or conditional logic based on number states. Meanwhile, SQR() returns the square root of a non-negative number, common in mathematical computations involving geometric calculations or scale factors .

A programmer would choose a DO...LOOP over a FOR...NEXT loop when at least one iteration of the loop must occur regardless of the condition being true. This is beneficial when an initial action must take place, such as user prompts or menus that need to display once before checking exit conditions. For example, a DO...LOOP can be used to repeatedly prompt for login credentials and validate them, ensuring the prompt is displayed at least once even if the exit condition is initially valid .

In QBASIC, the WHILE...WEND loop is implemented by initializing a counter or condition variable, followed by a WHILE statement that contains the loop's condition. The loop executes its body as long as the condition remains true, and counter variables need to be incremented manually within the loop . Typical use cases include iterations where the number of repetitions isn't predetermined, such as reading user input until a certain condition is met.

The LEFT$ function facilitates string manipulation by allowing extraction of a specified number of characters from the beginning of a string, useful for formatting or validation when the start of a string holds important information . Conversely, the RIGHT$ function extracts a specified number of characters from the end of a string, valuable in cases such as retrieving file extensions or identifying suffix patterns. Their ease of use and targeted character retrieval make them ideal for precise string handling tasks.

The STEP parameter in a FOR...NEXT loop specifies the amount by which the counter variable is incremented or decremented during each iteration. By default, the counter increments by 1, but STEP allows for control over the increment size, enabling the loop to increase or decrease by any positive or negative value until the loop condition is false . This provides flexibility in iterating over a sequence at a desired interval, such as iterating through even numbers by using STEP 2.

A scenario that effectively utilizes the MID$ function is parsing a user input string to extract specific information. For instance, when processing a date string '20231025', the MID$ function can extract the year, month, and day components individually: MID$(dateString, 1, 4) for the year, MID$(dateString, 5, 2) for the month, and MID$(dateString, 7, 2) for the day. This function provides precise string manipulation capabilities, enabling targeted data retrieval from a larger string without complex parsing logic .

You might also like