Midterm Help

Author

Matt Crump

Published

February 21, 2023

sum numbers from 1 to 100

sum(1:100)
[1] 5050
#1+2+3+4

a <- 0

for(i in 1:100){
  a <- a+i
}

a
[1] 5050

Write a function to find the sum of all integers between any two values.

function_name <- function(input_name){
  #body where you modify input
  return(name_of_output)
}

# running the function
function_name(some_input)
sum(50:100)
[1] 3825
sum(500:1000)
[1] 375750
sum_sequence <- function(min,max){

  return(sum(min:max))
  
}

sum_sequence(min = 5, max = 100)
[1] 5040
sum_sequence_loop <- function(min,max){
  
  a <- 0
  
  for(i in min:max){
    a <- a+i
  }
  
  return(a)
  
}

sum_sequence_loop(1,10)
[1] 55

Generate 100 random numbers

?runif

 random_numbers <-runif(n = 1000,min=0,max=1000)
 
 hist(random_numbers)

  normal_numbers <-rnorm(n = 1000,0,10)
 
 hist(normal_numbers)

 sample(1:6, 1)
[1] 2

Solve fizz buzz problem

for(i in 1:100) {
  if(i %% 3 == 0 & i %% 5 == 0) {
    print("FizzBuzz")
  } else if(i %% 3 == 0) {
    print("Fizz")
  } else if(i %% 5 == 0) {
    print("Buzz")
  } else {
    print(i)
  }
}
[1] 1
[1] 2
[1] "Fizz"
[1] 4
[1] "Buzz"
[1] "Fizz"
[1] 7
[1] 8
[1] "Fizz"
[1] "Buzz"
[1] 11
[1] "Fizz"
[1] 13
[1] 14
[1] "FizzBuzz"
[1] 16
[1] 17
[1] "Fizz"
[1] 19
[1] "Buzz"
[1] "Fizz"
[1] 22
[1] 23
[1] "Fizz"
[1] "Buzz"
[1] 26
[1] "Fizz"
[1] 28
[1] 29
[1] "FizzBuzz"
[1] 31
[1] 32
[1] "Fizz"
[1] 34
[1] "Buzz"
[1] "Fizz"
[1] 37
[1] 38
[1] "Fizz"
[1] "Buzz"
[1] 41
[1] "Fizz"
[1] 43
[1] 44
[1] "FizzBuzz"
[1] 46
[1] 47
[1] "Fizz"
[1] 49
[1] "Buzz"
[1] "Fizz"
[1] 52
[1] 53
[1] "Fizz"
[1] "Buzz"
[1] 56
[1] "Fizz"
[1] 58
[1] 59
[1] "FizzBuzz"
[1] 61
[1] 62
[1] "Fizz"
[1] 64
[1] "Buzz"
[1] "Fizz"
[1] 67
[1] 68
[1] "Fizz"
[1] "Buzz"
[1] 71
[1] "Fizz"
[1] 73
[1] 74
[1] "FizzBuzz"
[1] 76
[1] 77
[1] "Fizz"
[1] 79
[1] "Buzz"
[1] "Fizz"
[1] 82
[1] 83
[1] "Fizz"
[1] "Buzz"
[1] 86
[1] "Fizz"
[1] 88
[1] 89
[1] "FizzBuzz"
[1] 91
[1] 92
[1] "Fizz"
[1] 94
[1] "Buzz"
[1] "Fizz"
[1] 97
[1] 98
[1] "Fizz"
[1] "Buzz"