The following is an exercise I am having trouble with.
The button’s Click event procedure should display the number of integers from 14 to 23 in one of the labels and the sum of those integers in the other label. Code the procedure using the For…Next statement. Save the solution and then start and test the application. (The procedure should display the numbers 10 and 185.)
I'm able to display the sum 185 but not understanding how to display the amount of numbers (10) between 14 to 23. Any help is appreciated.
Public Class frmMain
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim intSum As Integer
For intNum As Integer = 14 To 23
lblShow.Text = lblShow.Text & intNum.ToString & " "
intSum = intNum
lblSum.Text = intSum.ToString
Next
End Sub
End Class
CodePudding user response:
display the number of integers from 14 to 23
This can be interpreted in a couple of ways:
- Display the count of integers between the two numbers (e.g. 23 - 14)
- Display each individual integer between the two numbers (e.g. 14, 15, 16, etc.)
If it is the former, then simply subtract the larger number from the smaller number and display that value in a label:
LabelIntegerCount.Text = (23 - 147).ToString()
If it is the latter, then inside of your For/Next loop append the currently iterated counter to the label:
For intNum As Integer = 14 To 23
LabelIntegerCount.Text &= intNum.ToString() & Environment.NewLine
' ...
Next
CodePudding user response:
Just declare sum and count local variables and increment them appropriately in the For
. You need only update the Label.Text once after the calculations have been done
Dim intSum As Integer
Dim intCount As Integer
For intNum As Integer = 14 To 23
intSum = intNum
intCount = 1
Next
lblSum.Text = intSum.ToString()
lblShow.Text = intCount.ToString()
I understand your homework has the For
requirement, but .NET has some functionality built in which can produce a list of numbers, sum them, and count them.
Dim start = 14
Dim finish = 23
Dim numbers = Enumerable.Range(start, finish - start 1)
lblSum.Text = numbers.Sum().ToString()
lblShow.Text = numbers.Count().ToString()
Both methods produce your required output