# 1.
# Generic function to calculate the factorial of any input integer.
calc.factorial = function(inp){
inpFact = inp
for (ctr in (inp-1):1){
inpFact <- inpFact * ctr
}
print(sprintf("%1.0f Factorial is %1.0f",inp,inpFact))
return(inpFact)
}
# 1. Alternate
# Specific function to calculate the factorial of the number 12.
calc.12factorial = function(){
inpFact = 12
for (ctr in 11:1){
inpFact <- inpFact * ctr
}
print(sprintf("12 Factorial is %1.0f",inpFact))
return(inpFact)
}
# 2.
# A function to create a numeric vector that contains an arithmetic sequence of N terms,
# given the first & last terms, and the common difference.
arithSequence = function(term1, termN, comDiff){
#Find the total number of terms in the sequence
termCount <- (termN - term1)/comDiff + 1
#Create a vector to store the sequence in
mySequence <- 1:termCount
print("The Arithmetic Sequence is: ")
#Calculate, store, and print the terms of the sequence one by one, while looping though the vector
for(i in 1:termCount){
mySequence[i] <- term1+((i-1)*comDiff)
print(sprintf("%d",mySequence[i]))
}
}
# 3.
# A function to solve any quadratic equation specified by the 3 co-efficient terms as inputs to the function
quadratic = function(a,b,c){
sol1 = 0
sol2 = 0
sol1 = (0 - b + sqrt(b^2 - (4 * a * c)))/(2 * a)
sol2 = (0 - b - sqrt(b^2 - (4 * a * c)))/(2 * a)
print(sprintf("Solution to this quadratic equation: x = %1.2f, and x = %1.2f", sol1, sol2))
}
# Call the generic function to calculate the factorial of any number, with input 12.
calc.factorial(12)
## [1] "12 Factorial is 479001600"
## [1] 479001600
# Call the specific function to calculate the fcatorial of 12.
calc.12factorial()
## [1] "12 Factorial is 479001600"
## [1] 479001600
# Call the function to solve a quadratic equation.
quadratic(6,-17,12)
## [1] "Solution to this quadratic equation: x = 1.50, and x = 1.33"
# Call the function to store an arithmetic sequence in a vector and print it.
arithSequence(20,50,5)
## [1] "The Arithmetic Sequence is: "
## [1] "20"
## [1] "25"
## [1] "30"
## [1] "35"
## [1] "40"
## [1] "45"
## [1] "50"