I learn loops in JavaScript with for-loop and I have this code (j) that does not work with me I don’t know why?
let start = 1;
let end = 6;
let breaker = 2;
for (let i = start; i <= end; i++) {
console.log(i);
for (let j = breaker; j <= end; i++) {
console.log(j);
}
}
You never increase j thus you get endless loop, try replacing
for(let j = breaker; j <= end; i++)
using
for(let j = breaker; j <= end; j+=1)
You changed i and j in inner loop
let start = 1;
let end = 6;
let breaker = 2;
for (let i = start; i <= end; i++)
{
console.log("i => ", i);
for(let j = breaker; j <= end; j++)
{
console.log("j => ", j);
}
}
`
Related
I'm trying to find a shorter way to print a right-triangle and an isosceles triangle without using that many nested loops. Please help, here is my code so far, it works I just have trouble finding a shorter way to write it:
//right-triangle
let triangleStr = "";
let num = 5;
for (let i = 1; i <= num; i++) {
for (let j = 0; j < num - i; j++) {
triangleStr += " ";
}
for (let k = 0; k < i; k++) {
triangleStr += "*";
}
triangleStr += "\n";
}
console.log(triangleStr);
//isosceles-triangle
triangleString = "";
for (let i = 1; i <= num; i++) {
for (let j = 1; j <= num - i; j++) {
triangleString += " ";
}
for (let k = 1; k <= 2 * i - 1; k++) {
triangleString += "*";
}
triangleString += "\n";
}
console.log(triangleString);
If you want to use only one loop, you can use repeat() method in ECMAScript6 or higher.
For Right triangle:
const line = 5;
let rightTriangle = "";
for (let l = 1; l <= line ; l++) {
const indent = line-l;
rightTriangle += `${" ".repeat(indent)}${"*".repeat(l)}${"\n"}`;
}
console.log(rightTriangle);
For Isosceles triangle:
const line = 5;
let isoscelesTriangle = "";
for (let l = 1; l <= line ; l++) {
const indent = line - l;
isoscelesTriangle += `${" ".repeat(indent)}${"*".repeat(2*l-1)}${"\n"}`;
}
console.log(isoscelesTriangle);
I want to print diamond pattern using *. Please find the code below:
for (let i=0; i<num; i++) {
let str="";
for (let j=i; j<num; j++) {
str+="*";
}
console.log(str);
}
for (let i=num; i>0; i--) {
let spaces=num-i;
let spacesStr="";
for (let j=0; j<spaces; j++) {
spacesStr+=" ";
}
let str=spacesStr;
for (let j=i; j>0; j--) {
str+="*";
}
console.log(str);
}
The output of the above code is as below:
****
***
**
*
****
***
**
*
I know that if I start printing both the patterns from line 1 I can achieve the desired output. But not sure how I can do that. Please let me know.
thanks
You've quite figured out the answer already. You will need 3 for loops inside your main loop inorder to get that pattern.
let num = 5;
let string = "";
for (let i = 0; i <= num; i++) {
// printing star
for (let j = 0; j < num - i; j++) {
string += "*";
}
// printing spaces
for (let k = 0; k < i * 2; k++) {
string += " ";
}
// printing stars
for (let l = num - i; l > 0; l--) {
string += "*";
}
string += "\n";
}
console.log(string);
First, we print the left stars, then we print the spaces, and then again we print the right stars.
The idea is to build each line.
First, let's focus on the top half of the diamond.
On the first line, there are n stars, 0 spaces, n stars.
On the second line, there are n-1 stars, 2 spaces, n-1 stars.
On the third line, there are n-2 stars, 4 spaces, n-2 stars.
And the pattern follows till there are 0 stars.
Now, coming to the bottom half of the diamond, the pattern is same, just reversed. So, for the inner loops, you can just change i to n-i and n-i to i.
const n = 5;
const star = "*";
const space = " ";
// Top half of the diagram
for (let i = 0; i < n; i ++) {
let pattern = ''
for (let j = 0; j < (n - i); j++) pattern += star;
for (let j = 0; j < i; j++) pattern += `${space}${space}`;
for (let j = 0; j < (n - i); j++) pattern += star;
console.log(pattern);
}
// Bottom half of the diagram
for (let i = 1; i <= n; i ++) {
let pattern = ''
for (let j = 0; j < i; j++) pattern += star;
for (let j = 0; j < (n - i); j++) pattern += `${space}${space}`;
for (let j = 0; j < i; j++) pattern += star;
console.log(pattern);
}
How to rotate a string in javascript and print the rotated versions of string without using any javascript functions, only for loops.
Given a string:
"hell"
Output:
"lhel", "llhe", "ellh", "hell"
I have tried but not succeded
var str1 = "hell";
let i = 0;
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
temp = str1[len]
while (i < len) {
console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You are almost there ! There is one thing missing, i should be reset at each iteration of the for loop, otherwise, the while (i < len) will be "played" only once :
var str1 = "hell";
let len = str1.length - 1;
let temp;
for (let j = 0; j < len+1; j++) {
let i = 0; // <-------------------- notice this
temp = str1[len]
while (i < len) {
//console.log(str1[i]);
temp += str1[i];
i++;
}
console.log(temp);
//console.log(typeof temp, typeof str1)
str1 = temp;
}
You could take a nested loop and get the characters at the position of i and j and take the reminder operator % for preventing characters outside of the string.
var string = "hell",
i, j,
temp;
for (i = 0; i < string.length; i++) {
temp = '';
for (j = 1; j <= string.length; j++) temp += string[(i + j) % string.length];
console.log(temp);
}
You can try this method. Basically you have two loops the first loop with (i) is for the possibilities the second one is for the shifting
var strValue = "hell";
var temp;
for(var i = 0; i < strValue.length; i++){
temp = "";
for(var j = 1; j < strValue.length; j++){
temp += strValue[j];
}
temp += strValue[0]
strValue = temp;
console.log(strValue)
}
In first loop add all symbols which indexes are greater then amount of shift steps (i in this case).
And add rest symbols after it the second loop.
const str = 'hello';
for (let i = 0; i < str.length; i++) {
let shifted = '';
for (let j = i; j < str.length; j++) {
shifted += str[j];
}
for (let j = 0; j < i; j++) {
shifted += str[j];
}
console.log(shifted);
}
i know this has already been answered so.. this is how i'd do it.
maybe you can learn from it.
const str = "hell";
// this loop will set the offset. so if it's 1, "hell" will become "ellh"
for (let offset = 0; offset < str.length; offset++) {
// this will contain the final string
let output = "";
// here we iterate through all the characters
for (let index = 0; index < str.length; index++) {
// and use modulo to switch 5 to 1 (in case length is 4)
output += str[(index + offset) % str.length];
}
// there we go
console.log(output);
}
let str = 'hell';
for(let i=0;i<str.length;i++){
str = str.substring(1,str.length) + str[0];
console.log(str);
}
the following code goes into infinite loop and a crash in the webpage I need to know what's wrong with it?
for (var i = 0; i < 2; i+1) {
for (var j = i; j < 8; j + 2) {
console.log(arr[j].Qu);
}
console.log(arr[i]);
}
i+1 doesn't update i's value, therefor, the i always has value 1, as it takes 0+1 in every run, thus never being > 2 and never ending
You need to change it with i++, like this
for (var i = 0; i < 2; i++) {
Also, as #Xufox points out, udpate your J loop with
for (var j = i; j < 8; j += 2) {
i+1 is not an assign operation, that's why you need to assign the value urself. i++ and j+=2 translate to
i = i+1;
j= j+2;
and the result of the righthand operation is self-assigned to the variable
Value is not assigned back to variable.
for (var i = 0; i < 2; i+=1) { // i++
for (var j = i; j < 8; j+=2) {
console.log(arr[j].Qu);
}
console.log(arr[i]);
}
i+1 doesn't modify i value.
You could write instead i++.
Similarly, j + 2 doesn't update j.
You should write j += 2.
Here is the corrected code :
for (var i = 0; i < 2; i++) {
for (var j = i; j < 8; j += 2) {
console.log(arr[j].Qu);
}
console.log(arr[i]);
}
for (var i = 0; i < 2; i+=1) {
for (var j = i; j < 8; j+= 2) {
console.log(arr[j]);
}
console.log(arr[i]);
}
Is something wrong with my code? I was expecting my code:
years=new Array();
for (i = 0; i < 5; ++i) {
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
to print something like:
[array[12],array[12],array[12],array[12]]
but the result that i get is:
[array[60],array[60],array[60],array[60]]
Create a new player array inside the first for loop. The problem with your code is that the values were being pushed into the same array instance.
var years = [];
for (i = 0; i < 5; ++i) {
var player = [];
for (j = 1; j < 13; ++j) {
player.push(Math.round( nestedData[i].value[j] ))
}
years.push(player)
}
console.log(years)
As an addition to the correct answer already, please use var to declare your variables:
for (var i=0; i < 5; ++i) {
var player = [];
for (var j = 1; j < 13; ++j) {
...
Otherwise, it will use i as a global variable, which could end poorly if you have two functions looping at the same time, e.g.:
function loopone() {
//wouldn't expect this to be an infinite loop eh?
for (i=0; i < 100; i++) {
looptwo();
}
}
function looptwo() {
for (i=0; i < 10; i++) {
}
}