In: Computer Science
Visual Basic Question :
Sum = 1 + 1/2 + 1/3 + 1/4 + .......
A project which allows the user to enter a number in the Textbox1 and which indicates the number of terms on the Label
e.g. I enter 10 (sum) in the Textbox1 and Label1 indicates 12367 (terms)
I have tried a few days but it does not work... thanks for your help!
dim i, t as integer
for i = 1 to t-1
textbox1 = textbox1 + 1/i
next
Label1 = t
NOTE :
HERE IN THE QUESTION EXCEPT TEXTBOX AND LABEL NO OTHER OBJECT FROM TOOLBOX ARE MENTIONED, SO HERE ONLY TEXTBOX AND LABEL ARE USED.
SO, HERE THE TEXT_CHANGE PROPERTY OF TEXTBOX IS USED. MEANS WHEN IN THE TEXTBOX THE SUM VALUE WILL BE PUT, THE CORRESPONDING NUMBER OF TERMS WILL BE SHOWN IN LABEL.
HERE THE PROGRAM IS DONE WITH VISUAL BASIC IN VISUAL STUDIO 2008 PLATFORM.
PROGRAM
Public Class Form1
Dim s As Integer
'initialize variable term as 1
Dim term As Long = 1
'initialize variable c as 0
Dim c As Integer = 0
'initialize variable sum as 0
Dim sum As Double = 0.0
' here number terms will be shown on label when sum is put in
textbox
Private Sub TextBox1_TextChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
' s store the value put in textbox1
s = Val(TextBox1.Text)
' the loop will continue until sum is less than s
While (sum < s)
' calculate sum of terms
sum = sum + 1 / term
' increment number of terms
term = term + 1
End While
' print number of terms in label
Label1.Text = term - 1
End Sub
End Class
SCREEN SHOT
OUTPUT