Home Work week # 1

Question 1: Write a loop that calculates 12-factorial
Ans:
num <- 12 # Value that we will find factorial for

# We can also take the input from user and find factorial for any positive integer "n" by replacing 12 with "as.integer(readline(prompt="Enter a number: "))"

factorial <- 1

# In case of taking value from the user Kindly un-comment the next coded section all the way to for loop and also the parenthesis bracket in the last line of the code.

#if(num < 0) {
#print("Sorry, factorial does not exist for negative numbers")
#} else if(num == 0) {
#print("The factorial of 0 is 1")
#} else {

# using for-loop

for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
## [1] "The factorial of 12 is 479001600"
#}
Question 2: Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
Ans:
# Making a sequence by using "seq" function and assigning it to a vector name "num_vector"

num_vector <- seq(20, 50, by = 5)

# Recalling the vector

num_vector
## [1] 20 25 30 35 40 45 50
Question 3: Create the function “quadratic” 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.
Ans:
      # Setting up the function name to quadratic

quadratic <- function (a,b,c)
{
  if(a == 0)
  {
    return ("Cannot be computed, since anything divided 0 is undefined")
  }
  
  else if (is.na (sqrt(b^2 - 4*a*c) < 0 ))
  {
    return ("There are no real roots since it will result in a negative value under root (imaginery nambers)")
  }
  
  else if (sqrt(b^2 - 4*a*c) == 0)
  {
    Sol <- (-b / 2*a)
    return (sprintf("The quadratic equation has only one Solution which is %s",Sol))
  }
  
  else
  {
    Sol1 <- (-b + sqrt(b^2 - 4*a*c)) / (2*a) 
      
    Sol2 <- (-b - sqrt(b^2 - 4*a*c)) / (2*a) 
    
    return (sprintf("Solutions are %s, and %s", 
                    format(round(Sol1,8), nsmall = 8), 
                    format(round(Sol2,8), nsmall = 8)))
  }
  

}
Note : Testing the quadratic function created in Question 3
quadratic(1,11,9)
## [1] "Solutions are -0.89022777, and -10.10977223"
quadratic(1,0,5)
## Warning in sqrt(b^2 - 4 * a * c): NaNs produced
## [1] "There are no real roots since it will result in a negative value under root (imaginery nambers)"
quadratic(1,-6,9)
## [1] "The quadratic equation has only one Solution which is 3"