I am a new web developer and need assistance generating a given output to a problem:
var totalNumberofRows = 5;
var output = '';
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
output += i;
}
console.log(output+' ');
output = '';
}
Output:
1
22
333
4444
55555
Expected Output:
1
22
333
55555
88888888
How would I be able to make my code produce the target output?
For non-sequential numbers you could use an array with the String.repeat method:
[1, 2, 3, 5, 8].forEach(n => console.log(n.toString().repeat(n)));
If you want to output the fibonachi sequence you can do :
let current = 1
let last = 0
for (let i = 0; i < 5; i++) {
console.log(Array(current+last).fill(current+last).join(''))
let toLast = current
current += last
last = toLast
}
Have you intended something similar to the Fibonacci sequence?
var totalNumberofRows = 5;
var output = '';
for (var i = 1; i <= totalNumberofRows; i++) {
var next = fibo(i + 1);
for (var j = 1; j <= next; j++) {
output += next;
}
console.log(output + ' ');
output = '';
}
function fibo(n) {
let result = [0, 1];
for (let i = 2; i <= n; i++) {
const a = result[i - 1];
const b = result[i - 2];
result.push(a + b);
}
return result[n];
}