1. Write a program in Java that allows the user to enter a number and then display its Pascal’s Triangle -The triangle is bordered by ones on the right and left sides, and each interior entry is the sum of the two entries above.
Sample Input/Output:
Please enter a value for Triangle: 6
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Solution:
import java.io.*; import java.util.*; public class Triangle
{
public static void main(String a[]) throws Exception { Scanner pasS = new Scanner(System.in); int pascalN; System.out.print("\nPlease enter a value for Triangle: "); pascalN = pasS.nextInt(); int[][] pascalA; if (pascalN > 0){ pascalA = pascalsTriagnle (pascalN); int space = pascalN; for (int pC=0; pC<pascalA.length; pC++) { space(space); for (int pC2=0; pC2<pascalA[pC].length; pC2++){ System.out.print(pascalA[pC][pC2]+" "); } space(space); space--; System.out.println(""); } } } public static int[][] pascalsTriagnle (int n) { int[][] newPA = new int[n][]; int mycounter = 1; for (int npc = 0; npc<n; npc++){ newPA[npc] = new int[mycounter]; for (int npc0 = 0; npc0<=npc; npc0++){ if (npc0==0 || npc==npc0){ newPA[npc][npc0] =1;} else { int firstN = newPA[npc-1][npc0]; int secondN = newPA[npc-1][npc0-1]; newPA[npc][npc0] =firstN+secondN; } } mycounter++; } return newPA; } public static void space (int n){ // For spacing... for (int x = 0; x<n; x++){ System.out.print(" "); }
}
2. “Guess the Number” using Java.
Welcome to the Guess the Number!
Guess the number from 1 - 100.
Your Guess Number: 65
The number is greater than