December 22, 2019

Gehad Gad

CUNY MSDS Winter Bridge

Assignment: 1

Question 1

1- Write a loop that calculates 12-factorial


factorial_function <- function(x = 0) {
 if (x == 0){ print("the factor of zero is: 1" ) 
 return(1) } 
 # Return 1 if x is zero
 else{
 factorial <- 1
 for (i in 1:x) {factorial<- factorial * i}
 message(sprintf("the factorial function result is : %s",factorial))
 return(factorial)
}}
# created a Loop to calculate factorial

factorial_function(3)
#the factorial function result is : 6
#[1] 6

factorial_function(12)
#the factorial function result is : 479001600
#[1] 479001600

Question 2

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

vector <- c(seq(20,50, by = 5))
vector 

## [1] 20 25 30 35 40 45 50

Question 3

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

Quadratic_F <- function (a,b,c) { 

#intializing the quadratic function

   Result1 <- round((−b + sqrt(abs(b**2 − 4*a*c)))/(2*a),digits=3)
   Result2 <- round((−b - sqrt(abs(b**2 − 4*a*c)))/(2*a),digits=3)
   
   Results=c(Result1,Result2)
   message(sprintf("the first result is : %s" ,Result1 ))
   message( sprintf("the second result is : %s" ,Result2 ))
   return (Results)
   
} 

##Calling the Quadratic function with a=2 , b=3 , c=5

Quadratic_F(2,3,5)

#the first result is : 0.642
#the second result is : -2.142
[1]  0.642 -2.142