#1 Write a loop that calculates 12-factorial.
x <-1 #define vector first
for (i in 1:12)
{
if(i == 1) x <- 1
else
{
x <- x * i;
}
cat(i,"!=", x, "\n")
}
## 1 != 1
## 2 != 2
## 3 != 6
## 4 != 24
## 5 != 120
## 6 != 720
## 7 != 5040
## 8 != 40320
## 9 != 362880
## 10 != 3628800
## 11 != 39916800
## 12 != 479001600
## The above code helps you to find the factorials from 1 to 12.
## The code below helps you to find the factorial of number 12.
## The question is little unclear so I have put two different codes for this question.
factorial<- function(a){
x <-1
for (i in 1:a)
{
x <- x*((1:a)[i])
}
print(x)
}
factorial(12)
## [1] 479001600
#2 Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
numVector <- as.numeric(c(seq(20,50,5)))
print(numVector)
## [1] 20 25 30 35 40 45 50
##
#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.
QuadFunction <- function(a, b, c)
{
numberSqrt <- b^2 - 4*a*c
if(numberSqrt > 0)
{
x1 <- (-b + sqrt(b^2 - 4*a*c)) / (2*a)
x2 <- (-b - sqrt(b^2 - 4*a*c)) / (2*a)
x <- c(x1, x2)
x
}
else if (numberSqrt == 0)
{
x <- -b/(2*a)
x
}
else
{
"Denominator is less than 0. Sorry, NO RESULTS."
}
}
QuadFunction(1, 5, -8)
## [1] 1.274917 -6.274917