Q1. Write a loop that calculates 12-factorial.

factorial <- 1

for (i in 1:12) {factorial <- factorial * i}
  
print(factorial)

#alternatively... 
#cat()=concatenate  
#\n=escape sequence that starts a new line
#escape sequences let you control the format & spacing of a string
factorial <- 1

for (i in 1:12) {
  factorial <- factorial * i
  cat(i, "!", factorial, "\n")
  }
## [1] 479001600
## 1 ! 1 
## 2 ! 2 
## 3 ! 6 
## 4 ! 24 
## 5 ! 120 
## 6 ! 720 
## 7 ! 5040 
## 8 ! 40320 
## 9 ! 362880 
## 10 ! 3628800 
## 11 ! 39916800 
## 12 ! 479001600

Q2. Show how to create a numeric vector that containes the sequence ##from 20 to 50 by 5.

numvec <- as.numeric(seq(from=20, to=50, by=5))

print(numvec)
## [1] 20 25 30 35 40 45 50

Q3. 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.

Quadratic Equation: \[ax^2 + bx+c = 0\]

Solution: \[x= -b +-sqrt(b^2-4ac) / 2a\]

factorial <- function(a, b, c)
{
  # real or imaginary
  inner <- b^2 - 4 * a * c
  
  # if real
  if (inner > 0)
  {
    pos <- (b * (-1) + sqrt(inner)) / (2 * a)
    neg <- (b * (-1) - sqrt(inner)) / (2 * a)
    ans <- c(pos, neg)
    return(ans)
  } else
    # Or the answer is complex
  {
    pos <- (b * (-1) + sqrt(as.complex(inner))) / (2 * a)
    neg <- (b * (-1) - sqrt(as.complex(inner))) / (2 * a)
    ans <- c(pos, neg)
    return(ans)
  }
}

factorial(1, 9, 4)
## [1] -0.4688711 -8.5311289