user6890950
user6890950

Reputation:

How to use continue in a loop to change a value

I am trying to have a loop that gives me values from 1 to 30. However every number divisible by 10 I want to hard code the value to the corresponding word. Example would be value 10 = "Ten", 20 = "Twenty" and so on.

I tried to do this with 'continue', however my displayed results do not go pass "Ten".

    for (i = 0; i <= 30; i++) {
        if (i == 10) {
            i = "Ten";
            continue;
        } if (i == 20) {
            i = "Twenty";
            continue;
        }
        console.log(i);
    }

Results

Am I going on about it the right way? Could you please offer some hints so I can figure this out. Thank you,

I tried this initially. But didn't work.

   for (i = 0; i <= 30; i++) {
      if (i == 10) {
        i = "Ten";       
      } if (i == 20) {
        i = "Twenty"; 
      }
   console.log(i);
   }

Upvotes: 0

Views: 108

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234795

Just get rid of the continue statements. They cause the loop to immediately skip to the end and start another iteration. Thus, your console output statement is skipped. Also, you don't want to touch the loop variable, and it wouldn't hurt to have an else. Something like this:

var result;
for (i = 0; i <= 30; i++) {
    if (i == 10) {
        result = "Ten";
    } else if (i == 20) {
        result = "Twenty";
    } else {
        result = i;
    }
    console.log(result);
}

Or you could just log the desired output directly in each branch of the if/else chain:

for (i = 0; i <= 30; i++) {
    if (i == 10) {
        console.log("Ten");
    } else if (i == 20) {
        console.log("Twenty");
    } else {
        console.log(i);
    }
}

Upvotes: 1

lleaff
lleaff

Reputation: 4309

When the counter i gets to ten, you are replacing it with a string, so when the control flow reaches the i++ part, your loop fails. What you should do is assign the value to be printed to another variable that is only used inside the body of the loop.

Upvotes: 0

Nik
Nik

Reputation: 11

I dont think you can change i and expect it to work as usual. hence as soon as you change the value to "TEN", the loop terminates..!!!!

Upvotes: 0

Related Questions