R Markdown

R Bridge Week 1 Assignment

Question 1. Write a loop that calculates 12-factorial

fac <- function(x){
y <- 1
for(i in 1:x){
y <-y*((1:x)[i])
}
print(y)
}
fac(12)
## [1] 479001600

Question 2. Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.

x<-vector(length=6)
j<-1
for (i in seq(20,50,5)){
  x[j]<-i
  j<-j+1
}
print(x)
## [1] 20 25 30 35 40 45 50

Question 3. Create the function “factorial” that takes a trio of input numbers a, b, and c and solve the quadratic equation. The function should print as output the two solutions.

factorial <- function(a,b,c){

if ((b^2-4*a*c) >0) {
    x1<-(-b + sqrt(b^2-4*a*c))/(2*a)
    x2<-(-b - sqrt(b^2-4*a*c))/(2*a)
    result<-c(x1,x2)
    print(result)
}
else if (b^2-4*a*c==0) {
    x=-b/(2*a)
    result<-c(x)
    print(result)
}

else if (b^2-4*a*c <0) {
  print("Real roots not defined for the equation")
} 

}

factorial(1,1,1)
## [1] "Real roots not defined for the equation"