'VB Net Console Loops

How to write a VB net console app using loops for this kind of output:

$$$$$
$$$$
$$$
$$
$
'Declaring the variables
Dim DollarSign As String

DollarSign = "$"

For counter = 5 To 1 Step -1
    Console.WriteLine(DollarSign)
Next

the output shows like this:

$
$
$
$
$

as well this following output:

1$$$$
12$$$
123$$
1234$

I can't figure this out. What's going on here?



Solution 1:[1]

Dim DollarSign as String = "$"

For counter = 5 To 1 Step -1
    Console.WriteLine(New String(DollarSign, counter))
Next

Solution 2:[2]

Right now your code is looping from 5 to 1 and printing the dollar sign once during each iteration.

It sounds like you want the dollar sign to be repeated based on the current index of the loop.

If that's the case then you can create a new string and pass in the dollar sign and the current index:

Dim dollarSign As Char = "$"c
For counter = 5 To 1 Step -1
    Console.WriteLine(New String(dollarSign, counter))
Next

Fiddle: https://dotnetfiddle.net/Ok8NSD

Solution 3:[3]

Another approach using NESTED for loops:

Dim numRows As Integer = 5
For row As Integer = numRows To 1 Step -1
    For col As Integer = 1 To row
        Console.Write("$")
    Next
    Console.WriteLine()
Next
Console.ReadKey()

Output:

$$$$$
$$$$
$$$
$$
$

Second version:

Dim numRows As Integer = 5
For row As Integer = numRows To 1 Step -1
    For col As Integer = 1 To ((numRows + 1) - row)
        Console.Write(col)
    Next
    For col As Integer = 1 To (row - 1)
        Console.Write("$")
    Next
    Console.WriteLine()
Next
Console.ReadKey()

Output:

1$$$$
12$$$
123$$
1234$
12345

Solution 4:[4]

There are just so many ways to do this:

Dim output = "$$$$$"
Do While output.Length > 0
    Console.WriteLine(output)
    output = output.Substring(1)
Loop

That gives:

$$$$$
$$$$
$$$
$$
$

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Coehoorn
Solution 2 David
Solution 3 Idle_Mind
Solution 4 Enigmativity