Solving Computer Science Algorithms - Pascal Triangle

Submitted by: Submitted by

Views: 630

Words: 561

Pages: 3

Category: Science and Technology

Date Submitted: 10/22/2011 03:10 AM

Report This Essay

Solving Computer Science Problems

This article will explain how to approach scientific computer programming problems.

Let’s work through an example. You get the question to write an algorithm or program to solve “Pascal’s Triangle”. The question might be something like “The user will enter a row number, and then the program must calculate and display the elements of that row in the Pascal Triangle”

Pascal's triangle is a geometric arrangement of the binomial coefficients in a triangle. In plain English this can be explained as “every number in the triangle is the sum of the two numbers above”. The number Zero is always invisible to the left and right of the triangle’s edges. (To read more about Pascal’s Triangle, follow this link: http://en.wikipedia.org/wiki/Pascal's_triangle)

Here are the first few rows of Pascal’s Triangle: (The triangle starts with Row 0 and each row starts with element 0 from left to right)

1

1. 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

Now, to solve this in an algorithm / program, there are always 4 basic ways to approach the problem. The 4 approaches are here listed from generally easiest to advanced, and also generally from worst to best.

1) Hard Coding

2) Iterative

3) Recursive

4) Function

1. Hard Coding

The hard-coded solution is a silly solution! Bad programming! To solve the problem with hard coding, we will store each row as a variable/memory structure and then when required, we return that specific row:

Row0 = ‘1’

Row1 = ‘1 1’

Row2= ‘1 2 1’

etc.

2. Iterative

The iterative approach is in most cases the “model answer”. This is generally a good solid solution. The solution is easy to write, and also easy for someone to understand when reading the code.

We will start with hard-coding only the first row. Then we will iterate calculating through the rows until we are at the required row....