Exercise 7 - Solution
Exercise 7 - Solution
EXERCISE 7
CONDITIONALS AND LOOPS
QUESTIONS
1. Write a for-loop program to print times table of 7 from 1 to 10 as the output below:
[1] "7 * 1 = 7"
[1] "7 * 2 = 14"
[1] "7 * 3 = 21"
[1] "7 * 4 = 28"
[1] "7 * 5 = 35"
[1] "7 * 6 = 42"
[1] "7 * 7 = 49"
[1] "7 * 8 = 56"
[1] "7 * 9 = 63"
[1] "7 * 10 = 70"
2. Write a program that use a nested for-loop (a for-loop inside a for-loop) to generate output as
below:
[1] "1 1"
[1] "1 2"
[1] "1 3"
[1] "1 4"
[1] "2 1"
[1] "2 2"
[1] "2 3"
[1] "2 4"
[1] "3 1"
[1] "3 2"
[1] "3 3"
[1] "3 4"
> x <- matrix(c(28, 35, 13, 13, 1.62, 1.53, 1.83, 1.71, 65, 59, 72, 83), nrow = 4, dimnames =
list(c("Veronica", "Karl", "Miriam", "Peter"), c("Age", "Size", "Weight")))
Age Size Weight
Veronica 28 1.62 65
Karl 35 1.53 59
Miriam 13 1.83 72
Peter 13 1.71 83
Write a for-loop program that generate that output as below: (hint: you can use rownames() and
colnames() in extracting the data)
[1] "The Age of Veronica is 28"
[1] "The Size of Veronica is 1.62"
[1] "The Weight of Veronica is 65"
[1] "The Age of Karl is 35"
[1] "The Size of Karl is 1.53"
[1] "The Weight of Karl is 59"
[1] "The Age of Miriam is 13"
[1] "The Size of Miriam is 1.83"
[1] "The Weight of Miriam is 72"
[1] "The Age of Peter is 13"
[1] "The Size of Peter is 1.71"
[1] "The Weight of Peter is 83"
5. Use a while-loop that print all numbers x as long as x2 is lower than 20, starting with x = 0. The
output is shown as below:
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
Question 1
> for (y in 1:10){
+
+ print(paste(7, '*' , y , '=' , 7*y))
+}
Question 2
> for ( row in 1:3 ) {
+ for ( col in 1:4 ) {
+ print ( paste ( row, col ) )
+ }
+}
Question 3
> for (rname in rownames(x)) {
+ for (cname in colnames(x)) {
+ print(paste("The", cname, "of", rname, "is", x[rname, cname]))
+ }
+}
Question 4
> mat <- matrix(NA_integer_, nrow = 5, ncol = 5)
> for (i in 1:5) {
+ for (j in 1:5) {
+ mat[i, j] <- abs(i - j)
+ }
+}
> mat
Question 5
> x <- 0
> while (x^2 < 20) {
+ print(x)
+ x <- x + 1
+}
Question 6
begin <- 1
while (begin <= 7){
cat('This is loop number',begin, '\n')
begin <- begin+1
print(begin)
}