Difference between revisions of "CSC212 Homework 1 Solution 2014"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- =Problem 2= <br /> <source lang="java"> import java.util.Scanner; public class Hw1_1 { /** * This is the main entry point * @param args the command line arg...")
 
(Problem 2)
Line 6: Line 6:
 
import java.util.Scanner;
 
import java.util.Scanner;
  
 +
/**
 +
* displays the nth row of Pascal's triangle.
 +
*/
 
public class Hw1_1 {
 
public class Hw1_1 {
  
Line 15: Line 18:
 
int[] pascal = new int[10];
 
int[] pascal = new int[10];
 
Scanner userInput;
 
Scanner userInput;
        userInput = new Scanner(System.in);
+
        userInput = new Scanner(System.in);
        System.out.println( "> " );
+
 
        int n = userInput.nextInt();
+
        // 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 row = 1; row <= n; row++) {
 
for (int i = pascal.length - 1; i >= 1; i--)
 
for (int i = pascal.length - 1; i >= 1; i--)
Line 25: Line 31:
 
}
 
}
  
 +
        // display the nth row, one number per line.
 
for (int i = 0; i < n; i++)
 
for (int i = 0; i < n; i++)
 
System.out.println(pascal[i] + " ");
 
System.out.println(pascal[i] + " ");

Revision as of 09:53, 20 September 2014

--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();
	}

}