I'm new to programming and stack overflow blogs, so hopefully I am following the 'do's and dont's' properly.
I have been given an assignment question asking me to store 5 integers in an array and to determine if they are a prime number or not.
The questions I have are as follows:
How do I store them into an integer array?
How do I make my program divide every input by every number less than the input?
The code I have written so far is this:
Sub Main()
Dim a, b, c, d, e As Integer
Dim isPrime As Boolean = True
Console.WriteLine("Please enter a value for a: ")
a = Console.ReadLine
Console.WriteLine("Please enter a value for b: ")
b = Console.ReadLine
Console.WriteLine("Please enter a value for c: ")
c = Console.ReadLine
Console.WriteLine("Please enter a value for d: ")
d = Console.ReadLine
Console.WriteLine("Please enter a value for e: ")
e = Console.ReadLine
If a Mod (a - 1) > 0 Or a = 2 And a <> 0 Then
Console.WriteLine("a is a prime number")
ElseIf a Mod (a - 1) = 0 Then
Console.WriteLine("a is not a prime number")
End If
If b Mod (b - 1) > 0 Or b = 2 And b <> 0 Then
Console.WriteLine("b is a prime number")
ElseIf b Mod (b - 1) = 0 Then
Console.WriteLine("b is not a prime number")
End If
If c Mod (c - 1) > 0 Or c = 2 And c <> 0 Then
Console.WriteLine("c is a prime number")
ElseIf c Mod (c - 1) = 0 Then
Console.WriteLine("c is not a prime number")
End If
If d Mod (d - 1) > 0 Or d = 2 And d <> 0 Then
Console.WriteLine("d is a prime number")
ElseIf d Mod (d - 1) = 0 Then
Console.WriteLine("d is not a prime number")
End If
If e Mod (e - 1) > 0 Or e = 2 And e <> 0 Then
Console.WriteLine("e is a prime number")
ElseIf e Mod (e - 1) = 0 Then
Console.WriteLine("e is not a prime number")
End If
Console.ReadKey()
End Sub
Learning all of this stuff with the prior knowledge provided has made things difficult, so any help would be greatly appreciated!
Dim a, b, c, d, e As Integer
Console.WriteLine("Please enter a value for a: ")
a = Console.ReadLine
Console.WriteLine("Please enter a value for b: ")
b = Console.ReadLine
Console.WriteLine("Please enter a value for c: ")
c = Console.ReadLine
Console.WriteLine("Please enter a value for d: ")
d = Console.ReadLine
Console.WriteLine("Please enter a value for e: ")
e = Console.ReadLine
Dim intary() As Integer = {CInt(a), CInt(b), CInt(c), CInt(d), CInt(e)}
For Each number As Integer In intary
Dim prime As Boolean = True
For x As Integer = 2 To number - 1
If number Mod x = 0 Then
prime = False
Exit For
End If
Next
If prime Then
Console.WriteLine(number.ToString & " IS a prime number")
Else
Console.WriteLine(number.ToString & " IS NOT a prime number")
End If
Next
The integer array is created in the first line. Then, the concept is you would want to iterate through each item in the array, and run a prime number test on it. So, we have a for loop that will run our prime number test on each number in the array. For each of the numbers, we divide the test-number by every number from two all the way up to the given test-number and check the mod remainder. If any of those return zero besides the number itself, then we do not have a prime number. In the example shown, I am just printing a simple line stating whether or not each number passed or failed the test...hope this helps and good luck learning your new language!
Side note, you could dim the array and add each new number as it's retrieved from the user, but you would need to redim or resize the array each time. The example I wrote just uses the input logic you already had in place. If the assignment didn't explicitly ask for an array, you'd be able to write a much cleaner solution if you were to use a list.
The basic answer to this question is to take the users inputs, and to run a mod on each of these numbers between 2 and the users input.
To the people who are starting out like me, my advice is that you don't differ from the basic idea and it will all eventually make sense!
Related
I am currently trying to generate random numbers until a user defined amount of identical numbers in a row appears. The numbers range from 1 to 10.
When I want 8 identical numbers in a row it takes between 3 and 5 seconds. It goes through about 5 million random numbers. When I want 9 in a row I have left it for over 45 minutes without any luck.
I thought it would only take about 10 times the amount of time as it did for 8 since 1/10 to the power of 9 is only ten times bigger than to the power of 8.
Is it a problem with my code or have I messed up the maths?
MY CODE:
Sub Main()
Console.WriteLine("how many identical numbers in a row do you want")
Dim many As Integer = Console.ReadLine
Dim storage(many - 1) As Integer
Dim complete As Boolean = False
Dim part As Integer = 0
Dim count As Integer = 0
Randomize()
While complete = False
count += 1
storage(part) = Int(Rnd() * 10) + 1
' Console.WriteLine(storage(part))
part += 1
If part = many Then
part = 0
End If
If storage.Min = storage.Max Then
complete = True
End If
End While
Console.WriteLine("===========")
Console.WriteLine(count.ToString("N"))
Console.WriteLine("===========")
For i = 0 To many - 1
Console.WriteLine(storage(i))
Next
Console.ReadLine()
End Sub
There is more than one possibility: it could be that the VB Rnd function is written so that it can never work, or it could be that it really does simply take a long time sometimes. You would have to do many trials and average them out to find out if your expected ratio of 1:10 works as expected.
Incidentally, you don't need to keep the last ten numbers. You can just keep a count of how many times the next random number equals the previous number. Also I suggest trying a different RNG (random number generator), for example the .NET one:
Module Module1
Dim rand As New Random()
Sub Main()
Console.Write("How many identical numbers in a row do you want: ")
Dim howMany As Integer = CInt(Console.ReadLine)
Dim count As Long = 0
Dim previous = -1
Dim soFar = 0
Dim n = 0
While soFar < howMany
count += 1
n = rand.Next(1, 11)
'Console.Write(n.ToString() & " ")
If n = previous Then
soFar += 1
Else
'If previous >= 0 Then
' Console.WriteLine(" X")
' Console.Write(n.ToString() & " ")
'End If
previous = n
soFar = 1
End If
End While
Console.WriteLine()
Console.WriteLine("Tries taken: " & count.ToString())
Console.ReadLine()
End Sub
End Module
I am fairly new to coding in VB and I am trying to reverse the string of numbers in the variable 'binary' by using a while loop (at the bottom of the code) but when the program runs I get a System.IndexOutOfRangeException error. What changes do I need to make to fix this?
Thanks
Module Module1
Sub Main()
Dim denary As Integer
Dim binary As String = " "
Dim x As Integer
Dim y As Integer = 0
Console.WriteLine("What is the denary number?") 'Asks the user what number denary number they want converted
denary = Console.Read()
While denary > 0 'Calculates the binary number, but reversed
If denary Mod 2 = 0 Then
binary = binary + "0"
denary = denary / 2
Else
binary = binary + "1"
denary = denary / 2
End If
End While
Console.WriteLine("The binary equivalent is:" & binary) 'Prints the binary number in reverse
Console.ReadLine()
x = Len(binary)
While x > 0
Console.WriteLine(binary(x)) 'Print the correct binary equivalent (Not working)
Console.ReadLine()
x = x - 1
End While
End Sub
End Module
Array indexes start at 0, so the last one is always 1 less than the length of the array:
x = Len(binary) - 1
While x >= 0
'...
I am making a hangman game on VB. An help is appreciated
All I have is that player 1 enters a word. The program then puts it into an array, which sorts it into letters. The player 2 (on the same computer) tries to guess the word, one letter at the time. They type in a letter and the program will go trough the array to check if there are any letter in the word. If there are it will show the letter (leaving the others blank) and leave the scoring system at 10 (I still need to put this in) If they guess wrong the letters will remain covered and it will minus 1 of the scoring system.
Module Module1
Sub Main()
Dim myword, guess As String
Dim mywordlen As Integer
Dim flag As Boolean
Console.WriteLine("Player 1, please enter a word to guess")
myword = Console.ReadLine()
mywordlen = myword.Length
Dim answer(mywordlen) As Char
For x = 0 To mywordlen - 1
answer(x) = "_"
While answer > 0 Then
Console.WriteLine("Please guess a letter")
guess = Console.ReadLine()
flag = False
For x = 0 To mywordlen - 1
If guess = myword Then {0}
answer(x) = guess
flag = True
Console.WriteLine("The answer is, {0}")
Next
Next
End Sub
Dim myword, guess As String
Dim mywordlen, x As Integer
Dim flag As Boolean
Console.WriteLine("Player 1, please enter a word to guess")
myword = Console.ReadLine()
mywordlen = myword.Length - 1
Dim answer(mywordlen), displayword(mywordlen) As Char
Dim score As Integer = 10
For x = 0 To mywordlen
answer(x) = Mid(myword, x + 1, 1)
displayword(x) = "_"
Next
While score > 0
Console.WriteLine("Please guess a letter")
guess = Console.ReadLine() 'Assumes user only types one letter
flag = False
For x = 0 To mywordlen
If guess = answer(x) Then
displayword(x) = guess
flag = True
End If
Next
If flag Then
If New String(displayword) = myword Then
Console.WriteLine("Congratulations! You won!")
Exit While
Else
Console.WriteLine("Correct! {0}", New String(displayword))
End If
Else
Console.WriteLine("Incorrect. {0}", New String(displayword))
score -= 1
End If
End While
Console.WriteLine("Game over. The word was {0}", myword)
I'm new to programming... I'm trying to code a very basic program so that 10 integers can be input by a user, and then averaged. I've considered using an ArrayList to store all the data, but once I use "Input" once I can't use it again.
What I'm supposed to do is take a basic averaging program like this:
Dim A, B, C, D, E, F, G, H, I, J As Integer
A = 10
B = 6
C = 17
...
...
...
J = 15
Dim K As Double
K = A + B + C + D + E + F + G + H + I + J
K /= 10
Console.WriteLine(K)
Console.ReadKey()
...and make it so that the user can input all of the variables.
Hopefully this problem is clear enough... anybody know what I can do?
I have included below and example with comments. Hopefull you will learn from the statements and understand how to loop with Do/Loop or For and how to use List(Of ) to store a variable amount of data.
Sub Main()
' Initialize variable for text input, and numeric value
Dim input As String, x As Double
' Initialize empty array of numbers
Dim array = New List(Of Double)()
Do
Console.Write("Enter a number or press [Enter] to Finish :")
' Read a number (as text)
input = Console.ReadLine()
' Check if input is a number
If (Double.TryParse(input, x)) Then
' If it is a number add it to list
array.Add(x)
ElseIf x.Length>0
' If not then display a message
Console.WriteLine("** Input Not Numeric **")
End If
' Continue until user presses enter
Loop Until input.Length = 0
Console.WriteLine("{0} Numbers Entered", array.Count)
' Calculate average from values
Dim average As Double = 0
For index As Integer = 1 To array.Count
average += array(index - 1)
Next
average /= array.Count
' Display results and wait for enter
Console.WriteLine("The Average Is {0}", average)
Console.Write("Press [Enter] to End")
Console.ReadLine()
End Sub
I would do things in steps. First your way.
Dim a, b, c, d As Integer
Console.Write("Type an integer: ")
a = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
b = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
c = Int32.Parse(Console.ReadLine())
Console.Write("Type an integer: ")
d = Int32.Parse(Console.ReadLine())
Console.WriteLine("The average is: " & ((a + b + c + d) / 4))
Console.ReadLine()
Then you convert the code to use a list
Dim v As New List(Of Integer)
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Console.WriteLine("The average is: " & ((v(0) + v(1) + v(2) + v(3)) / 4))
Console.ReadLine()
Now that you are using a list, you can easely use a loop to remove duplicate code.
Dim v As New List(Of Integer)
Do While v.Count < 4
Console.Write("Type an integer: ")
v.Add(Int32.Parse(Console.ReadLine()))
Loop
Console.WriteLine("The average is: " & ((v(0) + v(1) + v(2) + v(3)) / 4))
Console.ReadLine()
After that you add error validation and use the built-in Average function.
Dim tempVal As Integer
Dim v As New List(Of Integer)
Do While v.Count < 4
Console.Write("Type an integer: ")
If Int32.TryParse(Console.ReadLine(), tempVal) Then
v.Add(tempVal)
Else
Console.WriteLine("Not a valid integer")
End If
Loop
Console.WriteLine("The average is: " & v.Average())
Console.ReadLine()
I am facing an issue to perform numbers comparison between the integers inputted by user and random numbers generated by the codes.
Each of the integers input by the user should then be compared with the LOTTO numbers to check for a match. A For each… loop needs to be used to achieve this.
After checking all the 7 user input integers against the LOTTO numbers, the total number of matches should be output to the user. If there are no matches the output should read “LOOSER!”.
Here are my codes, I'm currently only stuck at the comparison portion, and we need to use for each loop to achieve this.
Imports System
Module Lotto
Sub Main()
'Declaration
Dim numbers(6) As Integer
Dim IsStarted As Boolean = True
'Prompt user to enter
Console.WriteLine("Please enter your 7 lucky numbers from 0 - 9 ONLY")
'Use Do While Loop to re-iterate the prompts
Do While IsStarted
For pos As Integer = 0 To 6
Console.Write("Enter number {0}: ", pos + 1)
'How it stores into an array
numbers(pos) = Console.ReadLine()
'Check if it is a number: use IsNumberic()
If IsNumeric(numbers(pos)) Then 'proceed
'Check if it is NOT 0 < x > 9
If numbers(pos) < 0 Or numbers(pos) > 9 Then
'Don't proceed
Console.WriteLine("Invalid Input")
IsStarted = True
'When any number is invalid, exit the loop
Exit For
End If
End If
IsStarted = False
Next
Loop
'Printing out the array. It can also be written as
'For pos = LBound(numbers) To UBound(numbers)
For pos = 0 To 6
Console.Write(numbers(pos) & " ")
Next
Console.WriteLine()
'Random number generator
Randomize()
Dim random_numbers(6) As Integer
Dim upperbound As Integer = 7
Dim lowerbound As Integer = 0
Dim rnd_number As Double = 0
For pos = 0 To 6
rnd_number = CInt((upperbound - lowerbound) * Rnd() + lowerbound)
random_numbers(pos) = rnd_number
Console.Write(random_numbers(pos) & " ")
Next
'Iterate and compare
Dim isSame As Boolean = False
Dim pos2 As Integer = 0
Dim Counter As Integer = 0
'For check = 0 To 6
'If numbers(pos2).Equals(random_numbers(pos2)) Then
For Each number As Integer In numbers
'Console.WriteLine(pos2 + 1 & ":" & number & ":")
If number.Equals(random_numbers(pos2)) Then
'Console.WriteLine("here is the number that matched:" & number & ":")
isSame = True
pos2 = pos2 + 1
End If
For Each num As Integer In random_numbers
If random_numbers Is numbers Then
Counter = Counter + 1
End If
Next
Next
Console.WriteLine()
'Display result
If isSame = True Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If
Console.ReadLine()
End Sub
End Module
Dim intCursor As Integer = 0
For Each intNumber As Integer In numbers
'Assumes first user chosen number must equal
'the first random number to be considered a match,
'the second user number must equal the second random,
'etc (Ordering is a factor).
If random_numbers(intCursor) = intNumber Then
Counter += 1
End If
intCursor += 1
Next
If (Counter > 0) Then
Console.WriteLine("The total numbers of matches are: " & Counter)
Else
Console.WriteLine("LOOSER!")
End If