Week 1 Homework-CUNY MSDS
Q1. Write a loop that calculates 12-factorial
getwd()
## [1] "C:/Users/Emahayz_Pro/Desktop"
setwd("C:/Users/Emahayz_Pro/Desktop")
Calc_factorial <- function (n){
if (n < 0) return (-1) # This will check that n is not negative
if (n == 0) return (1) # This will reurn 1 if n is zero
m <- 1
# Calculating the factorial using Loop
for(i in 1:n){
m <-m*((1:n)[i])
print(m)
}
}
# For any given value such as 12 and the factorial is calculated.
Calc_factorial(12)
## [1] 1
## [1] 2
## [1] 6
## [1] 24
## [1] 120
## [1] 720
## [1] 5040
## [1] 40320
## [1] 362880
## [1] 3628800
## [1] 39916800
## [1] 479001600
Q2. Show how to create a numeric vector that contains the sequence from 20 to 50 by5.
Sequence_numb <- vector() #This is an empty numeric vector
for(i in 20:50){
if(i %% 5 == 0)
{
Sequence_numb <-append(Sequence_numb, i)
}
}
Sequence_numb #Shows sequence of numeric vector from 20 to 50
## [1] 20 25 30 35 40 45 50