0

still in the learning stages of R. Trying to setup a basic piece of code that will allow me to have a user enter numbers until they enter "0", at which time the program will sum entries and display to the user. This is what I have so far:

    print ("Enter a number.enter 0 when finished")
    enterednum <-as.integer(readLines(con=stdin(),1))
    finalnum = 0

    while (enterednum != 0){
      print ("Enter another number. enter 0 when finished");
      newnum <-as.integer(readLines(con=stdin(),1));
      finalnum <- (enterednum + newnum)
    }
    print(paste("The sum of your numbers is", finalnum,"."))

The point of the exercise is to use while statements. While the false condition of the While statement (entering "0") works, any time the initial input is anything but 0, I receive a debug error for any lines after the while statement. Been wracking my brain and digging through here, but not been able to figure it out. Any help is appreciated.

A Nico
  • 3
  • 1
  • check out the answers here: https://stackoverflow.com/questions/44012056/r-how-do-i-prompt-the-user-for-input-from-the-console – GordonShumway Nov 09 '18 at 04:51

2 Answers2

0

Your while loop is based on the condition when enterednum != 0. However within the while loop you do not update the enterednum - which meaning it is an infinite loop and would never stop. It would be great if you either change the stoping condition to newnum != 0 or update enterednum inside the loop.

Hope the above helps.

S.Zhong
  • 66
  • 3
  • I'm a klutz...such a simple mistake, and modifying the variables to be able to break the loop worked. Thanks! – A Nico Nov 09 '18 at 14:35
0

Figured out the issue. Thanks to S. Zhong and GordonShumway for the tips! Corrected, working code below.

print ("Enter a number.enter 0 when finished")
enterednum <-as.integer(readLines(con=stdin(),1))
finalnum <- 0

while (enterednum != 0){
  finalnum = (finalnum + enterednum)
  print ("Enter another number. enter 0 when finished");
  enterednum <-as.integer(readLines(con=stdin(),1));
}

print(paste("The sum of your numbers is", finalnum,"."))
A Nico
  • 3
  • 1