silvertooth07 0 Newbie Poster

we were asked to input a number and display the sum of the odd and even integers.

eg.

number: 10
sum of odd: 25
sum of even: 30

intnum = CInt(txtnum.Text)

        Dim counter% = 1
        Do Until counter = intnum
            intcompare = counter Mod 2
            If intcompare = 0 Then inteven += counter Else intodd += counter
            counter += 1
        Loop
        txteven.Text = inteven
        txtodd.Text = intodd

when i ran the program, i keep on getting 20 instead of 30 for the sum of even integers. the sum of odd is correct.

thanks again~!

Dani AI

Generated

— the symptom you describe usually comes from the loop terminating before it processes the final value. A top-tested Do Until stops as soon as the condition becomes true, so when your counter reaches the input number the loop exits and that last number never gets added. That explains why the even total looks short by the highest even.

A simple, clearer fix is to use a For loop that includes the end value:

Dim intnum As Integer = CInt(txtnum.Text)
Dim inteven As Integer = 0
Dim intodd As Integer = 0

For counter As Integer = 1 To intnum
    If counter Mod 2 = 0 Then
        inteven += counter
    Else
        intodd += counter
    End If
Next

txteven.Text = inteven.ToString()
txtodd.Text = intodd.ToString()

If you prefer Do/Loop, make the condition inclusive (for example Do While counter <= intnum) or change the Do Until test to counter > intnum. Also ensure inteven and intodd are reset to zero each time the routine runs (class-level fields will accumulate otherwise), validate the input, and step through with the debugger to confirm which values are processed.

For details on loop semantics see Do...Loop Statement (Visual Basic).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.