Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pascal's Triangle question
#1
Can anyone help me in forming a pascal triangle?

This is what i got so far, i've only been able to show a specific row,
the formula for calculating an element in pascal triangle is
nCr = n!/ r!(n-r)!
n is the number of row
r is the element we're looking for

In my code :
n is n
n! is j
r! is k
(n-r)! is m
and x is to show elements containing in n row

Code:

Code:
DIM r AS STRING
CLS

INPUT "Enter the number of row"; n
IF n = 0 THEN
PRINT 1
GOTO 1
END IF

j = 1
DO
i = i + 1
j = j * i
LOOP UNTIL i = n
PRINT
PRINT 1;
  
k = 1
DO
  l = l + 1
  k = k * l
     m = 1
    FOR g = n - l TO 1 STEP -1
    m = m * g
    NEXT g
    x = j / (k * m)
    PRINT x;
LOOP UNTIL l = n

PRINT 1

1 END


my question is, how do i repeat this process from 1 to n?
so if i input 5, it'd show

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

instead of just "1 5 10 10 5 1" like my program does
i've tried using for next and do while, but i still can't get it to work.. help anyone?
Reply
#2
You can place everything inside a SUB and call it many times. This would be the "easy" way to solve this, although you should work to get this without using SUBs:

Code:
Declare Sub DrawPascalTriangleLine (n As Integer)

Cls
Print "Row number: ";
Input rowNumber%

For i% = 0 To rowNumber%
   DrawPascalTriangleLine i%
Next i%

End


Sub DrawPascalTriangleLine (n As Integer)

DIM r AS STRING

IF n = 0 THEN
  PRINT 1
  Exit Sub
END IF

j = 1
DO
  i = i + 1
  j = j * i
LOOP UNTIL i = n
PRINT
PRINT 1;
  
k = 1
DO
  l = l + 1
  k = k * l
    m = 1
    FOR g = n - l TO 1 STEP -1
      m = m * g
    NEXT g
    x = j / (k * m)
    PRINT x;
LOOP UNTIL l = n

PRINT 1

End Sub

Untested, but you get the idea. I just pasted your code inside a SUB and called it from the main section .
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#3
Please only post topics in one forum. Everyone who reads this forum most likely reads the Beginner forum as well. Thanks.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)