top of page

Example: Find the factorial of a number 
(Ref:https://www.datamentor.io/r-programming/examples/factorial/)

# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Output

Enter a number: 8 [1] "The factorial of 8 is 40320"

 

Example: Check to see if a number is positive negative or zero  
(Ref:https://www.datamentor.io/r-programming/examples/factorial/)

# In this program, we input a number check if the number is positive or negative or zero 
num = as.double(readline(prompt="Enter a number: "))
if(num > 0) {
print("Positive number")
} else {
if(num == 0) {
print("Zero")
} else {
print("Negative number")
}
}



Output 1
Enter a number: -9.6 [1] "Negative number"


Output 2
Enter a number: 2 [1] "Positive number"

Example: Check for Prime Number
(Ref:https://www.datamentor.io/r-programming/examples/factorial/)

# In this program, we input a number check if the number is positive or negative or zero 
num = as.double(readline(prompt="Enter a number: "))
if(num > 0) {
print("Positive number")
} else {
if(num == 0) {
print("Zero")
} else {
print("Negative number")
}
}



Output 1
Enter a number: -9.6 [1] "Negative number"


Output 2
Enter a number: 2 [1] "Positive number"

Prime Number Check
bottom of page