Program4:
# Recursive function to calculate the factorial
fact = function(n) {
if (n == 0) {
return(1)
} else {
return(n * fact(n - 1))
}
}
# Input a number from the user
n = [Link](readline("Enter a non-negative integer: "))
if (n < 0) {
cat("Factorial is not defined for negative numbers.\n")
} else {
result = fact(n)
cat("The factorial of", n, "is", result, "\n")
}
Explaination:
Like other programming languages in R it’s also possible to take input from the
user. For doing so, there are two methods in R.
Using readline() method
Using scan() method
Using readline() method
In R language readline() method takes input in string format. If one inputs an
integer then it is inputted as a string, lets say, one wants to input 255, then it will
input as “255”, like a string. So one needs to convert that inputted value to the
format that he needs. In this case, string “255” is converted to integer 255.
To convert the inputted value to the desired data type, there are some functions
in R,
[Link](n); —> convert to integer
[Link](n); —> convert to numeric type (float, double etc)
[Link](n); —> convert to complex number (i.e 3+2i)
[Link](n) —> convert to date …, etc
Syntax:
var = readline();
var = [Link](var);
Note that one can use “<-“ instead of “=”
Syntax:
var1 = readline(prompt = “Enter any number : “);
or,
var1 = readline(“Enter any number : “);
Using scan() method
Another way to take user input in R language is using a method,
called scan() method. This method takes input from the console. This method is
a very handy method while inputs are needed to taken quickly for any
mathematical calculation or for any dataset. This method reads data in the form
of a vector or list. This method also uses to reads input from a file also.
Syntax:
x = scan()
scan() method is taking input continuously, to terminate the input process, need
to press Enter key 2 times on the console.
Example:
This is simple method to take input using scan() method, where some integer
number is taking as input and print those values in the next line on the console.
For loop
For loop is used to iterate the elements over the given range. We can use for
loop to append, print, or perform some operation on the given range of integers.
Consider the below syntax of the for loop that also contains some range in it.
Syntax:
for(iterator in range) {
# statements
}
where,
range is the range of values that contains start:stop
iterator is available used to iterate the elements over the given range
R if statement
The syntax of if statement is:
if (test_expression) {
statement
}
If test_expression is TRUE, the statement gets executed. But if it's FALSE,
nothing happens.
if else statement
The syntax of if else statement is:
if (test_expression) {
statement1
} else {
statement2
}