Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loops - Adding Numbers - Visual Basic

Tags:

vb.net

So the program has to add all the numbers from "x" to "y".

But it also has to display all the numbers added :

i.e. 10 to 20 should display 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 = 165

Here's what I have:

Dim firstnum As Integer = Val(TextBox1.Text)
    Dim secondnum As Integer = Val(TextBox2.Text)
    Dim sum As Integer = 0


    While firstnum <= secondnum

        sum = sum + firstnum
        firstnum = firstnum + 1

        Label3.Text = firstnum & "+"

    End While


    suum.Text = "  =  " & Val(sum)
like image 984
Ds.109 Avatar asked Oct 24 '25 14:10

Ds.109


2 Answers

With the following:

Label3.Text = firstnum & "+"

You are overwriting the value in Label3 every time you go through the loop. What you probably want to do is concatenate the existing value with the next number.

This should get you on your way:

Label3.Text = Label3.Text & firstnum & " + "
like image 137
Oded Avatar answered Oct 27 '25 19:10

Oded


Is Linq ok? Then you can use Enumerable.Range and Enumerable.Sum:

Dim startNum = Int32.Parse(TextBox1.Text)
Dim endNum = Int32.Parse(TextBox2.Text)
Dim numbers = Enumerable.Range(startNum, endNum - startNum + 1) 'inclusive, therefore + 1
Label3.Text = String.Join(" + ", numbers)
suum.Text = numbers.Sum()
like image 43
Tim Schmelter Avatar answered Oct 27 '25 19:10

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!