-2

I am trying to create Pascal's Triangle with VB.

Here's my code (It uses Gray's Theroy) :

Dim input As Integer = Val(TextBox1.Text)
Dim rownumber As Integer = 0
Dim columnumber As Integer = 1
Dim x As Integer = 1

Do Until rownumber = input
  Do Until rownumber = columnumber
    Label2.Text = 1
    If rownumber = 0 Then
      x = 1
      Label2.Text = x & " "
    Else
      x = x * ((Math.Abs(rownumber - columnumber)) / (columnumber))
      columnumber = columnumber + 1
      Label2.Text = Label2.Text & " " & x & " "
    End If
  Loop
  columnumber = 1
  rownumber = rownumber + 1
  Label2.Text = x & vbNewLine
Loop

Another Idea, here I am using factorials (through a function) then incrememnting the values of the row and column.. Here's the output:

1
1 2
0 1 3
0 0 1 4
0 0 0 1 5
0 0 0 0 1 6

And the code:

Public Class Form1

Function factorial(ByVal n As Long)
  If (n <= 0) Then
    factorial = 1
  Else
    factorial = n * factorial(n - 1)
  End If
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Label2.Text = Nothing
  Dim input As Integer = Val(TextBox1.Text)

  Dim n As Integer
  Dim r As Integer
  Dim c As Integer
  Dim rnum, cnum As Integer

  For rnum = 0 To input Step +1
    For cnum = 1 To (rnum + 1) Step +1
      c = factorial(cnum) / (factorial(rnum) * factorial(cnum - rnum))
      Label2.Text = Label2.Text & " " & c & " "
    Next
    Label2.Text = Label2.Text & vbCrLf
  Next
End Sub

End Class

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Ds.109
  • 714
  • 8
  • 16
  • 32

1 Answers1

0

This line

Label2.Text = x & vbNewLine

resets the label2 to the default x and lost all the changes you had made.

Another problem is here:

If rownumber = 0 Then
  x = 1
  Label2.Text = x & " "
Else
  x = x * ((Math.Abs(rownumber - columnumber)) / (columnumber))
  columnumber = columnumber + 1
  Label2.Text = Label2.Text & " " & x & " "
End If

where x is only 1 in the first row only, but should be one in the first column ever to make the algorithm works.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
gbianchi
  • 2,129
  • 27
  • 35