R Workshop Homework 1

Question 1

Write a loop that calculates 12-factorial

Here is my answer for this question:

#loop that calculates 12 factorial

num=1

for(i in 1:12){
  
  num=num*i
  
}

print(num)
## [1] 479001600

Question 2

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

Here is my answer for this question:

# numeric vector 20 to 50 by 5

answer= seq(20,50, by=5)
print(answer)
## [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.

Here is my answer to this question. Please note that depending on the values of a,b,and c; the solution might be imaginary. I adjusted my function to work for any values of a,b,and c. I’ve added a couple of test cases afterwards to demonstrate the function.

Solution:

#function quadratic


quad= function(a,b,c){
  
  r=(b^2)-(4*a*c)
  denom=2*a
  
  #making sure both solution exists first
  if (r>0){
  
    #square root part
    rad= sqrt(r)
  
    #results
    x1=(-b+rad)/denom
    x2=(-b-rad)/denom
  
    print(x1)
    print(x2)
    
  #if the radical is 0, there will be only 1 solution
    
  }else if(r==0){
    denom=2*a
    x=-b/denom
    print(x)
    
  #If the radical is negative, then we are dealing with imaginary numbers  
  }else{
  
    real=-b/denom
    img=(sqrt(-r))/denom
    
    x1=paste(real,'+', img,'i')
    x2=paste(real,'-',img,'i')
    
    print(x1)
    print(x2)
  }
  
}
quad(1,2,1)
## [1] -1
quad(1,6,5)
## [1] -1
## [1] -5
quad(1,1,1)
## [1] "-0.5 + 0.866025403784439 i"
## [1] "-0.5 - 0.866025403784439 i"