CSC212 Homework 1 Solution 2014

From dftwiki3
Revision as of 09:53, 20 September 2014 by Thiebaut (talk | contribs) (Problem 2)
Jump to: navigation, search

--D. Thiebaut (talk) 10:50, 20 September 2014 (EDT)


Problem 2


import java.util.Scanner;

/**
 * displays the nth row of Pascal's triangle.
 */
public class Hw1_1 {

	/**
	 * This is the main entry point
	 * @param args the command line arguments.
	 */
	public static void main(String[] args) {
		int[] pascal = new int[10];
		Scanner userInput;
        	userInput = new Scanner(System.in);

	        // ask user for row number
	        System.out.println( "> " );
	        int n = userInput.nextInt();
        
	        // compute Row 1 to n, included, starting at the end of the row.
		for (int row = 1; row <= n; row++) {
			for (int i = pascal.length - 1; i >= 1; i--)
				pascal[i] = pascal[i - 1] + pascal[i];
			pascal[0] = 1;
		}

	        // display the nth row, one number per line.
		for (int i = 0; i < n; i++)
			System.out.println(pascal[i] + " ");
		System.out.println();
	}

}