Q1: Write a loop that calculates 12-factorial.
A1:
factorial <- 1
for (i in 1:12)
{
factorial <- factorial * i
}
print(factorial)
A1 Output: 479001600
Q2: Show how to create a numeric vector that contains the sequence
from 20 to 50 by 5.
A2.1:
sequence <- seq(from = 20, to = 50, by = 5)
print(sequence)
A2.1 Output: [1] 20 25 30 35 40 45 50
A2.2:
class(sequence)
A2.1 Output: [1] "numeric"
Q3:Create the function “quad” 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.Please run and test your answer for (1,2,1),
(1,6,5) and (1,1,1).
A3.1:
quad <- function(a, b, c) {
d <- b^2 - 4 * a * c
r1 <- (-b + sqrt(d)) / (2 * a)
r2 <- (-b - sqrt(d)) / (2 * a)
sprintf("Plus result: %s and Minus result: %s", r1, r2)
}
a <- 1
b <- 5
c <- 6
quad(a, b, c)
A3.1 Output: [1] "Plus result: -2 and Minus result: -3"
A3.2:
Test (1,2,1)
a <- 1
b <- 2
c <- 1
quad(a, b, c)
Output: [1] "Plus result: -1 and Minus result: -1"
Test (1,6,5)
a <- 1
b <- 6
c <- 5
quad(a, b, c)
Output: [1] "Plus result: -1 and Minus result: -5"
Test (1,1,1)
a <- 1
b <- 1
c <- 1
quad(a, b, c)
Output: [1] "Plus result: -0.5 and Minus result: -0.5"