Saturday, April 26, 2008

Loops!!!!!

Program is being programed in Visual Basic


Loops can be useful in many ways. Anything you can think of that you need some statement repeated can be used with loops. The two im going to discuss are Do while and Do until loops. Once you understand one of them you will be able to understand the other because there are practically the samething with one minor difference which will be discussed later. So lets get started with the Do while loops.

First, lets get a idea of a program this can be used for. We will use the exmaple of the Sum of all number. An example of this would be the sum of all number of 10 would be 10+9+8.......+1. So lets get to the program.

You will need the following:
One static label - a label that does not change (Change the text to Sum of Number)

One dynamic label - a label that will be changing (Leave this one blank cause this will be where the answer pops up and name it lblanswer)

One Textbox - name it txtnumber

Three buttons - A calculate button (btncalc) A clear button (btnclear) and a exit button (btnexit)

For the sake of keeping this tutorial simple i will not be adding messages boxes to the exit buttons or anything really.

So now you have you buttons, textbox, and labels ready lets get to the code.

We will start with the exit button.

Private Sub btnexit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
End
End Sub


This should be good enough without any explanation.

Now we will do the clear button.
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
txtNumber.Clear()
lblanswer.Text = ""
txtNumber.Focus()
End Sub

The .clear() function clears the variable you set before the function. With the labels the .clear() will not work so we set set it back to an empty string. The .focus() will but the "focus" or the variable with be useable when you click the button. so basically the code above will clear the answer, the textbox with the number and automatically be ready for a new input.

Now the actually loops that you have been waiting for!!!!

Private Sub btncalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncalc.Click
Dim counter As Integer
Dim number As Integer
Dim number2 As Integer
Dim result As Integer

counter = 1

number = txtNumber.Text

Do While counter <= number
counter += 1
number2 = number - 1
result = number + number2
Loop
lblanswer.Text = result
End Sub
End Class

The loop actually does the samething over and over while minusing one to make the sum of all numbers, then displays the final result in lblanswer.text.

I used do while but if you wanted to use the Do until you would write DO Until counter = number. You should be able to read the difference on Do whiles and Do until......its common english. Have Fun!

No comments: