Prompts:
- Write a function called add_five that takes a number and returns
that number plus 5.
add_five <- function(n){
sum <- 0
sum <- n + 5
return(sum)
}
add_five(4)
## [1] 9
add_five(5)
## [1] 10
- Write a function check_number that takes a number and returns
“Positive” if the number is greater than 0, “Negative” if less than 0,
and “Zero” if equal to 0.
check_number <- function(n){
if(n == 0){
return("Zero")
}else if(n >= 0){
return("Positive")
}else(return("Negative"))
}
check_number(5)
## [1] "Positive"
check_number(0)
## [1] "Zero"
check_number(-5)
## [1] "Negative"
- Write a function sum_of_cubes that uses a for loop to calculate the
sum of the cubes of numbers from 1 to n.
sum_of_cubes <- function(n){
result <- 0
sum <- 0
for(i in 1:n){
result <- i^3
sum <- sum + result
cat("Cube:", result , "| Sum:", sum, "\n")
}
return(paste("Sum of cubes: ", sum))
}
sum_of_cubes(3)
## Cube: 1 | Sum: 1
## Cube: 8 | Sum: 9
## Cube: 27 | Sum: 36
## [1] "Sum of cubes: 36"
- Write a function countdown that uses a while loop to print numbers
starting from n down to 1, and then returns “Blast off!”.
countdown <- function(n){
i <- 0
while(i< n){
print(n)
n <- n-1
}
return("Blast off!" )
}
countdown(5)
## [1] 5
## [1] 4
## [1] 3
## [1] 2
## [1] 1
## [1] "Blast off!"