How to add the rows in pascal's triangle without using an array?
the user should input a row number and the output will be the sum above the input row and the row below the input row.
Assume that the row number is up to 30.
Sample Input:
Enter row no: 4
Output:
Sum of numbers in row 5 is 32.
Sum of all numbers above 4 is 15.
1
Expert's answer
2012-10-25T11:46:30-0400
import java.util.Scanner; public class Test { public static void main(String[] args) { & Scanner console = new Scanner(System.in); & System.out.println("Enter row number: "); & String temp = console.next(); & int neededRow, upperRow, lowerRow = 0; & neededRow = Integer.parseInt(temp); & upperRow = neededRow + 1; & lowerRow = neededRow - 1; & int sum = 0; & int nCk = 1; & & for (int k = 0; k <= upperRow; k++) { & nCk = nCk * (upperRow - k) / (k + 1); & sum += nCk; & } & System.out.println("Sum of number in row " + upperRow + " is " + sum); & & sum = 0; & nCk = 1; & for (int k = 0; k <= lowerRow; k++) { & nCk = nCk * (lowerRow - k) / (k + 1); & sum += nCk; & } & & System.out.println("Sum of all numbers above " + neededRow + " is " & + sum);
Comments
Leave a comment