Daniel E Carcamo
Daniel E Carcamo

Reputation: 19

For statement nested in while statement not working

I am learning how to use while and for loops, and am having difficulty executing a for loop within a while loop. I am trying to recurse a simple procedure over a vector, and have the while loop set the conditionals for which parts of the vector are operated upon. This is really just meant as an exercise to understand how to use for and while loops in conjunction.

data <- c(1:200)

n=0   

while(n < 100){
for(x in data){
n=x+1
if(x >= 10 & x < 100){
   print("double digit")
} else {
   print("single digit")
}}}

I want to stop the while loop when the procedure hits x=100 of the vector that runs from 1:200. But instead, the for loop runs through every element within the vector, from 1:200, failing to stop executing when n hits 100.

Would appreciate any advice to help out a new coder, thanks.

I have also tried

for(x in data){
n=x+1
while(n < 100){
if(x >= 10 & x < 100){
  print("double digit")
} else {
  print("single digit")
}}}

But the code does not stop executing.

Upvotes: 2

Views: 46

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

First let's try a for loop. Each time through it n will be set to the loop counter plus 1. If this result is between 10 and 100, print a message, if not print something else. Note that no loop depends on n .

data <- c(1:200)

n = 0

for (x in data) {
    n = x + 1
    if (n < 100) {
        if (x >= 10 && x < 100) {
            print("double digit")
        } else {
            print("single digit")
        }
    }
}
x
#[1] 200

n
#[1] 201

Now for a while loop. I believe it is much simpler, it only envolves one variable, n.

n <- 0
while (n < 100) {
    n = n + 1
    if (n < 100) {
        if (n >= 10) {
            print("double digit")
        } else {
            print("single digit")
        }
    }
}
n
#[1] 100

Upvotes: 2

Related Questions