0

I have noticed that an if-else condition does not work if else is on the next line, as follows. Isn't this bad?

i = 4;
if(i<5)
{
print("less than 5")
}
else
{
print ("greater than or equal to 5")
}

This can be corrected as follows

i = 4;
if(i<5)
{
print("less than 5")
}else
{
print ("greater than or equal to 5")
}

However, the same works(placing 'else' in the next line after 'if') if it's inside a for loop.

i = 0;
for(i in 1:10)
{
 if(i<5)
 {
  print("less than 5")
 }
 else
 {
  print ("greater than or equal to 5")
 }
}
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
IAMTubby
  • 1,627
  • 4
  • 28
  • 40
  • 7
    From `?"if"`, *...you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source.* – Rich Scriven Dec 13 '14 at 04:38
  • @RichardScriven , thanks. But why does the same work inside the for loop? – IAMTubby Dec 13 '14 at 04:56
  • Because the interpreter was waiting for you to close the `for` loop brackets, so everything inside has been defined completely by the time you close the loop. Whereas at the prompt, once you close the first set of `if` brackets, the interpreter interprets that as the end of the statement. The answer in the linked question explains that as well – Rich Scriven Dec 13 '14 at 04:59

0 Answers0