Assignment
This exercise is important because loops will be used everywhere, you need to start thinking with loops. Every task that might be done with loops will save you multiple lines of codes and give you a lot more flexibility.
1. The code below uses a function called GenerateRandomString which generates a random string obviously! But what you have to do is convert the function so it uses a loop to do its processing. I strongly suggest a For or While loop in this situation. The loop should also use the NumberOfCharacters argument to give the possibility to increase or decrease the number of characters to generate a user can enter.
Option Strict On Option Explicit On Module Program Dim Rnd As Random = New Random() Sub Main() Dim NumberOfCharactersToGenerate = 5 Console.WriteLine(GenerateRandomString(NumberOfCharactersToGenerate)) Console.ReadKey() End Sub Private Function GenerateRandomString(NumberOfCharacters As Integer) As String Dim GeneratedString As String = String.Empty Dim RandomLetter As Char = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter RandomLetter = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter RandomLetter = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter RandomLetter = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter RandomLetter = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter Return GeneratedString End Function End Module
Hint: remember to identify the repeating pattern.
2. Add a new loop to the preceding code to make it generate 100 random words!
Good luck!
Solution
Question 1
The exercise gives us a bit of code, that’s great! We have our Main(), and a function. The function here is the key for the question 1 because we have to implement a loop by replacing some of the already existing code inside of it. If you remember the hint at the bottom of the number 1, it says to try to identify repetitive parts.
The function itself only generates a certain number of characters, add them to a String type variable and returns this variable. As you can see, the part that is repeated is the letter generation. We’ve seen that we can accomplish a task multiple times with a loop, that’s what we’re aiming for.
The part in the red square will have to be converted. How are we going to do that? We will be using a For loop. Why?
Remember that a For loop needs 3 things, a starting point, a target and a step amount. Our starting point will be 1 for the first letter, then we will use the NumberOfCharacters in parameter as our target number of characters to generate. Finally, our step is simply 1.
Private Function GenerateRandomString(NumberOfCharacters As Integer) As String Dim GeneratedString As String = String.Empty For Index As Integer = 1 To NumberOfCharacters Step 1 Dim RandomLetter As Char = Convert.ToChar(Rnd.Next(97, 123)) GeneratedString += RandomLetter Next Return GeneratedString End Function
As you can see, I did exactly what I pointed out in the statement above. You can now test the code and see that it outputs the right number of random characters. Yeah!
FAQ about the code above
What is the New Random()? This is a declaration of a variable which contains an instance of an Object of type Random. You don’t have to worry about this right now, this is a more advanced topic for another tutorial.
Why is the new variable declared and initialized inside of the loop? You can declare it outside if you prefer. The compiler should make it so it does not re-declare a new variable everytime the code loops. That would be performance costly!
What is GeneratedString += RandomLetter doing exactly? This line is adding the RandomLetter value to the existing GeneratedString variable. We call that String concatenation. Again, += means the exact same thing as GeneratedString = GeneratedString + RandomLetter. We are adding a new letter at the end of the GeneratedString variable.
What is Convert.ToChar()? The function: Rnd.Next(97, 123) generates a random Integer number from 97 to 123 exclusively. We need to convert it to a Char value to make sure we can add it to our String type variable later. What is the relationship between String and Char you say? A String is a special type that is in fact an Array(Table) of Chars values. In our case, the Convert.ToChar converts the result of the Rnd.Next(97, 123) function to a Char using the ASCII table. In the ASCII table, number 97 to 122 designate the letters a to z.
Notice that the Rnd variable is declared and initialized outside of the Sub and Function block but inside of the Module, that makes it a variable accessible to any functions/subs inside that module! (If no Private/Public is added, the variable is Private by default)
Question 2
In the second question, we had to execute the random String generation 100 times. The purpose of the function GenerateRandomString is to generate that random String, we would have to execute this part 100 times. Not by copy-pasting please! Lets use a loop to do that for us!
I used a While loop in that case, here is what you should have in your Main() Sub.
Sub Main() Dim NumberOfCharactersToGenerate = 5 Dim Counter As Integer = 1 Dim RandomString As String = String.Empty While (Counter <= 100) RandomString = GenerateRandomString(NumberOfCharactersToGenerate) Console.WriteLine(RandomString) Counter += 1 End While Console.ReadKey() End Sub
I declare a Counter variable to keep the count of how many words I have generated. The condition for the While loop to exit is that Counter must be Less than or equal to 100. And the Counter is incremented by 1 each time the loop is executed for a total of 100 executions until it exits.
Remember that the loops require practice, a lot of practice. You should try to find more example or exercises if you don’t quite understand what is going on. You can also ask a question in the comments or have a look at my Youtube channel video equivalent! Don’t forget that the breakpoint should now be your new best friend to make sure you understand what the computer does at all time!
No Comments Yet!
You can be first to comment this post!