School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 300,347 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,537 people online right now. Registration is fast and FREE... Join Now!




Pascal's Triangle and Character Patterns

 
Reply to this topicStart new topic

> Pascal's Triangle and Character Patterns

Louisda16th
Group Icon



post 11 Oct, 2007 - 02:23 AM
Post #1


Character Patterns
Finally my first tutorial! I hope it gets accepted. smile.gif
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.

IPB Image

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):

CODE

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


Now you need to know the number of rows:
CODE

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
CODE

    For i = 1 To n
        Print Space(n - i) + String(i, "*")
    Next i


That finishes it. Your entire code should look like this:
CODE

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:
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:
IPB Image
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:
CODE

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:
CODE

    For i = n To 1 Step -1
        Print Space(n - i) + String(i, "*")
    Next i

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

Pascal's Triangle
Now, lets move on to Pascal’s Triangle. It looks like this:
IPB Image
and so on……
There are two ways of finding each term. One is to find the coefficient with the formula:
IPB Image
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:
CODE

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
CODE

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:
CODE

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.
CODE

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:
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, 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:
CODE

    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:
CODE

    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
CODE

            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:
CODE

    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
CODE

CurrRow = NextRow

Basically makes the “next row”, the “current row” for your next iteration.
All this together is:
CODE

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):
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, 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: 1 Nov, 2007 - 10:41 AM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Louisda16th
Group Icon



post 15 Oct, 2007 - 04:43 AM
Post #2
To the mod who accepted this! Thank you very much! I never thought my first tut would be accepted smile.gif.
Go to the top of the page
+Quote Post

PsychoCoder
Group Icon



post 30 Oct, 2007 - 10:43 PM
Post #3
Very nice Louisda16th! And you included a VB6 and VB.Net example which will help many smile.gif
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 1 Nov, 2007 - 05:29 AM
Post #4
Thanx for your compliments man smile.gif.
Go to the top of the page
+Quote Post

Martyr2
Group Icon



post 1 Nov, 2007 - 08:56 AM
Post #5
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. icon_up.gif

smile.gif

This post has been edited by Martyr2: 1 Nov, 2007 - 08:57 AM
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 1 Nov, 2007 - 10:38 AM
Post #6
My bad. Sorry. Thanks for the correction smile.gif. 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.

Changes Made

This post has been edited by Louisda16th: 1 Nov, 2007 - 10:44 AM
Go to the top of the page
+Quote Post

PsychoCoder
Group Icon



post 1 Nov, 2007 - 11:04 AM
Post #7
This has nothing to do with this tutorial but I think I'm going to make a C# version smile.gif
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 3 Nov, 2007 - 04:35 AM
Post #8
QUOTE(PsychoCoder @ 2 Nov, 2007 - 12:34 AM) *

This has nothing to do with this tutorial but I think I'm going to make a C# version smile.gif

That'll be great. I'll try writing one for C.
Go to the top of the page
+Quote Post

miat9473
*



post 15 Feb, 2008 - 12:52 AM
Post #9
what the output of this code>?

whats the output of this code>?
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 15 Feb, 2008 - 05:38 PM
Post #10
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.
Go to the top of the page
+Quote Post

miat9473
*



post 22 Feb, 2008 - 01:26 AM
Post #11
QUOTE(Louisda16th @ 3 Nov, 2007 - 05:35 AM) *

QUOTE(PsychoCoder @ 2 Nov, 2007 - 12:34 AM) *

This has nothing to do with this tutorial but I think I'm going to make a C# version smile.gif

That'll be great. I'll try writing one for C.

Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 22 Feb, 2008 - 02:54 AM
Post #12
Is there something you want to ask?
Go to the top of the page
+Quote Post

born2c0de
Group Icon



post 16 Mar, 2008 - 05:44 AM
Post #13
icon_up.gif

There are a few places where you've forgotten to add ByVal to the second parameter.
vb
Private Function nCr(ByVal n As Integer, r As Integer) As Long

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


Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 16 Mar, 2008 - 04:29 PM
Post #14
Isn't the ByVal default?
Go to the top of the page
+Quote Post

carLisLe0818
*



post 13 Sep, 2009 - 03:47 AM
Post #15
[font=Arial Narrow]
how i wish u could just post the whole codes.
Go to the top of the page
+Quote Post

firebolt
Group Icon



post 14 Sep, 2009 - 02:30 AM
Post #16
Then you would just be copying and pasting, ie. not actually learning anything. Read it and understand why that piece of coding was used.
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 14 Sep, 2009 - 04:22 AM
Post #17
I thought the code was complete!!! dry.gif
Go to the top of the page
+Quote Post

Louisda16th
Group Icon



post 14 Sep, 2009 - 04:22 AM
Post #18
*double posted by mistake*

This post has been edited by Louisda16th: 14 Sep, 2009 - 04:25 AM
Go to the top of the page
+Quote Post

firebolt
Group Icon



post 14 Sep, 2009 - 05:55 AM
Post #19
Yeah, actually after reading it carefully, you have actually posted the whole code. smile.gif
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/7/09 06:04PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month