#' @example
#' ## Printing Numbers
#'
#' R has a built-in function called `seq` that creates a list of numbers:
#'
#' 
seq(3)

#' Using `seq`, write a function that prints the first **N** natural numbers, one per line:
#'
#' 
#' ~~~
#' print_N(3)
#' ~~~
#' {: .language-r}
#' 
#' 
#' 
#' ~~~
#' [1] 1
#' [1] 2
#' [1] 3
#' ~~~
#' {: .output}
#'
#' > ## Solution
#' > ~~~
#' > print_N <- function(N) {
#' >   nseq <- seq(N)
#' >   for (num in nseq) {
#' >     print(num)
#' >   }
#' > }
#' > ~~~
#' > {: .language-r}
#' {: .solution}
{: .challenge}

#' ## Summing Values
#'
#' Write a function called `total` that calculates the sum of the values in a vector.
#' (R has a built-in function called `sum` that does this for you.
#' Please don't use it for this exercise.)
#'
#' 
#' ~~~
#' ex_vec <- c(4, 8, 15, 16, 23, 42)
#' total(ex_vec)
#' ~~~
#' {: .language-r}
#' 
#' 
#' 
#' ~~~
#' [1] 108
#' ~~~
#' {: .output}
#'
#' > ## Solution
#' > ~~~
#' > total <- function(vec) {
#' >   # calculates the sum of the values in a vector
#' >   vec_sum <- 0
#' >   for (num in vec) {
#' >     vec_sum <- vec_sum + num
#' >   }
#' >   return(vec_sum)
#' > }
#' > ~~~
#' > {: .language-r}
#' {: .solution}
{: .challenge}

#' ## Exponentiation
#'
#' Exponentiation is built into R:
#'
#' 
#' ~~~
#' 2^4
#' ~~~
#' {: .language-r}
#' 
#' 
#' 
#' ~~~
#' [1] 16
#' ~~~
#' {: .output}
#'
#' Write a function called `expo` that uses a loop to calculate the same result.
#'
#' 
#' ~~~
#' expo(2, 4)
#' ~~~
#' {: .language-r}
#' 
#' 
#' 
#' ~~~
#' [1] 16
#' ~~~
#' {: .output}
#'
#' > ## Solution
#' > ~~~
#' > expo <- function(base, power) {
#' >   result <- 1
#' >   for (i in seq(power)) {
#' >     result <- result * base
#' >   }
#' >   return(result)
#' > }
#' > ~~~
#' > {: .language-r}
#' {: .solution}
{: .challenge}


carpentries/pegboard documentation built on Nov. 13, 2024, 8:53 a.m.