This is the homework for R Programming Bridge Course - Summer 2018 - Week 1. The assignment has total of 3 questions. Each of the 3 R chunks below are for each question respectively. Question - 1: Write a loop to calculate 12-factorial. This question has been solved using a for loop and then a while loop. In the end I have given the available factorial function to print 12 factorial.
# Question 1 - Factorial of a number e.g. 12 in his case - using for loop
factorial_of_12 <- 1
for (i in 12:1)
{factorial_of_12 <- factorial_of_12 * i
}
factorial_of_12
## [1] 479001600
# Question 1 - 2nd way using while loop
factorial_of_12_2 <- 1
i <- 12
while (i >= 1)
{factorial_of_12_2 <- factorial_of_12_2 * i
i <- i - 1}
factorial_of_12_2
## [1] 479001600
# Question 1 - using the factorial function
factorial_of_12_3 <- factorial(12)
factorial_of_12_3
## [1] 479001600
Question - 2: To create a numeric vector that contains the sequence from 20 to 50 by 5. I have tried to achieve this using 2 ways - 1 using vector multiplication and a vector with sequential numbers, and 2nd using seq function.
# Question 2 - creating a numeric vector that contains the sequence from 20 to
# 50 by 5 - 1st way - using vector multiplication
a_vect <- c(4:10)
b_vect <- 5 * a_vect
b_vect
## [1] 20 25 30 35 40 45 50
# Question 2 - 2nd way - using seq function
a_vect_2 <- seq(from=20, to=53, by=5)
a_vect_2
## [1] 20 25 30 35 40 45 50
This is plot for the vector in question 2
Question - 3: To create a function that takes 3 numbers as input and solve the quadratic equation : ax^2 + bx + c. This function then displays the 2 solutions.
# Question 3 - a function to solve the quadratic equation that takes the input numbers a, b and c, and prints out the 2 solution values
factorial.function <- function(a,b,c)
{
solution1 <- (-1 * b + sqrt(b^2 - 4 *a * c))/(2*a)
solution2 <- (-1 * b - sqrt(b^2 - 4 *a * c))/(2*a)
print(solution1)
print(solution2)
}
factorial.function(1,-2,1)
## [1] 1
## [1] 1