Here is the code to display pyramid but its not exactly producing required output.
**You can FRAME for loop conditions for any patterns given either it may be a triangle, right-angled triangle, inverse triangle, etc.. For more info refer the below code and workbook image. PS: in work book image in step 6 it is 2 + i and not 3+i therefore j >= 4 - i && j <= 2 + i for any number of rows n formula is : j >= n+1 - i && j <= n - 1 + i **
1, 3, 5, 7, 9 =>
Odd number series (stars) appear in pyramid pattern
1, 2, 3, 4, 5 =>
Counter (number of rows)
For each counter there exist
(2 * n) - 1
value
function pyramid(n) { // Input or number of rows
for (var i = 1; i <= n; i++) {
var s = "";
// For every each counter there exist 2*n-1 value
for (var j = 1; j <= (2 * n - 1); j++) {
// Hint: Check the workbook image
(j >= n + 1 - i && j <= n - 1 + i) ? s += "*" : s += " ";
}
console.log(s);
}
}
pyramid(5);
For your requirements, the following code should be fine:
function generateNumberTriangle(v) {
for (var i = 1; i <= v; i++) {
var chars = " ";
for (var j = 1; j <= v; j++) {
if (j <= i) { chars += j + " "; }
}
console.log(chars);
}
}
generateNumberTriangle(7);
Simple code of Number Pyramid
for(var i=1; i<=5; i++){
var Num='';
for(var j=0; j<i; j++){
Num += i;
}
print(Num) }
Assuming you want to return numbers and not asterisks as the other answers show, here is that solution:
Note that this solution runs in linear (O(n)) time complexity and doesn't sacrifice performance by logging every line to the console, but the entire pyramid at once instead.
function generatePyramid(n) {
let pyramid = '';
let prev;
for (let i = 1; i <= n; i++) {
if (prev) {
pyramid += '\n';
prev = prev + ' ' + i;
} else {
prev = i;
}
pyramid += ' '.repeat(n - i) + prev;
}
return pyramid;
}
Log to the console as such: console.log(generatePyramid(n));
If you're looking to just draw a triangle as the picture in your question shows, this function will do that (again, in linear time complexity):
function drawTriangle(n) {
let triangle = '';
let prev;
for (let i = 1; i <= n; i++) {
if (prev) {
triangle += '\n';
prev = prev + ' ' + i;
} else {
prev = i;
}
triangle += prev;
}
return triangle;
}
If you want to print out a right angle triangle using symbols or single digits. You can use the following code.
let pyramid = '';
for(pyramid.length=0; pyramid.length<=7 ; pyramid+='#'){
console.log(pyramid);
}
Why not this ?
let printPyramid = (n) => {
if (n===0) {
return false;
} else {
let arr = [];
for(let i=0; i<n; i++) {
arr.push(i);
console.log(arr.toString());
}
}
}
You should generate an array on every row iteration and output it at the end:
function generatePyramid() {
var totalNumberofRows = 5,
arr;
for (var i = 1; i <= totalNumberofRows; i++) {
arr = [];
for (var j = 1; j <= i; j++) {
arr.push(j);
}
console.log(arr.join(" ") + "\n");
}
}