- Write a function called add_five that takes a number and returns
that number plus 5.
add_five <- function(n) {
return(n + 5)
}
add_five(4)
## [1] 9
- 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("Positive")
if(n<0)
return("Negative")
else
return("Zero")
}
check_number(-2)
## [1] "Negative"
check_number(0)
## [1] "Zero"
check_number(5)
## [1] "Positive"
- 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) {
total <- 0
for(i in 1:n) {
total <- i^3 + total
}
return(total)
}
sum_of_cubes(10)
## [1] 3025
- Write a function countdown that uses a while loop to print numbers
starting from n down to 1, and then returns “Blast off!”.
blast_off <- function(n) {
print(n)
while(n != 1) {
n <- n - 1
print(n)
}
return("Blast Off!")
}
blast_off(10)
## [1] 10
## [1] 9
## [1] 8
## [1] 7
## [1] 6
## [1] 5
## [1] 4
## [1] 3
## [1] 2
## [1] 1
## [1] "Blast Off!"