Home > OS >  Sum of input number with do loops until
Sum of input number with do loops until

Time:10-20

Quick problem on my homework. I have to make a version of this code will "Do Until Loop". The first part regarding the "please enter a positive number" works, but not the second part, that calculates the sum.

Sub Main()
    
    Dim sumOdd, oddinput As Integer
    Dim odd = 1

    Console.Write("Please Enter a Positive Odd Number!: ")
    oddinput = CInt(Console.ReadLine())

    Do Until oddinput < 0 Or oddinput Mod 2 = 0

        Console.Write("Please Enter a Positive Odd Number!: ")
        oddinput = CInt(Console.ReadLine())

    Loop
   

'The do until loop below is giving me the issue

    Do Until odd <= oddinput

        sumOdd  = odd
        odd  = 2

    Loop

    
    Console.WriteLine("The Sum of all the odd numbers up to {0} is {1}!", oddinput, sumOdd)

    Console.ReadLine() 
End Sub

End Module

CodePudding user response:

Try:

Do Until odd > oddinput

Previously, with odd = 1 and the condition odd <= oddinput, for any oddinput bigger than 1, the loop would have just exited.

CodePudding user response:

You should initialize sumOdd at the begining.

sumOdd=0

And odd should start with 2 and not 1

Dim odd = 2

Replace also this line:

 Do Until odd > oddinput

That will work. After that you need to verify the validation because it's validating for example the -2.

CodePudding user response:

We will use a List(Of T) since we don't know how many numbers the user wants to enter. The T stands for Type and we want type Integer.

The user may enter "end" or 'eNd" it will still work because we called ToUpper on UserInput.

I moved the validation code to a separate Function so it wouldn't clutter up the Sub Main. In the ValidateInput method I used nested If statements so I could display a different message for each error. The order of the If statements is important because we can't compare the input to 0 or use the Mod operator until we have an Integer, i. Only when the input passes all three test do we return true. All the other paths return false.

Only if ValidateInput returns True do we add the UserInput to the list.

I used a StringBuilder to make a string with all the odd numbers entered. The StringBuilder helps if there are more than 10 numbers entered and won't really hurt otherwise. Strings are immutable (can't be changed) so every time you change a string, the compiler must throw away the old string and create an entirely new one. The StringBuilder avoids this.

I used interpolated strings to display the results. The $ before the string means it is an interpolated string. It is easier to deal with than the old String.Format() because you can insert variables directly in the string surround by braces { }. It is not necessary to call ToString on non string variables. That will happen automatically.

I did call ToString on the StringBuilder because I needed to Trim off the final comma and space.

Sub Main(args As String())
    Dim lst As New List(Of Integer)
    Console.WriteLine("To end type End")
    Do
        Console.Write("Please Enter a Positive Odd Number!: ")
        Dim UserInput = Console.ReadLine
        If UserInput.ToUpper = "END" Then
            Exit Do
        End If
        If ValidateInput(UserInput) Then
            lst.Add(CInt(UserInput)) 'You can use CInt with confidence because you have already validated
        End If
    Loop
    Dim sb As New StringBuilder
    For Each item In lst
        sb.Append(item.ToString & ", ")
    Next
    Console.WriteLine($"These are the numbers you entered {sb.ToString.Trim({" "c, ","c})}")
    Console.WriteLine($"You have entered {lst.Count} odd numbers. The sum is {lst.Sum}")

    Console.ReadKey()
End Sub

Private Function ValidateInput(input As String) As Boolean
    Dim i As Integer
    If Integer.TryParse(input, i) Then 'First check if it is an Integer
        If i > 0 Then 'Next check if it is positive
            If i Mod 2 <> 0 Then 'Finally check if it is odd
                Return True
            Else
                Console.WriteLine("Please enter an odd number.")
                Return False
            End If
        Else
            Console.WriteLine("Please enter a positive number.")
            Return False
        End If
    Else
        Console.WriteLine("Please enter a valid number")
        Return False
    End If
End Function

I hope you enjoy your course. If some of this code is ahead of what you have learned so for, your teacher should be okay with it as long as you understand what it is doing and can explain it.

  • Related