All pastes #895489 Raw Edit

Pascals triangle

public text v1 · immutable
·published 2008-02-07 21:33 UTC
rendered paste body
            bool runReady = false;
            int rows = 0;
            int[] last = new int[1];
            last[0] = 1;
            int[] current = new int[last.Length + 1];

            while (!runReady)
            {
                //Try to parse the number
                Console.Write("Please enter the number of rows: ");
                if (!Int32.TryParse(Console.ReadLine(), out rows))
                {
                    //If we cant, skip the rest with continue
                    Console.WriteLine("Please enter a valid number");
                    continue;
                }

                //If parsed we get out of the loop
                runReady = true;
            }

            Console.WriteLine();
            Console.WriteLine(last[0]);
            //Looping through all of the rows to calculate the next numbers
            for (int i = 0; i < rows + 1; i++)
            {
                for (int j = 0; j < current.Length; j++)
                {
                    current[j] = FindAdditon(last, j);
                    Console.Write(current[j] + " ");
                }
                //Change the current array to the last and reform the array to one size larger
                Console.WriteLine();
                last = current;
                current = new int[last.Length + 1];
            }
        }

        // Finds the upper left and right numbers
        public static int FindAdditon(int[] last, int position)
        {
            int r = 0;

            //Checking the upper right number
                if (last.Length > position)
                    r += last[position];
            //Checking the upper left number
                if (position - 1 >= 0)
                    r += last[position - 1];

            return r;
        }