Question How do I make a triangle using a listbox?

gameclub

New member
Joined
Jan 29, 2009
Messages
1
Programming Experience
Beginner
I have been trying to make a triangle using a listbox for quite a while now, I know how to make the top half, but can't make the bottom half. Here are th exact instructions:

Write a program that will ask the user to input a key (letter, number, symbol, etc.) AND a number that will indicate the “size” that will be used to create something like the following display.


Z
ZZ
ZZZ
ZZZZ
ZZZZZ
ZZZZZZ
ZZZZZ
ZZZZ
ZZZ
ZZ
Z


This above example would use the letter “z” and the number (size) that is inputted is 7.

Here's my code:

Public Class Form1
Inherits System.Windows.Forms.Form
Dim number As Integer
Dim num As Integer
Dim X As Integer
Dim output As String
Dim Z As Integer
Dim input As String

+Windows form designer generated code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
'To make the top half of the triangle
number = Val(TextBox1.Text)
If number > 100 Then
MsgBox("Please choose a number less than 100")
Else : For X = 1 To number
output += TextBox2.Text
ListBox1.Items.Add(output)

Next X
number = 0
X = 0
output = ""
TextBox1.Text = "0"
End If

Just to let you know:
I'm using a listbox, two textboxes, and a button to make the program work.

I'm using visual basic.net 2003.
 

MattP

Well-known member
Joined
Feb 29, 2008
Messages
1,206
Location
WY, USA
Programming Experience
5-10
Using a ListBox, 2 Textboxes, and a Button.

Creating an ArrayList to hold the values while in the loop and adding it to the ListBox at the end using AddRange.

Inserting the letter twice in the middle of the ArrayList (once for beginning and once for the end).

1st itteration

Z
Z

2nd itteration

Z
ZZ
ZZ
Z

6th itteration

Z
ZZ
ZZZ
ZZZZ
ZZZZZ
ZZZZZZ
ZZZZZZ
ZZZZZ
ZZZZ
ZZZ
ZZ
Z

You'll have 1 extra element in the middle of the ArrayList that needs to be removed so your triangle comes to a point.

It would be less resource intensive to write a routine to fill in the 1st half of the triangle and another to do the 2nd rather than inserting into the ArrayList. I'll leave that part to you. :)

Code:
	Private Sub uxProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles uxProcess.Click

		uxDisplayResults.Items.Clear()

		Dim maxLength As Integer = Integer.Parse(uxNumber.Text)
		Dim letter As String = uxLetter.Text
		Dim myArrayList As New ArrayList(2 * maxLength)

		If maxLength < 100 Then
			For i As Integer = 0 To maxLength - 1
				myArrayList.Insert(i, letter.PadLeft(i + 1, letter))
				myArrayList.Insert(i, letter.PadLeft(i + 1, letter))
			Next

			myArrayList.RemoveAt(maxLength)
			myArrayList.TrimToSize()

			uxDisplayResults.Items.AddRange(myArrayList.ToArray)
		Else
			MessageBox.Show("Please enter a number less than 100")
		End If

	End Sub
 
Top Bottom