Main Topics
Browse All TopicsI am a beginning Visual Basic student and I am having problems with arrays. Is there anyone out there that can help?
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Instead of focusing on the Syntax of Arrays I would suggest that you consider the purpose of Arrays. Such an approach will help you realize their importance and usefulness.
For instance, Arrays can be used to simplify your code by grouping like things together. For instance, let’s say you have 2 students and you simply want to decide which student is younger. In such a case you might need to define two variables that will allow you to talk about each of the student’s ages. For example, let’s say we represent the age of a student as a Long such that the first 4 digits are the birth Year, the next 2 digits are the birth Month, and the last 2 digits are the birth Day. So, if you were born on Feb 06, 1978 then the Long that represents your birthday would be 19780206. We can solve this problem by simply comparing the two Longs to see which is smaller. Like this:
Define Student1Age As A Long
Define Student2Age As A Long
Get Student1Age from the first student
Get Student2Age from the second student
If Student1Age = Student2Age then Output "The students are the same age"
If Student1Age < Student2Age then Output "Student 1 is younger then Student 2"
If Student1Age > Student2Age then Output "Student 2 is younger then Student 1"
Ok, so I could have written those "If" statements a little tighter, but I wanted to keep it basic. Anyway, the point is that there is no problem using two variables to solve such a problem.
However, let’s say that you have a full room of students. Then what do you do if you want to organize them by age (similarly to what we did above for 2 students). This is where the usefulness of Arrays come in. And there are two reasons that Arrays are nice for such a problem.
The first reason that arrays are nice is that I didn’t tell you how many students were in the class. If you don’t know how many students were in the class then there is no way for you to declare exactly enough variables for the number of students. You would at least need to waste some memory to make sure that you always have enough space to solve this problem (think about this when I give you an example for the Second reason below).
The second reason arrays are good is that it is a pain in the rump to even try to solve this problem using individual variables. For example, for simplicity sake lets assume that every classroom will always have exactly 10 students (that is a big assumption that makes the coding much easier for me, but even with such an assumption I’m not looking forward to typing in this example which follows—without this assumption I would probably not even type in an example). First we would declare our student variables like this:
Define Student1Age As A Long
Define Student2Age As A Long
Define Student3Age As A Long
Define Student4Age As A Long
Define Student5Age As A Long
Define Student6Age As A Long
Define Student7Age As A Long
Define Student8Age As A Long
Define Student9Age As A Long
Define Student10Age As A Long
But instead of thinking of these variables as the ages of specific students, think of them as being places in a line. Such that when we first line up the students they are not ordered properly, but when we finish ordering the line of students then Student1Age will be the youngest aged student and Student10Age will be the oldest. Actually, lets rename our variables to imply this approach. So, use these variables instead:
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
Define StudentBirthDateLinePositi
And just so I don’t have to type these long names ever time I want to talk about them lets instead use this set of variables:
Define SBDateLPos1 As A Long
Define SBDateLPos2 As A Long
Define SBDateLPos3 As A Long
Define SBDateLPos4 As A Long
Define SBDateLPos5 As A Long
Define SBDateLPos6 As A Long
Define SBDateLPos7 As A Long
Define SBDateLPos8 As A Long
Define SBDateLPos9 As A Long
Define SBDateLPos10 As A Long
Whew!!!! Ok, so now we fill up the line by simply asking the students to randomly form a line. So the above line is not yet ordered but each variable would have a number in it that represents the birth date of the student that is in that position in the line.
Ok, so now what do I do. Well, basically I need to find the youngest student first and move that student to the start of the line. So, let’s do that,
If SBDateLPos2 < SBDateLPos1 Then
SWITCH the student in line position 2 with the student in line position 1
If SBDateLPos3 < SBDateLPos1 Then
SWITCH the student in line position 3 with the student in line position 1
If SBDateLPos4 < SBDateLPos1 Then
SWITCH the student in line position 4 with the student in line position 1
If SBDateLPos5 < SBDateLPos1 Then
SWITCH the student in line position 5 with the student in line position 1
If SBDateLPos6 < SBDateLPos1 Then
SWITCH the student in line position 6 with the student in line position 1
If SBDateLPos7 < SBDateLPos1 Then
SWITCH the student in line position 7 with the student in line position 1
If SBDateLPos8 < SBDateLPos1 Then
SWITCH the student in line position 8 with the student in line position 1
If SBDateLPos9 < SBDateLPos1 Then
SWITCH the student in line position 9 with the student in line position 1
If SBDateLPos10 < SBDateLPos1 Then
SWITCH the student in line position 10 with the student in line position 1
**************************
Now, that just gets the youngest student into position 1 of the line. Now we need to get the second youngest student into the second position of the line. Like this:
If SBDateLPos3 < SBDateLPos2 Then
SWITCH the student in line position 3 with the student in line position 2
If SBDateLPos4 < SBDateLPos2 Then
SWITCH the student in line position 4 with the student in line position 2
If SBDateLPos5 < SBDateLPos2 Then
SWITCH the student in line position 5 with the student in line position 2
If SBDateLPos6 < SBDateLPos2 Then
SWITCH the student in line position 6 with the student in line position 2
If SBDateLPos7 < SBDateLPos2 Then
SWITCH the student in line position 7 with the student in line position 2
If SBDateLPos8 < SBDateLPos2 Then
SWITCH the student in line position 8 with the student in line position 2
If SBDateLPos9 < SBDateLPos2 Then
SWITCH the student in line position 9 with the student in line position 2
If SBDateLPos10 < SBDateLPos2 Then
SWITCH the student in line position 10 with the student in line position 2
**************************
Now we have the first and second students in the correct positions. Now we just have to do the same thing for all the other positions and we are done. So the complete algorithm would look like this (lots of repetitive code to do something trivial):
‘Find position 1 student
If SBDateLPos2 < SBDateLPos1 Then
SWITCH the student in line position 2 with the student in line position 1
If SBDateLPos3 < SBDateLPos1 Then
SWITCH the student in line position 3 with the student in line position 1
If SBDateLPos4 < SBDateLPos1 Then
SWITCH the student in line position 4 with the student in line position 1
If SBDateLPos5 < SBDateLPos1 Then
SWITCH the student in line position 5 with the student in line position 1
If SBDateLPos6 < SBDateLPos1 Then
SWITCH the student in line position 6 with the student in line position 1
If SBDateLPos7 < SBDateLPos1 Then
SWITCH the student in line position 7 with the student in line position 1
If SBDateLPos8 < SBDateLPos1 Then
SWITCH the student in line position 8 with the student in line position 1
If SBDateLPos9 < SBDateLPos1 Then
SWITCH the student in line position 9 with the student in line position 1
If SBDateLPos10 < SBDateLPos1 Then
SWITCH the student in line position 10 with the student in line position 1
‘Find position 2 student
If SBDateLPos3 < SBDateLPos2 Then
SWITCH the student in line position 3 with the student in line position 2
If SBDateLPos4 < SBDateLPos2 Then
SWITCH the student in line position 4 with the student in line position 2
If SBDateLPos5 < SBDateLPos2 Then
SWITCH the student in line position 5 with the student in line position 2
If SBDateLPos6 < SBDateLPos2 Then
SWITCH the student in line position 6 with the student in line position 2
If SBDateLPos7 < SBDateLPos2 Then
SWITCH the student in line position 7 with the student in line position 2
If SBDateLPos8 < SBDateLPos2 Then
SWITCH the student in line position 8 with the student in line position 2
If SBDateLPos9 < SBDateLPos2 Then
SWITCH the student in line position 9 with the student in line position 2
If SBDateLPos10 < SBDateLPos2 Then
SWITCH the student in line position 10 with the student in line position 2
‘Find position 3 student
If SBDateLPos4 < SBDateLPos3 Then
SWITCH the student in line position 4 with the student in line position 3
If SBDateLPos5 < SBDateLPos3 Then
SWITCH the student in line position 5 with the student in line position 3
If SBDateLPos6 < SBDateLPos3 Then
SWITCH the student in line position 6 with the student in line position 3
If SBDateLPos7 < SBDateLPos3 Then
SWITCH the student in line position 7 with the student in line position 3
If SBDateLPos8 < SBDateLPos3 Then
SWITCH the student in line position 8 with the student in line position 3
If SBDateLPos9 < SBDateLPos3 Then
SWITCH the student in line position 9 with the student in line position 3
If SBDateLPos10 < SBDateLPos3 Then
SWITCH the student in line position 10 with the student in line position 3
‘Find position 4 student
If SBDateLPos5 < SBDateLPos4 Then
SWITCH the student in line position 5 with the student in line position 4
If SBDateLPos6 < SBDateLPos4 Then
SWITCH the student in line position 6 with the student in line position 4
If SBDateLPos7 < SBDateLPos4 Then
SWITCH the student in line position 7 with the student in line position 4
If SBDateLPos8 < SBDateLPos4 Then
SWITCH the student in line position 8 with the student in line position 4
If SBDateLPos9 < SBDateLPos4 Then
SWITCH the student in line position 9 with the student in line position 4
If SBDateLPos10 < SBDateLPos4 Then
SWITCH the student in line position 10 with the student in line position 4
‘Find position 5 student
If SBDateLPos6 < SBDateLPos5 Then
SWITCH the student in line position 6 with the student in line position 5
If SBDateLPos7 < SBDateLPos5 Then
SWITCH the student in line position 7 with the student in line position 5
If SBDateLPos8 < SBDateLPos5 Then
SWITCH the student in line position 8 with the student in line position 5
If SBDateLPos9 < SBDateLPos5 Then
SWITCH the student in line position 9 with the student in line position 5
If SBDateLPos10 < SBDateLPos5 Then
SWITCH the student in line position 10 with the student in line position 5
‘Find position 6 student
If SBDateLPos7 < SBDateLPos6 Then
SWITCH the student in line position 7 with the student in line position 6
If SBDateLPos8 < SBDateLPos6 Then
SWITCH the student in line position 8 with the student in line position 6
If SBDateLPos9 < SBDateLPos6 Then
SWITCH the student in line position 9 with the student in line position 6
If SBDateLPos10 < SBDateLPos6 Then
SWITCH the student in line position 10 with the student in line position 6
‘Find position 7 student
If SBDateLPos8 < SBDateLPos7 Then
SWITCH the student in line position 8 with the student in line position 7
If SBDateLPos9 < SBDateLPos7 Then
SWITCH the student in line position 9 with the student in line position 7
If SBDateLPos10 < SBDateLPos7 Then
SWITCH the student in line position 10 with the student in line position 7
‘Find position 8 student
If SBDateLPos9 < SBDateLPos8 Then
SWITCH the student in line position 9 with the student in line position 8
If SBDateLPos10 < SBDateLPos8 Then
SWITCH the student in line position 10 with the student in line position 8
‘Find position 9 student
If SBDateLPos10 < SBDateLPos9 Then
SWITCH the student in line position 10 with the student in line position 9
‘Find position 1 student
‘Position 10 student has already been placed when we placed position 9 student
**********************
Ok, so the point is that this is a pain in the butt for just 10 students. It just gets more painful the more students I have. If I had 50 students it would be a mess of code and if I had an arbitrary unknown number of students it would be even tougher.
Ok, so how do Arrays help. Well, here is the same algorithm using an Array.
Define SBDateLPos(1 Through 10) As Long
Loop X From 1 To 9
Loop Y From X+1 To 10
If SBDateLPos(Y) < SBDateLPos(X) Then
SWITCH the student in line position Y with the student in line position X
Loop End
Loop End
You see how much coding effort we save using arrays? Even if there is an arbitrary number of students (call it N) the algorithm is the same. Here it is:
Let N represent the arbitrary number of students
Define SBDateLPos(1 Through N) As Long
Loop X From 1 To N-1
Loop Y From X+1 To N
If SBDateLPos(Y) < SBDateLPos(X) Then
SWITCH the student in line position Y with the student in line position X
Loop End
Loop End
I’m tired of typing so I’ll let you digest all that. Reading back it probably won’t be much help but I typed it all and I’m going to post it anyways. Hee hee.
So that I can finish my thought let me tell you what is involved with the statement “SWITCH the student in line position Y with the student in line position X”. This is basically a Swap routine. You basically move the information from position X into a temporary place. You then overwrite the information in position X with position Y’s information (thus the need to save it temporarily before you overwrite it). Then you take the saved information about position X and overwrite the information in position Y. So, to expand our algorithm above it might look like this:
Define SBDateLPos(1 Through 10) As Long
Loop X From 1 To 9
Loop Y From X+1 To 10
If SBDateLPos(Y) < SBDateLPos(X) Then
TempSBDateLPos = SBDateLPos(X)
SBDateLPos(X) = SBDateLPos(Y)
SBDateLPos(Y) = TempSBDateLPos
End If
Loop End
Loop End
I define this so I can finish my thought in the next message….wait for it….
Your next step would be to understand multi-dimensional arrays. Multi-dimensional arrays are not normally something that you will run into. They are just not as common as single dimensional arrays. And even when you see them it is even more uncommon to see the need for more than a 2-dimensional array. There are applications that could use more then a 2-dimensional array, but they are rare. So, if you understand single dimensional arrays then you got most of what you will need.
Still, you might find applications that will tempt you to use a 2-dimensional array, but then odds are you will be better off using a single dimensional array of records rather then a 2-dimensional array. For example, in our problem above with the Students birth date, you might also want to store the student’s weight with his birth date. Using arrays you might come up with three ways of doing this.
You could create two single dimensional arrays.
Define SBDateLPos(1 Through 10) As Long
Define SWeightLPos(1 Through 10) As Long
Loop X From 1 To 9
Loop Y From X+1 To 10
If SBDateLPos(Y) < SBDateLPos(X) Then
TempSBDateLPos = SBDateLPos(X)
SBDateLPos(X) = SBDateLPos(Y)
SBDateLPos(Y) = TempSBDateLPos
TempSWeightLPos = SWeightLPos(X)
SWeightLPos(X) = SWeightLPos(Y)
SWeightLPos(Y) = TempSWeightLPos
End If
Loop End
Loop End
Notice that as I add more and more properties I end up with another declaration and at least three more lines of code inside the “If” for each. So, if I added resting heart rate as a property I would end up with 9 lines of code inside the “If”.
Now, I could also solve the problem using a double dimension array like this:
Define SBDateLPos(1 Through 10, 1 Through 2) As Long
Loop X From 1 To 9
Loop Y From X+1 To 10
If SBDateLPos(Y) < SBDateLPos(X) Then
TempSBDateLPos = SBDateLPos(X, 1)
SBDateLPos(X, 1) = SBDateLPos(Y, 1)
SBDateLPos(Y, 1) = TempSBDateLPos
TempSBDateLPos = SBDateLPos(X, 2)
SBDateLPos(X, 2) = SBDateLPos(Y, 2)
SBDateLPos(Y, 2) = TempSBDateLPos
End If
Loop End
Loop End
Now that didn’t do much for us. I guess it made the code a little more readable. Mind you if we were using a language that allowed us to reference a full row of data within a double dimension array then we could have done something like this for the SWITCH:
TempSBDateLPos = SBDateLPos(X)
SBDateLPos(X) = SBDateLPos(Y)
SBDateLPos(Y) = TempSBDateLPos
And thus it would move both the Birth Date and the Weight data (as well as any other data that we associate) all at the same time. Only VB won’t let you do this so you have to move each item individually.
Now, what happens if you want to also get the name of the student? Now double dimensional arrays are no good at all (though I can think of a way of using a double dimensional array with an index into a single dimensional array that contains the names, but lets not get over our heads). The point is that if I have a double dimension array it can only be of one type (in this case Long). So, in this case having a bunch of single dimension arrays is better. That is you could do this:
Define SBDateLPos(1 Through 10) As Long
Define SWeightLPos(1 Through 10) As Long
Define SNameLPos(1 Through 10) As Long
Loop X From 1 To 9
Loop Y From X+1 To 10
If SBDateLPos(Y) < SBDateLPos(X) Then
TempSBDateLPos = SBDateLPos(X)
SBDateLPos(X) = SBDateLPos(Y)
SBDateLPos(Y) = TempSBDateLPos
TempSWeightLPos = SWeightLPos(X)
SWeightLPos(X) = SWeightLPos(Y)
SWeightLPos(Y) = TempSWeightLPos
TempSNameLPos = SNameLPos(X)
SNameLPos(X) = SNameLPos(Y)
SNameLPos(Y) = TempSNameLPos
End If
Loop End
Loop End
You see it’s hard to come up with good uses of even 2 dimensional arrays. They can be useful when doing matrix related mathematics (which you will often see when manipulating image). And there are definitely other uses for them; however, they are not as useful as an understanding of single dimensional arrays.
Ok, just to be complete lets talk about Records. Records help to solve two problems in our examples above. The first problem was that I wanted to Swap all the data in one swoop of code rather then having to move each item individually. The second problem was that I wanted to be able to mix and match data types associated with each student (like a student name, with is weight, with his birth date, with his heart rate, etc). Well, records will do that for us. Here is an example:
Declare Record SLPosRec With
SName As String
SBDate As Long
SWeight As Long
SHeartRate As Single
End Declare
Define SLPos(1 Through 10) As SLPosRec
Loop X From 1 To 9
Loop Y From X+1 To 10
If SLPos(Y).SBDate < SLPos(X).SBDate Then
TempSLPos = SLPos(X)
SLPos(X) = SLPos(Y)
SLPos(Y) = TempSLPos
End If
Loop End
Loop End
So, you see this solves both problems. You have String types and Long types and Single types all associated with each student and when you need to swap the position of a student you do it with one swap. So, ultimately the best solution for this problem would be to use a single dimensioned array of records. Again, if we define the problem as lining up a bunch of students in a line from youngest to oldest all the while keeping track of information (like the student name and weight, etc) about each student in the line. We basically use a bubble sort to sort the student information that is contained in an array of records.
Just to be complete let me give you some VB syntax to go with the above solution.
In a module you would declare your Record like this:
Public Type SLPosRec
SName As String
SBDate As Long
SWeight As Long
SHeartRate As Single
End Type
And you might define your global array of this type:
Public SLPos(1 To 10) As SLPosRec
Then you would sort the array somewhere else in some sub or function like this:
Dim X As Long
Dim Y As Long
Dim TempSLPos as SLPosRec
For X = 1 to 9
For Y = X+1 To 10
If (SLPos(Y).SBDate < SLPos(X).SBDate) Then
TempSLPos = SLPos(X)
SLPos(X) = SLPos(Y)
SLPos(Y) = TempSLPos
End If
Next Y
Next X
Its not so much the syntax that matters but rather the principles and reasons behind the usefulness of arrays that you should first understand. The problem you approuch defines what data types you will need to create. In the end you will eventually work you way up to Class types which can be thought of as a Record that includes not only the data (Long, String, Single, etc) but the functions that work on that data (Methods, Events). But that is another story.
I need to have this code (that I wrote) to ask the user to enter 10 numbers and only print the numbers that are repeated
Module Module1
Sub Main()
Dim numbers As Integer() = New Integer(9) {}
Dim num As Integer
Dim counter As Integer = 0
Dim i As Integer
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine()
If num < 10 Or num > 100 Then
Console.Write("Please enter a between 10 and 100, inclusive: ")
num = Console.ReadLine()
Else
Do Until i = 9
For i = 0 To 9
numbers(i) = num
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine()
Next
For i = 0 To 9
Console.WriteLine(numbers(
Next
Loop
End If
End Sub
End Module
Ok, so lets look at the first part first. That is lets solve the “Read in all the numbers from the User” part in this message.
First let’s talk a bit about the constraints. There seems to be two constraints that I see from your code.
1. There are exactly 10 numbers that we read from the user.
2. Each number must be between 10 and 100 inclusively.
Ok, so now we can talk about solving that first part like this:
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Get a valid number from the user and put it into Numbers(X)
End Loop
Of course, we need to expand that a bit more. So lets expand it to this:
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Get another number from the user and put it into Numbers(X)
End While
End Loop
And to be more complete lets also add in a bit more detail so that you can see what is going on.
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Numbers(X)
End While
End Loop
So, now all you need to do is convert the above into VB code and you have solved the first part of your problem. You might even consider putting the above into a separate sub and calling it InputNumbers or something like that. But that is up to you.
In the next message we will look at the second part of your problem which is “Output only those numbers that are repeated in the list”
Actually, before we go on lets compare my algorithm for part one of your project with your code.
Notice first that you are attempting to use an “If” statement to determine if the number entered is between 10 and 100 inclusively. And you did get the comparison correct because you can see that I am also using that same comparison in my while loop.
However, notice that your “If” statement is outside of your “For” loop. Clearly you want to check every number that the user enters. So, clearly you must put the “If” statement directly after the user enters each number. By having that “If” statement outside your loop all you are doing is checking the first number that the user entered (though you are not really even doing that, but that is in a sense what you are trying to do by putting the “If” outside of your loop).
Now, the problem is that if you simply move your “If” statement inside your “For” loop it will only check the number once. This is to say that you want to repeatedly check the number forever until the user types in a valid number. This is why you can’t use an “If” statement. Instead you need to use a “While” statement. In this case you can just think of the “While” statement as an “If” statement that will repeat while the statement is True. So you simply read that as, WHILE the number that the user typed is invalid continue to ask the user for another number (and do it forever or until the user types in a valid number).
Also, notice that you did throw in a Do Until loop, which is basically the same as a While loop. In fact, I could have used a Do Until loop and made the algorithm I wrote even tighter, but lets just stick with the While for now. In any case, the way you are using the Do Until has zero effect on the code. The code works the same with or without that loop and thus I’m not sure what you were trying to achieve with it. Most likely it is just an attempt to find a solution to the condition problem that I mentioned above.
The last thing that I should mention is that you have another loop that is outputting the numbers back to the user. So, I’m thinking that you are trying to solve the full problem rather then breaking it up into its two components. As I said, you need to think about each part of the problem separately and then write the code.
Lets work on that second part now….in the next message.
Great info by the way. You rock. Here is what I have come up with so far, I am still having problems with checking to see if there is a repetiion
Module Module1
Sub Main()
Dim numbers As Integer() = New Integer(9) {}
Dim num As Integer
Dim i As Integer = 0
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine
If num < 10 Or num > 100 Then
Console.Write("Please enter a between 10 and 100, inclusive: ")
num = Console.ReadLine()
Else
Do Until i >= 9
numbers(i) = num
i = i + 1
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine()
If num = i - 1 Then
Console.Write(num & " ")
End If
Loop
No, you still need to get rid of that "If" statement, see my previous note.
Also, notice that you are using a Do Until loop based on i. However, notice that inside the loop you increment i by 1. Whenever you see such an occurance then it is more likely that you will want to use a "For" loop (not always though). Obviously you did that in this case because you wanted to move the number that you got outside the loop (num) into your Numbers array, but as I said earlier you don't even want to get anything outside the loop or use an "If" outside the loop. Read my other post.
To illistrate this...lets say the user types in the number 5 and then he types in the number 3. This is what will happen with your code because you have the condition outside your loop.
Please enter a number between 10 and 100:
5
Please enter a between 10 and 100, inclusive:
3
However, the 3 will then be put into your numbers array as the first number because you are only check to see if the very first number is between 10 and 100. None of the other numbers are checked. See what I mean? The condition must go inside the loop and even then it needs to be a "While" statement instead of an "If" statement.
I went to lunch so I didn't finish the problem. Let me do that now.
For instance, if the user types in the following 11 numbers only the first one will be disallowed. All the rest will make it into your Numbers array.
5 <---- Will trigger the If statement and won't get used.
4 <---- Will end up in Numbers(0)
7 <---- Will end up in Numbers(1)
3001 <---- Will end up in Numbers(2)
8 <---- Will end up in Numbers(3)
1 <---- Will end up in Numbers(4)
9 <---- Will end up in Numbers(5)
-9999 <---- Will end up in Numbers(6)
2 <---- Will end up in Numbers(7)
4 <---- Will end up in Numbers(8)
222 <---- Will end up in Numbers(9)
You see that is obviously not what you want to happen, but that is what your code will allow because you have your condition (your check to see if the number is between 10 and 100) outside your loop. That check must occure after ever attempt to get a number from the user (which is why you will end up using a While loop instead of an "If" statement to preform that check).
To put it in its simplest English like form.
For each number that you want to get from the user (there are 10 of them)
Loop continuously asking the user for a number until the user types in a valid one that is between 10 and 100
You see there are two loops there. You can use whatever loop types you want, but the first one should probably be a "For" loop and the second can be a "While" or a "Do Until".
This is what I came up with...
Module Module1
Sub Main()
Dim numbers As Integer() = New Integer(9) {}
Dim num As Integer
Dim i As Integer = 0
For i = 0 To 9
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine
Next
Do While num < 10 Or num > 100
Console.WriteLine("That number is not valid, please try again: ")
num = Console.ReadLine
Loop
Do Until i >= 9
numbers(i) = num
i = i + 1
Console.Write("Please enter a number between 10 and 100: ")
num = Console.ReadLine()
If num = i - 1 Then
Console.Write(num & " ")
End If
Loop
For i = 0 To 9
If numbers(i) = numbers(i) Then
Console.Write(numbers(i) & " ")
End If
Next
End Sub
End Module
So, if I was the user and you was the program this is how our conversation would go:
You: Give me the first number
Me: 5
You: No that is not between 10 and 100 so give me another number
Me: -12
You: Comeon, I said give me a number between 10 and 100. Give me another number.
Me: 8
You: No, that is not right either. Please give me a number between 10 and 100.
Me: 12
You: Ok, I got the first number from you now give me the second number.
Me: 22
You: Ok, I got the second number from you now give me the third number.
Me: -2
You: No that is not a vaild number between 10 and 100, please try again.
Me: 9
You: Nope that is wrong too, give me another number.
Me: 17
You: Ok, I got the thrid number so now give me the fouth number.
etc...
Now, of course we won't be so wordy when we write the code. Instead we will see something like this from the computer.
Computer: Please type in a number between 10 and 100 (inclusively):
User: 5
Computer: That number was not between 10 and 100 (inclusively), please try again:
Me: -12
Computer: That number was not between 10 and 100 (inclusively), please try again:
Me: 8
Computer: That number was not between 10 and 100 (inclusively), please try again:
Me: 12
Computer: Please type in a number between 10 and 100 (inclusively):
Me: 22
Computer: Please type in a number between 10 and 100 (inclusively):
Me: -2
Computer: That number was not between 10 and 100 (inclusively), please try again:
Me: 9
Computer: That number was not between 10 and 100 (inclusively), please try again:
Me: 17
Computer: Please type in a number between 10 and 100 (inclusively):
etc...
You see how there is two loops there. One to walk through each of the 10 numbers and another that keeps asking the user for a number until he types in a valid one. Right?
Almost....take a look at my algorithm again.
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Numbers(X)
End While
End Loop
All you need to do is rewrite this using VB. Let me get you started.
Dim Numbers(1 To 10) As Integer
Dim X As Integer
For X = 1 to 10
Console.Write "Please type in a number between 10 and 100 (inclusively):"
Numbers(X) = Console.ReadLine()
While (Numbers(X) < 10) Or (Numbers(X) > 100)
...
...
...
WEnd
Next X
Just fill in the "..." with the rest of it and you got the answer to the first part of your problem. We still haven't looked at the second part yet. Let's make sure you understand the first part first.
Ok, so now we need to solve the second part of the problem. We need to “Output only those numbers that are repeated in the list”. This is where we can be creative. There are probably lots of different ways to do this. Still, ultimately every solution will have to do the following.
For each item in the array compare it to every other item in the array and see if there are any duplicates, if there are duplicates that output that item to the user.
Now if we think about how we would do this in the real world we would realize that we need at least two loops to perform this task. For instance, lets say I gave you a list of numbers like this.
14
18
12
19
18
18
11
12
22
34
The way you might solve this in real life is to start with the first number 14 and then scan down the rest of the list looking for a duplicate. You don’t find it so you ignore that first number (the 14) and move to the next number 18. Now again you scan down the entire list and you see that there are duplicates. So you mark down on another sheet of paper that 18 has duplicates. Then you move to the next number in the list (12)….and repeat the process.
Notice that each time I say “move to the next number” I am basically saying that we have a loop that starts at the first number and walks through the entire list (a for loop maybe). Also, notice that for each number I said “scan down the rest of the list” and that means that we are talking about another loop (maybe a while). In any case, you can see that when we look at how we might solve the problem in real life we will need to do two loops (or two repetitive tasks in real life).
Ok, so that should be simple for us to write the solution into a computer program, but there is one part that I kind of glossed over. When we noticed that number 18 repeated I simply said “mark down on another sheet of paper that 18 had duplicates”. Well, that is where the problem comes in. Not just there but also in my real life example above I failed to tell you what you do when you see another 18 in the list. We need a way to ignore the other occurrences of 18 since we already marked it down as a duplicate. It is these two parts of the problem that allow for us to have many solutions. It allows for a brute force approach or a memory hog approach or any number of other approaches to coming up with the same solution. So this requires a bit of thought and a little more information.
For instance, lets say that we are allowed to change the data in the Numbers array such that after we find the solution and output it to the user the Numbers array is trashed. This might not be an assumption I can make, but that is up to you to decide. So, lets just assume that it is ok for now. If that is ok, then we could solve the problem like this:
Loop X goes from 1 to 9
Set FoundMatch equal to False
Loop Y goes from X+1 to 10
If (Numbers(X) = Numbers(Y)) then do the following
Set FoundMatch equal to True so that we can output that Number(X) has duplicates
Set Numbers(Y) equal to 0 so that we do not process the duplicates a second time
End If
End Loop
If (FoundMatch is True) then do the following
Output to the user that Numbers(X) has duplicates
End If
End Loop
Hey!!!!!! That sure does look familiar. Doesn’t it look like the bubble sort that I did in my very first example way back in my first post to you? Remember it looked like this:
Loop X From 1 To 9
Loop Y From X+1 To 10
If SLPos(Y).SBDate < SLPos(X).SBDate Then
TempSLPos = SLPos(X)
SLPos(X) = SLPos(Y)
SLPos(Y) = TempSLPos
End If
Loop End
Loop End
I mean, at least the looping looks the same. We are doing something a bit different inside the loops, but we still need to visit each item in our Numbers array in the same way that the bubble sort works.
Now, the disadvantage in the way that we are solving the problem is that once we have the solution the Numbers Array has been modified and is really trash. It is this line that messes up the Numbers array for us:
Set Numbers(Y) equal to 0 so that we do not process the duplicates a second time
But in this case we might not care that the numbers array is trashed so long as the program gives us the correct answer before it trashes the numbers array. If that is the case then this solution will work fine for us.
On the other hand if it is not ok then we need to come up with a solution that will restore the numbers array before the algorithm finishes. For instance, we could use the bubble sort to sort the array and then just look for consecutive duplicate numbers. But maybe we are not even allowed to modify the order of the array data. If so, then instead of setting Numbers(Y) to 0 we can simply make it negative (–Numbers(Y)). Then before we finish we would simply reset each of the Numbers back to their absolute values. Or we could set up another array that allows us to track whether a number has been considered as a duplicate or not. Oh, there are many many ways we can solve the problem, but lets first start with the one we have found and decide if it will due.
Ok, so to put it all together you would have this as your total solution (only one of many solution):
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Numbers(X)
End While
End Loop
Loop X goes from 1 to 9
Set FoundMatch equal to False
Loop Y goes from X+1 to 10
If (Numbers(X) = Numbers(Y)) then do the following
Set FoundMatch equal to True so that we can output that Number(X) has duplicates
Set Numbers(Y) equal to 0 so that we do not process the duplicates a second time
End If
End Loop
If (FoundMatch is True) then do the following
Output to the user that Numbers(X) has duplicates
End If
End Loop
Still, lets look at some other solution that is quite different. For instance, this one trades off memory to get an advantage in coding and runtime. I think it is probably the neatest solution. At least the neatest that I can think of quickly. Take a look at it and see if you can tell what it is doing. Let me go test it to see if I didn't make any typos.
Define Array Numbers(1 Through 10, 1 Through 2) As Integers
Define NumNums As Integer
Set NumNums = 0
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Num
While (Num < 10) or (Num > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Num
End While
Set DupIndex equal to 0
Set Y equal to 1
While (DupIndex = 0) And (Y <= NumNums) do the following
If (Num = Numbers(Y, 1)) then do the following
If (Numbers(Y, 2) = 1) then do the following
Output that Num has duplicate entries
Else
Set Numbers(Y, 2) = 2
End If
DupIndex = Y
End If
If (DupIndex = 0) then
Set NumNums = NumNums + 1
Numbers(NumNums, 1) = Num
Numbers(NumNums, 2) = 1
End if
Set Y = Y + 1
End While
End Loop
Opps, no there are some minor errors. This is the correct algorithm.
Define Array Numbers(1 Through 10, 1 Through 2) As Integers
Define NumNums As Integer
Set NumNums = 0
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Num
While (Num < 10) or (Num > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Num
End While
Set DupIndex equal to 0
Set Y equal to 1
While (DupIndex = 0) And (Y <= NumNums) do the following
If (Num = Numbers(Y, 1)) then do the following
If (Numbers(Y, 2) = 1) then do the following
Output that Num has duplicate entries
Set Numbers(Y, 2) = 2
End If
DupIndex = Y
End If
Set Y = Y + 1
End While
If (DupIndex = 0) then
Set NumNums = NumNums + 1
Numbers(NumNums, 1) = Num
Numbers(NumNums, 2) = 1
End if
End Loop
I'll even give you the VB code; because, I know if you use this solution your teach will ask you what you are doing and if you don't know then you will get burned (cause your teach probably won't understand it). So, if you don't understand it then you need to solve the problem the first way I mentioned. Mind you, I am using VB6 so I don't have Console. When I did it I just randomly generated the numbers (Int(122 * RND)) and I used Debug.Write to show it in the debug window. But I changed it back to Console for you to try.
Public Sub Main()
Dim Numbers(1 To 10, 1 To 2) As Integer
Dim NumNums As Integer
Dim X As Integer
Dim Y As Integer
Dim Num As Integer
Dim DupIndex As Integer
NumNums = 0
For X = 1 To 10
Console.Write "Please type in a number between 10 and 100 (inclusively):"
Num = Console.ReadLine()
While (Num < 10) Or (Num > 100)
Console.Write "That number was not between 10 and 100 (inclusively), please try again:"
Num = Console.ReadLine()
Wend
DupIndex = 0
Y = 1
While (DupIndex = 0) And (Y <= NumNums)
If (Num = Numbers(Y, 1)) Then
If (Numbers(Y, 2) = 1) Then
Console.Write Num & " has duplicates."
Numbers(Y, 2) = 2
End If
DupIndex = Y
End If
Y = Y + 1
Wend
If (DupIndex = 0) Then
NumNums = NumNums + 1
Numbers(NumNums, 1) = Num
Numbers(NumNums, 2) = 1
End If
Next X
End Sub
Notice that I got a 2-dimensional array in there for ya too. So you can see it in action. I think this is the most elegant solution given the amount of time that I worked on it. There are probably even better solutions though. Still, your teacher is probably looking for a solution that is more like the first one I gave you the psuedocode for. This one:
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Numbers(X)
End While
End Loop
Loop X goes from 1 to 9
Set FoundMatch equal to False
Loop Y goes from X+1 to 10
If (Numbers(X) = Numbers(Y)) then do the following
Set FoundMatch equal to True so that we can output that Number(X) has duplicates
Set Numbers(Y) equal to 0 so that we do not process the duplicates a second time
End If
End Loop
If (FoundMatch is True) then do the following
Output to the user that Numbers(X) has duplicates
End If
End Loop
I won't write that one in VB code, but it should be pretty easy to convert the above psuedocode to VB code. Just make sure you define all your variables (like FoundMatch as boolean, and X and Y as integer, etc...).
Oh...and if you would rather it not tell you that the number has duplicates as you are typing in the numbers (that is you want it to wait until all numbers are typed in before outputing which have duplicates). Then you just make a few minor changes to the code and this will do it:
Public Sub Main()
Dim Numbers(1 To 10, 1 To 2) As Integer
Dim NumNums As Integer
Dim X As Integer
Dim Y As Integer
Dim Num As Integer
Dim DupIndex As Integer
NumNums = 0
For X = 1 To 10
Console.Write "Please type in a number between 10 and 100 (inclusively):"
Num = Console.ReadLine()
While (Num < 10) Or (Num > 100)
Console.Write "That number was not between 10 and 100 (inclusively), please try again:"
Num = Console.ReadLine()
Wend
DupIndex = 0
Y = 1
While (DupIndex = 0) And (Y <= NumNums)
If (Num = Numbers(Y, 1)) Then
If (Numbers(Y, 2) = 1) Then
Numbers(Y, 2) = 2
End If
DupIndex = Y
End If
Y = Y + 1
Wend
If (DupIndex = 0) Then
NumNums = NumNums + 1
Numbers(NumNums, 1) = Num
Numbers(NumNums, 2) = 1
End If
Next X
For X = 1 To NumNums
If (Numbers(X, 2) = 2) Then
Console.WriteLine Numbers(X, 1) & " has duplicates."
End If
Next X
End Sub
Again, the above solution will raise eyebrows so you had better understand it if you are going to use it. Instead, it is easier to understand my original psuedocode solution. This one:
Define Array Numbers(1 Through 10) As Integers
Loop X from 1 to 10
Output “Please type in a number between 10 and 100 (inclusively):”
Get a number from the user and put it into Numbers(X)
While (Numbers(X) < 10) or (Numbers(X) > 100) do the following
Output “That number was not between 10 and 100 (inclusively), please try again:”
Get another number from the user and put it into Numbers(X)
End While
End Loop
Loop X goes from 1 to 9
Set FoundMatch equal to False
Loop Y goes from X+1 to 10
If (Numbers(X) = Numbers(Y)) then do the following
Set FoundMatch equal to True so that we can output that Number(X) has duplicates
Set Numbers(Y) equal to 0 so that we do not process the duplicates a second time
End If
End Loop
If (FoundMatch is True) then do the following
Output to the user that Numbers(X) has duplicates
End If
End Loop
Ok....here is one more solution. It is kind of neat too. See if you can tell what it is doing. All of these solutions give the same results; however, they are all quite different in their approuch. This is important to realize because most problems have many solutions that give the same results. You need to be able to look at all of these solutions and get a feel for why one solution is better or worse then another. What are the tradeoffs? Usually there is a tradeoff between memory and runtime. Throw more memory at a problem and you can sometimes get an improvement in the runtime (though you waste more memory). Anyway, see if you can tell what this is doing and try to compair this solution to the others (its less code for one thing, but it uses more memory, but it will work for any number of input numbers, etc).
Public Sub Main()
Dim Numbers(10 To 100) As Integer
Dim X As Integer
Dim Num As Integer
'This is probably not needed for such a small problem but we might as
'well initialize the Numbers array to make sure it contains only zeros
For X = 10 To 100
Numbers(X) = 0
Next X
For X = 1 To 10
Console.Write "Please type in a number between 10 and 100 (inclusively):"
Num = Console.ReadLine()
While (Num < 10) Or (Num > 100)
Console.Write "That number was not between 10 and 100 (inclusively), please try again:"
Num = Console.ReadLine()
Wend
Numbers(Num) = Numbers(Num) + 1
Next X
For X = 10 To 100
If (Numbers(X) > 1) Then
Console.WriteLine X & " has duplicates."
End If
Next X
End Sub
Again, the above third solution will also raise eyebrows so you had better know what it is doing if you want to use it. I still think that the solution your teacher wants is the first solution (the one that I only gave you the psuedocode for). Still, if you can understand what the above solution is doing then it is a more interesting solution that could stimulate discussion with your teacher.
Business Accounts
Answer for Membership
by: Erick37Posted on 2005-02-14 at 17:31:12ID: 13310094
What's the problem?