errors in code for addition of two numbers

a=as.numeric(readline(prompt="Enter the value of x: "))
b=as.numeric(readline(prompt="Enter the value of y: "))
print(sum(a,b))

please confirm what is the issue in above code. i just started yesterday :slight_smile:

Your code works for me. What error are you seeing?

> a=as.numeric(readline(prompt="Enter the value of x: "))
Enter the value of x: 5
> b=as.numeric(readline(prompt="Enter the value of y: "))
Enter the value of y: 6
> print(sum(a,b))
[1] 11

When i run it line wise it was working..if i select all the line the below error is coming.

Warning message:
NAs introduced by coercion

print(sum(a,b))
Error in print(sum(a, b)) : object 'b' not found

when you select the script and run it entire, thats equivalent to sending each line to the console.
so the second line of your script is being pushed to the console when the first line of your script is asking you to enter a number, that would cause an error
(imagine running line by line but copy and pasting in the 2nd codeline as your response to the first prompt, thats effectively what is happening)

You can however wrap your interactive code in a function

myfunc <- function()
  {a=as.numeric(readline(prompt="Enter the value of x: "))
b=as.numeric(readline(prompt="Enter the value of y: "))
print(sum(a,b))}

myfunc()

Got it, thx for the help.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.