Page 52 - Computing Book 8
P. 52
Developing Applications – Visual Studio Class 8
Repetition:
In computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached. An operation is done, such as getting an item of data and changing it, and then
some condition is checked such as whether a counter has reached a prescribed number
In Visual Basic, we have two different structures that support repetitions, or loops as they are called
in programming languages.
For…Next loop
What if we want to add all the integers from 1 to 50? Of course, we are not going to start writing
1+2+3+…, we are going to program the computer to do the same thing using loops.
Follow the steps below to create a program using Loops.
• Create a new form with two labels and one button and edit their text preferably as shown in
the example.
• Double click on the button and type the code.
st
• In the 1 line declare the “i” variable as an integer.
nd
• In the 2 line declare the “sum” variable as an integer.
rd
• In the 3 line set the value of “sum” to 0.
th
• In the 4 line For loop is defined that i=1 to 50 means it will run
50 times and increment 1 in the value of sum.
th
• In the 5 line, while the loop runs every time it will add the value
of “i” in the sum variable.
Do…Next loop
In repetition do loop is used when we don’t know exactly how many
times this loop will run. Do loop will run until a condition is met or while a
condition is true.
Follow the steps to create a program to add all integers starting from 1
until the sum is 500 or greater.
• Create a new form with a button and a ListBox and name
it lstResults. ListBox is another type of control
element and can be added through toolbox it is used
to have a list of options for users to select but here
we have used only to display the output of the
Do loop program.
• The Do…Loop structure does not increment any
counter variable automatically, so we have included
the instruction i = i + 1 to increment it by one inside
the loop.
• With the instruction lstResults.Items.Add(i & vbTab & sum), we
add one line in each loop to the ListBox, containing the current
counter value and the current sum.
• The & operator is used to concatenate the different values into a
single line and the vbTab is a predefined constant of Visual Basic
representing a tab space.
• The loop here runs for as long as the value of the sum is smaller than 500.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 51 of 75

