Problem Set 4 | 15 April 2020 - 22 April 2020 at 10 AM

Below there are 2 nested for loop questions, but please be sure to answer the questions that proceed the ‘#’ in the R code blocks.

Problem 1.

Write a nested for loop that will print the following output:

1

2 2

3 3 3

4 4 4 4

Hint: use the cat function to print correctly.

for (i in seq(1:4)){
  for(j in seq(i)) {
    cat(i, " ")
  }
  cat("\n")
}
## 1  
## 2  2  
## 3  3  3  
## 4  4  4  4
# How many times was the outler loop executed? 4 
# How many times was the inner loop executed? 10

# Which numbers does the inner loop loop over on the third execution of the outler loop and why?  1 2 3 because i = 3, so you are looping over seq(3).

Problem 2.

Count the characters in all these movie titles and print the results one by one to your screen, in this format:

“The title [movie_title] is [X] characters long.”

Hint: Look into the stringr library and its functions to help you complete the task.

library(stringr) 
my_movies = list(c("Dead Poets Society", "Life is Beautiful"),
                 c("Radium Girls", "Parasite"),
                 c("Inception", "Interstellar"))

for (movie_list in my_movies) {
    for (movie_name in movie_list) {
        char_num = str_length(movie_name)
        cat("The title ", movie_name," is ", as.character(char_num), " characters long.")
        cat("\n")
}
}
## The title  Dead Poets Society  is  18  characters long.
## The title  Life is Beautiful  is  17  characters long.
## The title  Radium Girls  is  12  characters long.
## The title  Parasite  is  8  characters long.
## The title  Inception  is  9  characters long.
## The title  Interstellar  is  12  characters long.
# How many times was the outler loop executed? 3
# How many times was the inner loop executed? 6