Week 5: Functions

Prompts:

  1. Write a function called add_five that takes a number and returns that number plus 5.
add_five <- function(x){
  return(x+5)
}

add_five(10)
## [1] 15
add_five(3)
## [1] 8
  1. 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(x){
  if(x > 0){
    return("Postivite")
  } else if(x<0){
    return("Negative")
  }else{
    return("Zero")
  }
}

check_number(9)
## [1] "Postivite"
check_number(0)
## [1] "Zero"
check_number(-30)
## [1] "Negative"
  1. 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 <- total + i^3
  }
  return(total)
}

sum_of_cubes(2)
## [1] 9
sum_of_cubes(5)
## [1] 225
  1. Write a function countdown that uses a while loop to print numbers starting from n down to 1, and then returns “Blast off!”.
count_down <- function(n){
  while(n >= 1){
    print(n)
    n <- n - 1
  }
  return("Blast off!")
}
count_down(2)
## [1] 2
## [1] 1
## [1] "Blast off!"
count_down(50)
## [1] 50
## [1] 49
## [1] 48
## [1] 47
## [1] 46
## [1] 45
## [1] 44
## [1] 43
## [1] 42
## [1] 41
## [1] 40
## [1] 39
## [1] 38
## [1] 37
## [1] 36
## [1] 35
## [1] 34
## [1] 33
## [1] 32
## [1] 31
## [1] 30
## [1] 29
## [1] 28
## [1] 27
## [1] 26
## [1] 25
## [1] 24
## [1] 23
## [1] 22
## [1] 21
## [1] 20
## [1] 19
## [1] 18
## [1] 17
## [1] 16
## [1] 15
## [1] 14
## [1] 13
## [1] 12
## [1] 11
## [1] 10
## [1] 9
## [1] 8
## [1] 7
## [1] 6
## [1] 5
## [1] 4
## [1] 3
## [1] 2
## [1] 1
## [1] "Blast off!"