Choose 2 numbers then find the nth number - vb.net

"Write a program which reads in a start and an end value. The program then stores all the even numbers between these two values (inclusive) in an array. The user is then asked to select a number (n), the program should output the nth even number"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
number1 = InputBox("Enter first number")
number2 = InputBox("enter second number")
Any guidance on this would be much appreciated, I'm completely lost.

Ok, the edit is making more sense to me now. You were on the right track getting the first three inputs. Then we neeed to do 2 things to our inputs:
1) Get the even numbers within the range the user has given us
2) Return the nth term if it exists
I would approach the problem like this:
'Get our inputs
Dim number1 As Integer = CInt(InputBox("Enter first number"))
Dim number2 As Integer = CInt(InputBox("Enter second number"))
Dim nthTerm As Integer = CInt(InputBox("Enter Nth Term"))
Dim evenNumbers As New List(Of Integer)
'Now, we want to get a list of all the even numbers within n1 to n2 range
For i As Integer = number1 To number2
'if the number divided by 2 has a remainder of 0, then it's an even number
If i Mod 2 = 0 Then evenNumbers.Add(i)
Next
'Now that we have all the even #s, try to return the nth one as long as it exists
Try
'We substract 1 from the nthTerm entered by used to account for list's 0-based index
MsgBox(evenNumbers(nthTerm - 1).ToString)
Catch ex As Exception
MsgBox("Nth Term out of bounds")
End Try

Related

Visual Basic: Simple Counter with leading Zero

I am trying to create a simple counter that increases when the button is clicked.
What I would like is when the counter is clicked it displays "01", "02" etc.
I can create it already with "1", "2", but I would like to have a leading zero.
I have searched and found I can do this by converting the label to a string, but I cant seem to get the value to count?
If I change "count.text = counter" to "count.text = cot" it will display "01", but wont count. I'm guessing this is due to the fact its only displaying what is currently in the string but not increasing the value?
If I could get any guidance that would be great!
Many thanks!
Dim counter As Integer = 1
Dim cot As String = String.Format("{0:00}", counter)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter = cot + 1
count.Text = counter
End Sub
PadLeft is the key.
Dim number as Integer = 12
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 12
number = 2
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 02
The problem is, that you don't update your formatted number properly. It's only initialized a single time.
To increment the counter, use counter += 1 or counter = counter + 1 first. This will add 1 to the current value of the integer variable. Then modify the text of your Label by calling that formatting code again: count.Text = String.Format("{0:00}", counter).
This should get you started...
it converts the string into an integer. increments the number, converts it back into a string and then checks for a leading 0, if not found it adds it.
I will let you convert it into your button click for practise, as it should help you have a good understanding of the conversion between types :)
Sub string_counter()
Dim string_counter As String
string_counter = "00"
For x = 0 To 10
Debug.Print string_counter
string_counter = Int(string_counter) + 1
string_counter = Str(string_counter)
If Left(Trim(string_counter), 1) <> "0" Then
string_counter = "0" + Trim(string_counter)
End If
Next x
End Sub

Using check digit algorithm to determine whether a value inputed is valid?

I am writing code for a form that is supposed to determine whether a value inputted by the user is valid as a check digit. They input a 13 digit number and it should determine whether or not the last value is valid as a check digit. I have written in the code for the check digit algorithm but I'm having trouble with comparing the value that the algorithm found with what the user input. I have tried using the substring method to compare the 13th number given by the user with the check digit that the algorithm determined but I am having issues with the syntax of everything.
This is the code I have been working on:
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim intDigit As Integer
Dim intTotalOdd As Integer
Dim intTotalEven As Integer
Dim intGrandTotal As Integer
Dim intRemainder As Integer
Dim intCheckDigit As Integer
If txtNumber.Text.Length = 13 Then
For intOdd As Integer = 1 To 11 Step 2
intTotalOdd += (intDigit * 3)
Next intOdd
For intEven As Integer = 0 To 10 Step 2
intTotalEven += intDigit
Next intEven
intGrandTotal = intTotalOdd + intTotalEven
intRemainder = intGrandTotal Mod 10
If intRemainder <> 0 Then
intCheckDigit = 10 - intRemainder
End If
If txtNumber.Text.Substring(12, 13) = intCheckDigit Then
lblStatus = "Valid"
Else
lblStatus = "Not Valid"
End If
End If
End Sub
I think the way I'm doing it should work but I don't have very much to reference on how I would go about making the syntax work. Will the way that I'm trying to do it work or do I need to go about it in a different way?

Trying to shorten code in VB.NET

One of my assignments in vb.net is to make a program that takes in 15 inputted "test scores", returns the average, and then returns the corresponding letter grade. I am trying to make this as short as possible, and I remembered a code format that I can use when I am coding in Python (simple example with only three scores):
counter = 0
number = 0
test1,test2,test3 = 0,0,0
for i in [test1,test2,test3]:
print("Enter a test score")
i = int(input())
counter += i
number += 1
average = counter/number
Is there such a code format in VB.NET?
Yes.
Here is a simple sample code which asks user to input number of items and then items one by one. At the end it calculates average of numbers.
Console.WriteLine("Enter number of Items")
Dim numberOfItems As Integer
If Integer.TryParse(Console.ReadLine(), numberOfItems) Then
Dim items As New List(Of Decimal)()
For i As Integer = 1 To numberOfItems
Console.WriteLine("Enter number {0}", i)
Dim num As Decimal
If Decimal.TryParse(Console.ReadLine(), num) Then
items.Add(num)
End If
Next
Console.WriteLine("Average is " + items.Average())
Console.ReadLine()
End If
Please note that I've not included any type of error handling.

Find missing value in a numbers sequence - DGV column

I tried searching and didn't have any success in fixing my problem so I tried finding my own solution.
First I found max (Max) value (min value is always 1), then I set loop to search value by value, but something is wrong with my loop.
For i As Integer = 1 To Max
For y As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(y).Cells(0).Value = i Then
Else
builder2.Append(i & ",")
End If
Next
Next
To me loop looks OK but it's not working. If value i is found do nothing if it's not found add i to stringbuilder, and so on until it reaches Max value. But whatever combination I've tried I get some weird results.
Numbers are sorted from lowest to highest.
I've also extracted all values from DGV column to comma delimited string if it's easier that way...
EDIT :
Just for experimenting with that loop I've put i = 40 to 50 (to reduce the range). I know that missing values in DGV column are 40-46 and 59.
This is what I've got with loop above :
You can use LINQ to find missing numbers quite easily. You just need to get the existing numbers into a List, and then you can use Max() to find the largest number, and Except() to find the missing ones.
I put a DGV named DataGridView1 with one column, a button named bnPopulateDGV, and a button named bnFindMissingNumbers on a new Windows Form, and used the following code (with Option Infer On):
Private Sub bnPopulateDGV_Click(sender As Object, e As EventArgs) Handles bnPopulateDGV.Click
DataGridView1.Rows.Clear()
Dim seq1 = Enumerable.Range(1, 100).ToList()
Dim rand As New Random
' knock some out
For i = 1 To 5
seq1.RemoveAt(rand.Next(0, 50))
Next
For Each s In seq1
DataGridView1.Rows.Add(New String() {s.ToString()})
Next
End Sub
Private Sub bnFindMissingNumbers_Click(sender As Object, e As EventArgs) Handles bnFindMissingNumbers.Click
Dim existingNumbers As New List(Of Integer)
For Each r As DataGridViewRow In DataGridView1.Rows
existingNumbers.Add(CInt(r.Cells(0).Value))
Next
Dim min = 1
Dim max = existingNumbers.Max()
Dim missingNumbers = Enumerable.Range(min, max - min + 1).Except(existingNumbers)
MsgBox("Missing: " & String.Join(", ", missingNumbers))
End Sub

generate numbers between set values vb.net

I am creating a program to generate numbers between a list of values.
Problem I am having is if the first number stats with a smaller value than the second value it will create an error, such as 1000 and 32 will say it doesnt work, or 532 and 64
I do not understand why or how to fix it
Private Sub Generate_Click(sender As System.Object,
e As System.EventArgs) Handles Generate.Click
'Displays to enter correct information if lower is <=
If Upper.Text <= Lower.Text Or Lower.Text >= Upper.Text Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
'If Upper range is higher than lower range then display numbers until total value is displayed
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= Upper.Text 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
End Sub
Basically you have to compare numeric value you are comparing string so it is happening.
And 'or' condition is not required in if statement so omit it.
please replace you code as follows.
if System.Convert.ToInt32(Upper.Text) <= System.Convert.ToInt32(Lower.Text) Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= System.Convert.ToInt32(Upper.Text) 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
With the If clause, you are doing a string comparison on numerical values. You need to cast them to integer values. And you are doing the same comparison twice which is unnecessary. Also there is a simpler way of generating random numbers between two integers.
I would encourage you to code with the "Option Strict On" declaration at the top of the page. The compiler will alert you when you attempt to make implicit conversions of which there are several in your code.
Dim iMinimum As Integer = Integer.Parse(Lower.Text)
Dim iMaximum As Integer = Integer.Parse(Upper.Text)
If iMaximum <= iMinimum Then
Number.Text = "Please enter correct info Upper # higher value than Lower #"
Else
Dim randomObject As Random = New Random
Number.Text = randomObject.Next(iMinimum, iMaximum).ToString
End If