Day 58: Pattern using loops of 100DaysCodingChallenge
Hello all,
#day58
Day58
Today's my task was to Print the below Pattern using loops.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
I have started the 100 days of coding challenge to improve my programming skills..
Code :
let a = prompt("Enter a number : "); let numRows = a; var generate = function(numRows) { let triangle = [[1], [1,1]] if(numRows === 0){ return [] } else if(numRows == 1){ return [[1]] } else if(numRows == 2){ return [[1], [1,1]] } else { for(let i = 2; i < numRows; i++){ addRow(triangle) } } return triangle }; var addRow = function(triangle){ let previous = triangle[triangle.length - 1] let newRow = [1] for(let i = 0; i < previous.length - 1; i++){ let current = previous[i] let next = previous[i+1] newRow.push(current + next) } newRow.push(1) return triangle.push(newRow) } //console.log(generate(a)); const pascalTriangle = n => { const arr = [] for (let i = 0; i < n; i++) { const row = [1] for (let j = 1; j < i; j++) { row.push(arr[i-1][j-1] + arr[i-1][j]) } if( i > 0 ) row.push(1) arr.push(row) } return arr } console.log(pascalTriangle(a));
Output :
Happy Coding:)
Thank you...
Comments
Post a Comment