functions
Title
Question
fib <- function(n)
{
fib[0] <-1
fib[1] <- 1
for (i in 2:n) {
fib[i] <- fib[i - 2] + fib[i - 1]
}
print(fib)
}
fib(5)
pls help
R Functions-in-R 02-03 min 10-20 sec
Answers:
Please modify your code as given below:
--------------------------------------------------------------------------------------------------------------------------------------
fib <- function(n){
x <- vector(mode="numeric", length=n)
x[1] <- 1
x[2] <- 1
for (i in 3:n) {
x[i] <- x[i - 2] + x[i - 1]
}
return(x)
}
fib(5)
-------------------------------------------------------------------------------------------------------------------------------------
Alternatively, you can use the code given below:
-------------------------------------------------------------------------------------------------------------------------------------
n <- as.integer(readline("enter the number "))
fibonacci <- function(n) {
num1 <- 0
num2 <- 1
for(i in 1:n) {
print(num2)
num3 <- num2 +num1
num1 <- num2
num2 <- num3
}
}
fibonacci(n)
-------------------------------------------------------------------------------------------------------------------------------------
Login to add comment