Sum of input number with do loops until - vb.net

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

The first part actually does not do what you want it to.
oddinput < 0
will accept any number smaller than zero
oddinput Mod 2 = 0
will accept any even number, not odd.
But what you want is to ask the user to enter a number until it is positive and odd:
Do Until oddinput > 0 And oddinput Mod 2 = 1
Console.Write("Please Enter a Positive Odd Number!: ")
oddinput = CInt(Console.ReadLine())
Loop
For the second part you want it to add odd numbers until odd is bigger than oddinput, then stop.
Do Until odd > oddinput
sumOdd += odd
odd += 2
Loop
In your last assignment you had to use While loop so you could say: while odd is smaller or equal the final number. Here you do basically the opposite: Do until odd is bigger than the final number.
Also do not use >= as the loop would stop when odd is the same as the final number, but you want this one still to be added.

Try:
Do Until oddinput < 0 Or oddinput Mod 2 = 1
You were asking for an odd number, but the condition only accepted an even one.
And:
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.

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.

Related

Sum of the first 100 even and odd number?

I need some help getting this code to work. I need the code to calculate the first 100 even and odd numbers. The code below shows the even portion, but I assume they both will work the same way, just with different numbers. I know that the first 100 even numbers are 2 to 200 or 0 to 200?, and the first 100 odd numbers are 1 to 199. (I also need to use while loops, would I use a separate while loop to determine how the code calculate the sum?)
here is the code.
Dim sum, count As Integer 'the sum and count are changing and they must be a whole number.
Const num As Integer = 2
'now we must deveolp a while loop/equation that adds every number lower or equal to 100 together.
While count Mod 2 <= 200 'while the count is smaller or equal to 100,
count =
sum += count 'The sum will be add or equaled to the count
count += 1 'The count will be added to equaled to 1
End While
Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sum) 'This is the text the user sees, which tells them that the sum of the first 100 numbers will be 5050.
Console.ReadLine()
End Sub
As usual the math portion is giving me trouble. I feel like I have the right idea, but I cant execute it properly.
Dim sumEven, sumOdd As Integer
Dim even = 2
Dim odd = 1
While even <= 200 AndAlso odd <= 200
sumEven += even
sumOdd += odd
even += 2
odd += 2
End While
Console.WriteLine("The Sum of the first 100 even numbers is: {0}!", sumEven)
Console.WriteLine("The Sum of the first 100 odd numbers is: {0}!", sumOdd)

How Do I Count When Numbers Do Not Show Up

I have numbers from 1 to 25, four numbers will show up daily. I need to put a +1 on each of the four numbers and need to put a -1 on each of the 21 numbers didn't show up.
The four numbers that come up daily will be inputted in four different text boxes. The count being positive or negative needs to go on 25 separate text boxes labeled 1 thru 25.
I have tried "if textbox <> number, then count -= 1" but I get a count of -4 because it doesn't see the number in any of the four text boxes.
I only need a daily count not a textbox count. Sorry I don't have any code started and would greatly appreciate if someone can point me in the right direction. I'm doing this on Visual Studio 2012.
Thank you all for responding. Here is some code I've started but the count is not correct. My four input text boxes are in GroupBox2. Four numbers from 1 to 25 will draw daily like a lottery. The four numbers drawn will have a value of +1 each all others -1. I need to find the age of each number 1 thru 25. If a number has a +3 then that means that number has drawn 3 consecutive days. If a number has a -15 then that means that number has not drawn for the past 15 days.
Dim tb As New TextBox
Dim ctrl As Control
Dim Counter As Integer
For Each ctrl In GroupBox2.Controls
tb = ctrl
If tb.Text = 1 Then
Counter += 1
ElseIf tb.Text <> 1 Then
Counter -= 1
TextBox464.Text = Counter
End If
If tb.Text = 2 Then
Counter += 1
ElseIf tb.Text <> 2 Then
Counter -= 1
TextBox463.Text = Counter
End If
If tb.Text = 3 Then
Counter += 1
ElseIf tb.Text <> 3 Then
Counter -= 1
TextBox462.Text = Counter
End If
If tb.Text = 4 Then
Counter += 1
ElseIf tb.Text <> 4 Then
Counter -= 1
TextBox461.Text = Counter
End If
Next
We will need more information about how your going to approach it to be able to help you further, but as for your problem with this If Textbox <> number Then count -= 1 you can use something like this since your only going to be having numbers on the textboxes If Cint(Textbox.Text) <> number then count -= 1 since your using just Textbox its attempting to evaluate it as a control and not the property that your looking for, you need to read from its .Text Property, However since its evaluated as a String and not an Integer it will throw an error exception, thats why the Cint() is included (This may also be used to convert it to integer Ctype(number, Integer) Not sure if there is an execution speed difference or not, however Cint() is a faster way of writing it.) it will try and convert the String into an Integer and when its converted into an integer it can be evaluated like one using <>. No one is going to write a whole solution out for you, but while you attempt to create it yourself and more information can be added we are more than happy to help you with problems along the way.

Visual Basic - How to sort highest and lowest number of a series?

****I don't necessarily want the code to fix this problem, I would just like if someone would be able to explain to me why this is happening or what I could have done better to solve this problem.****
I have a homework assignment where I need to print out the highest and lowest number of a series.I am currently able to print out the highest and lowest numbers but if all of the numbers entered are positive, then it displays my lowest number as 0, and same if all the entered numbers are negative.
So if someone would be able to explain how to solve this, without necessarily giving away the answer, it would be greatly appreciated!
Here is my code:
Module Module1
'This is going to have the user enter a series of numbers,
'Once the user is finished have them enter '-99' to end the series,
'then it is going to return largest and smallest number
Sub Main()
NumSeries()
End Sub
'This is going to get the series from the users
Sub NumSeries()
Dim largeNum As Integer = 0
Dim smallNum As Integer = 0
Dim userNum As Integer = 0
Dim largeTemp As Integer = 0
Dim smallTemp As Integer = 0
Console.WriteLine("Please enter a series of positive and negative numbers")
Console.WriteLine("Then type '-99' to end the series")
Console.WriteLine()
While (userNum <> -99)
Console.Write("Enter num: ")
userNum = Console.ReadLine()
If (userNum > largeTemp) Then
largeTemp = userNum
largeNum = largeTemp
ElseIf (userNum < smallTemp And userNum <> -99) Then
smallTemp = userNum
smallNum = smallTemp
End If
End While
Console.WriteLine("The largest number is " & largeNum)
Console.WriteLine("The smallest number is " & smallNum)
End Sub
End Module
Two points:
You don't need the variables largeTemp and smallTemp.
(The answer to your question) You should initialize largeNum to a very small number, and smallNum to a very large number. For example, if smallNum is set to zero at the beginning of the program, only numbers smaller than zero will replace it. To find an error like this, you should trace through the program either by hand or with a debugger and see what happens at each step. It would be a good idea to do this now so you'll understand the problem. (Alternatively, as Idle-Mind pointed out, you can initialize largeNum and smallNum to the first item in the list.)
Don't use any sentinel values at all. Simply declare a Boolean variable so you know if you the value retrieved is the very first one or not:
Dim FirstEntry As Boolean = True
If it is, then set both largeNum and smallNum to that value. Now just compare each additional entered value with those stored values to see if they are bigger or smaller than the previously known extreme.
A few things you should improve upon:
You can remove the temp variables. They don't serve any other purpose other than unnecessarily consuming memory and CPU time.
You should initialize your min and max variables with highest and lowest possible values respectively. If you think larger than integer values should be allowed, change the type to Long
Dim largeNum As Integer = Integer.MinValue
Dim smallNum As Integer = Integer.MaxValue
Remove the ElseIf. Use two If statements instead. This is so that both variables will be set with the very first input itself.
If (userNum > largeNum) Then largeNum = userNum
If (userNum < smallNum) Then smallNum = userNum

Random number macro does not return desired value

I have created a simple module that is meant to do following:
generate random number between 0 and 999;
if number is lower than 500, assign value "lower", otherwise "higher"
write the random number and assigned value in cells A1 and B1
repeat the process 100,000 times.
Problem is, it returns assigned value "lower" even if the number is higher than or equal to 500, i.e., all assigned values, 100,000 of them, are "lower"!
I'd appreciate if someone can check where I'm going wrong with this code; I'm not an expert in VBA, but I thought I could do this myself... :\
Sub MacroRanNum()
Dim RunNum As Integer
Dim Outcome As String
For i = 1 To 100000
Randomize
RanNum = Int((999 - 0 + 1) * Rnd + 0)
If RunNum < 500 Then
Outcome = "Lower"
ElseIf RunNum >= 500 Then
Outcome = "Higher"
Else
Outcome = "Error!"
End If
Sheets("podatak").Cells(i, 1) = RanNum
Sheets("podatak").Cells(i, 2) = Outcome
Next i
End Sub
Your variable name is RanNum but you check for RunNum
OPTION EXPLICIT could help to avoid such problems.
You are mixing your variable names. You define and check against RunNum but your random value and your display value are RanNum. You are never testing against the value you randomly generated.

What's Wrong With my logic in this Vb program?

I'm new to visual basic and I just started taking classes on it at school. I was given an assignment to write an app that tells if an input in a textbox is a Prime Number Or Not.
I have written this code snippet in Visual Studio:
Public Class PrimeNumberApp
Public Sub CheckButton_Click(sender As Object, e As EventArgs) Handles CheckButton.Click
Dim x, y As Integer
x = Val(PrimeTextBox.Text)
For y = 2 To (x - 1)
Select Case x
Case Is = (33), (77), (99)
MsgBox("Its not a prime number, try a different number!")
Exit Sub
End Select
If x Mod y = 0 Then
MsgBox("Its not a prime number, try a different number!")
Exit Sub
Else
MsgBox("Its a prime number, you're golden!")
Exit Sub
End If
Next
Select Case x
Case Is <= 0
MsgBox("I'm only accepting values above 0. :p")
Exit Sub
End Select
End Sub
I have this code snippet displaying a Message Box telling whether the input by the user is a prime number or not with the help of the Mod operator in visual basic.
If you go through the code carefully, you'll notice I had to separately create more or less escape statements for the number 33, 77 and 99.
I had to do this cause every time I typed either of those three numbers, I'd get the result that the number is a prime number which is incorrect since they're all divisible by numbers apart from themselves. Without getting things mixed up, the program displays other prime and non-prime numbers with the right Message Box, just those three.
I had spent hours trying to figure out what I had done wrong before I added the lines below to put myself out of vb misery, lol.
Select Case x
Case Is = (33), (77), (99)
MsgBox("Its not a prime number, try a different number!")
Exit Sub
End Select
But doing this isn't healthy if I really want to be awesome at coding. So here's my question, how do I get this program fixed to display the right message box when any integer is typed in the text box. Thanks.
Your code doesn't seem to work at all. It seems to always say that every number is a prime number. You loop through every possible divisor and in that loop you test to see if the input is evenly divisible by the current divisor. That part makes sense. The problem, though is that you always immediately exit the loop after the first iteration regardless of the result of the test. Pay close attention to this code from inside your loop:
If x Mod y = 0 Then
MsgBox("Its not a prime number, try a different number!")
Exit Sub
Else
MsgBox("Its a prime number, you're golden!")
Exit Sub
End If
If we remove all of the spurious details, you can tell that the logic is flawed:
If MyTest = True Then
Exit Sub
Else
Exit Sub
End If
As you can see, no matter what the result of the test is, it's always going to exit the loop. Therefore, the loop will never progress beyond the first iteration. In order to make it continue testing every possible divisor, you need to remove the Exit Sub statements and just keep track of the result in a variable. For instance, something like this:
Dim isPrime As Boolean = True
For y = 2 To x - 1
If XIsEvenlyDivisibleByY Then
isPrime = False
Exit For
End If
Next
If isPrime Then
' ...
Else
' ...
End If
Notice that once the first evenly divisible divisor is found, I have it Exit For. There's no point in searching any further since one is enough to make it not prime.
For what it's worth, you should use Integer.TryParse rather than Val and you should use MessageBox.Show rather than MsgBox. Val and MsgBox are old VB6 style functions. It's preferable to use the newer .NET-only versions.
here is an example of how to find prime numbers, for example up to 100, using 2 loops to check every single number in a given range. In this case I started by 2 because as you know 2 is the smallest of the prime numbers.
Dim i As Integer = 2, j As Integer = 2
For i = 2 To 100
For j = 2 To (i / j)
If i Mod j = 0 Then
Exit For
End If
Next
If (j > (i / j)) Then
Console.WriteLine("{0} is prime", i)
End If
Next