• (2 Pages)
• • 1
• 2

Pascal's Triangle and Character Patterns Rate Topic:     //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=35079&amp;s=f41365e5e071edad7992bb340d50a373&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 11 October 2007 - 03:23 AM

Character Patterns
Finally my first tutorial! I hope it gets accepted. This happens to be a problem asked in almost every introductory course in every language. This tutorial aims to help you go about creating all those patterns.

Prerequisites: Youll need to be thorough with loops, nested loops and If  Then.Else , and other similar constructs, arrays and functions. You also need to know about some of VBs intrinsic functions namely Val(), Space() and String().

Lets start with a simple problem of creating a pattern like this. Also suppose that the number of rows can be specified by the user.

To start, create a standard EXE project in VB6 while in .NET create a Windows Application.

Put a command button. This will be used to generate the pattern required.

Now, to write your program, youll have to decide what variables youre going to use. Pretty simple, you need one for holding the number of rows and another for the loop. Put the following code in the buttons click event (The following works for VB6. .NET code is given later. Only a few modifications are required):

Dim n As Integer  'Number of rows
Dim i As Integer 'Counter

Now you need to know the number of rows:
n = Val(InputBox("Enter number of rows"))

And now comes the important part. To write the code, remember that a particular sequence follows for n rows. Each row is printed like this:
Print <certain_number_of_spaces> + <i number of *>
Notice that the number of spaces is the total number of rows minus the current row. This repeats for every row. So your Print statement should be
For i = 1 To n
Print Space(n - i) + String(i, "*")
Next i

That finishes it. Your entire code should look like this:
Private Sub Command1_Click()

Dim n As Integer  'Number of rows
Dim i As Integer 'Counter
n = Val(InputBox("Enter number of rows"))
For i = 1 To n
Print Space(n - i) + String(i, "*")
Next i

End Sub

Now run the program. Enter the number of rows when you click the button and check out the pattern.
To write the program in .NET, youll need a textbox. VB.NET does not have a print statement to print something on a form. So well use a textbox. Add a textbox to your form and use the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer  'Number of rows
Dim i As Integer 'Counter
n = Val(InputBox("Enter number of rows"))
For i = 1 To n
textbox1.text += Space(n - i + 1) + StrDup(i, "*") + vbNewLine
Next i
End Sub

Another small variation in the problem is to print: The key idea here is to use ASCII values of characters. Remember that the ASCII value of A is 65. The other letters follow in order. So change the print statement to:
Print Space(n - i) + String(i, Chr(64 + i))

Notice one thing. The pattern goes hay-wired after E. This is because Letters will have different widths. So you will see that questions dont normally go above D.

You can also have:
For i = n To 1 Step -1
Print Space(n - i) + String(i, "*")
Next i

which prints: Try experimenting with more complicated patterns yourself!!

Pascal's Triangle
Now, lets move on to Pascals Triangle. It looks like this: and so on
There are two ways of finding each term. One is to find the coefficient with the formula: C stands for combination (Permutations and Combinations).
The other way is that each term is got by adding the two numbers directly above it.

Lets start with the first one since its somewhat straightforward (At least thats what Ive felt). Youll need to know about functions for this.

Begin by creating a standard EXE in VB6 and a Windows application in .NET. Add a button.

Well need a function to calculate nCr. Lets call it nCr. Since this function requires that you find a factorial, create one more function called factorial.

The code for each function would be:
Private Function nCr(ByVal n As Integer, r As Integer) As Integer
If (n = r) Then
nCr = 1
Else
nCr = Factorial(n) / (Factorial(n - r) * Factorial(r))
End If
End Function

and
Private Function Factorial(ByVal n As Integer) As Integer
Dim i As Integer
Factorial = 1
If n <> 0 Then
For i = 2 To n
Factorial = Factorial * i
Next i
End If
End Function

That takes care of finding each term. Now all you need to worry about is arranging them. Thats easy since we do it the same way as we did for the * pattern. So add the following last piece of code to finish off:
Private Sub Command1_Click()

Dim n As Integer  'Number of rows
Dim i, j As Integer 'Counters
n = Val(InputBox("Enter number of rows"))
For i = 0 To n
Print Space(n - i);
For j = 0 To i
Print Trim(Str(nCr(i, j))) + " ";
Next j
Print
Next i

End Sub

And that is all you require to do the work. Heres the code posted together.
Private Sub Command1_Click()

Dim n As Integer  'Number of rows
Dim i, j As Integer 'Counters
n = Val(InputBox("Enter number of rows"))
For i = 0 To n-1
Print Space(n - i);
For j = 0 To i
Print Trim(Str(nCr(i, j))) + " ";
Next j
Print
Next i

End Sub
Private Function nCr(ByVal n As Integer, r As Integer) As Long
If (n = r) Then
nCr = 1
Else
nCr = Factorial(n) / (Factorial(n - r) * Factorial(r))
End If
End Function

Private Function Factorial(ByVal n As Integer) As Long
Dim i As Integer
Factorial = 1
If n <> 0 Then
For i = 2 To n
Factorial = Factorial * i
Next i
End If
End Function

In .NET, youll have to use a textbox like before. With a few modifications, the code will look like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer  'Number of rows
Dim i, j As Integer 'Counters
n = Val(InputBox("Enter number of rows"))
For i = 0 To n-1
TextBox1.Text += (Space(n - i))
For j = 0 To i
TextBox1.Text += Trim(Str(nCr(i, j))) + " "
Next j
TextBox1.Text += vbNewLine
Next i
End Sub

Private Function nCr(ByVal n As Integer, ByVal r As Integer) As Long
If (n = r) Then
nCr = 1
Else
nCr = Factorial(n) / (Factorial(n - r) * Factorial(r))
End If
End Function

Private Function Factorial(ByVal n As Integer) As Long
Dim i As Integer
Factorial = 1
If n <> 0 Then
For i = 2 To n
Factorial = Factorial * i
Next i
End If
End Function

Now lets move on to the other way of getting the triangle. As said before, the term required is equal to the sum of the two terms directly above it.
Lets use two arrays: one to store the current row and the other to store the next row. All the declarations would go like this:
Dim n As Integer  'Number of rows
Dim i As Integer, j As Integer  'Counters
Dim term As Integer

Dim CurrRow() As Integer	   'Current Row
Dim NextRow() As Integer	   'Next Row

The two arrays are dynamic. Well need to change their size frequently. Also, apart from storing the required numbers in the row, Ive used a leading and a trailing zero in each row. So row1 is stored as 010, row2 as 0110, row3 as 01210 and so on. This is done to make manipulations a little easier.
Next we ask for the number of rows and also define the initial dimensions of the array. The initial dimensions of CurrRow would be the number of elements in row1 while that of NextRow would be the number of elements in row2 (This includes the extra zeros). Also well initialize the second element of CurrRow to 1. The other elements in both rows will be zero by default. So:
n = Val(InputBox("Enter number of rows"))

ReDim CurrRow(2)
ReDim NextRow(3)
CurrRow(1) = 1

Now heres the main section: Getting the element itself. Look at Pascals triangle again. Lets take 3 rows for simplicity (with the zeros):

Row1: 010
Row2 0110
Row3 01210
Notice that the element of a particular row is got by adding the element of the previous row at the same column position with the element of the previous column position. So to get the required element of the Next Row:
<element of next row at column j> = <element of prev row at column j> + <element of prev row at position j-1>
Well also have to print this element. Hence the code required will be
term = CurrRow(j - 1) + CurrRow(j)
Print term;
NextRow(j) = term

All this needs to be in two loops: one to handle each row and the other for each element in the current row. The second loop is nested within the first. We also need to re-define the dimensions of the two arrays after a particular row has been taken care of. All of this condenses to:
For i = 1 To n
Print Space(n - i);
For j = 1 To i
term = CurrRow(j - 1) + CurrRow(j)
Print term;
NextRow(j) = term
Next j
Print
ReDim CurrRow(i + 2)
CurrRow = NextRow
ReDim NextRow(i + 3)
Next i

The line
CurrRow = NextRow

Basically makes the next row, the current row for your next iteration.
All this together is:
Private Sub Command1_Click()

Dim n As Integer  'Number of rows
Dim i As Integer, j As Integer  'Counters
Dim term As Integer

Dim CurrRow() As Integer	   'Current Row
Dim NextRow() As Integer	   'Next Row

n = Val(InputBox("Enter number of rows"))

ReDim CurrRow(2)
ReDim NextRow(3)
CurrRow(1) = 1

For i = 1 To n
Print Space(n - i);
For j = 1 To i
term = CurrRow(j - 1) + CurrRow(j)
Print term;
NextRow(j) = term
Next j
Print
ReDim CurrRow(i + 2)
CurrRow = NextRow
ReDim NextRow(i + 3)
Next i

End Sub

Similarly, in .NET the code would be (remember to add a textbox as before):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim n As Integer  'Number of rows
Dim i As Integer, j As Integer  'Counters
Dim term As Integer

Dim CurrRow() As Integer	   'Current Row
Dim NextRow() As Integer	   'Next Row

n = Val(InputBox("Enter number of rows"))

ReDim CurrRow(2)
ReDim NextRow(3)
CurrRow(1) = 1

For i = 1 To n
TextBox1.Text += Space(n - i)
For j = 1 To i
term = CurrRow(j - 1) + CurrRow(j)
TextBox1.Text += Str(term)
NextRow(j) = term
Next j
TextBox1.Text += vbNewLine
ReDim CurrRow(i + 2)
CurrRow = NextRow
ReDim NextRow(i + 3)
Next i
End Sub

Thats it. Now run the program, enter the number of rows you want and see the results!

This post has been edited by Louisda16th: 01 November 2007 - 11:41 AM

Is This A Good Question/Topic? 0

Replies To: Pascal's Triangle and Character Patterns

#2 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 15 October 2007 - 05:43 AM

To the mod who accepted this! Thank you very much! I never thought my first tut would be accepted .

#3 PsychoCoder Reputation: 1660
• Posts: 19,853
• Joined: 26-July 07

Posted 30 October 2007 - 11:43 PM

Very nice Louisda16th! And you included a VB6 and VB.Net example which will help many #4 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 01 November 2007 - 06:29 AM

Thanx for your compliments man .

#5 Martyr2 Reputation: 5465
• Posts: 14,418
• Joined: 18-April 07

Posted 01 November 2007 - 09:56 AM

Awesome work man! I just found one minor bug in the first one where you have For = 0 to n which would actually end up giving you one more row than the user asked for since for loops are inclusive it would count 0. So if you specified 6 it would actually execute 7 times and give you 7 rows. The second example with the arrays you start from 1 which does give you the correct number of rows.

Again, minor minor thing.

Great stuff though. Nice tutorial.  This post has been edited by Martyr2: 01 November 2007 - 09:57 AM

#6 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 01 November 2007 - 11:38 AM

My bad. Sorry. Thanks for the correction . I'll go ahead and change it.
EDIT:. Its actually from 0 to n-1. Not 1 to n. Basically I calculate 0C0 as well for the first row which is just a 1.

This post has been edited by Louisda16th: 01 November 2007 - 11:44 AM

#7 PsychoCoder Reputation: 1660
• Posts: 19,853
• Joined: 26-July 07

Posted 01 November 2007 - 12:04 PM

This has nothing to do with this tutorial but I think I'm going to make a C# version #8 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 03 November 2007 - 05:35 AM PsychoCoder, on 2 Nov, 2007 - 12:34 AM, said:

This has nothing to do with this tutorial but I think I'm going to make a C# version That'll be great. I'll try writing one for C.

#9 miat9473 Reputation: 0
• Posts: 2
• Joined: 15-February 08

Posted 15 February 2008 - 01:52 AM

what the output of this code>?

whats the output of this code>?

#10 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 15 February 2008 - 06:38 PM

I have shown what the output should be before I've gone into the code. Look for the triangular patterns of characters. Those are the outputs.

#11 miat9473 Reputation: 0
• Posts: 2
• Joined: 15-February 08

Posted 22 February 2008 - 02:26 AM Louisda16th, on 3 Nov, 2007 - 05:35 AM, said: PsychoCoder, on 2 Nov, 2007 - 12:34 AM, said:

This has nothing to do with this tutorial but I think I'm going to make a C# version That'll be great. I'll try writing one for C.

#12 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 22 February 2008 - 03:54 AM

Is there something you want to ask?

#13 born2c0de Reputation: 187
• Posts: 4,673
• Joined: 26-November 04

Posted 16 March 2008 - 06:44 AM There are a few places where you've forgotten to add ByVal to the second parameter.
Private Function nCr(ByVal n As Integer, r As Integer) As Long

should be
Private Function nCr(ByVal n As Integer, ByVal r As Integer) As Long

#14 Louisda16th Reputation: 15
• Posts: 1,967
• Joined: 03-August 06

Posted 16 March 2008 - 05:29 PM

Isn't the ByVal default?

#15 carLisLe0818 Reputation: 0
• Posts: 1
• Joined: 01-September 09

Posted 13 September 2009 - 04:47 AM

[font=Arial Narrow]
how i wish u could just post the whole codes.

• (2 Pages)
• • 1
• 2

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }