Chapter 5 : Function

1(a)

A multiprint function that consists of two arguments n and c that prints n copies of character c.

Multiprint function - function that allows printing multiple objects at once

Function using for-loop

The for-loop (i in 1:n) controls how many times the code runs, executing exactly n iterations (1,2,..,n). During each iteration, print(c) is executed once, so the value of c is printed n times in total.

multiprint <- function(n,c) {
  for (i in 1:n){
    print (c)
  }
}

multiprint(2,"University")
## [1] "University"
## [1] "University"
multiprint(3,1052)
## [1] 1052
## [1] 1052
## [1] 1052

Function using Replication

This function uses rep(c, times = n) to repeat the value c exactly n times and store it as a vector. The print() function then displays the entire repeated vector in a single output, instead of printing line by line.

multiprint2 <- function(n,c) {
  print(rep(c,times=n))
}

multiprint2(2,"University")
## [1] "University" "University"
multiprint2(3,1052)
## [1] 1052 1052 1052
1(b)

An ismultiply function that returns TRUE if the third argument is equal to the multiplication of the first and second argument. The default value of all arguments is 1.

ismultiply - function that checks whether one number is a multiple of another and returns TRUE or FALSE.

ismultiply

  1. An issquare function that returns TRUE if the argument is a square number.
  2. A generatetwice function that generates random numbers from 1 – 10. The function will display the random number generated and return the first random number that generate twice.