Code - Investing - FI

Visual Basic Exercise 3 – More Loops!

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!

The solution will be posted in one day! Good luck!

Next article Visual Basic Exercise 3 Solution - More Loops
Previous article Visual Basic Tutorial 9 - Loops

Related posts