Array Exercises

Mild Practice

Calculate Daily Pay

Trisha gets paid $22 each time she walks a dog. The array below holds 7 numbers, the number of dog walks she took each day last week. Iterate over the array, and print out "Trisha earned $____ today!" for each day.

var dogWalks = [4, 5, 2, 2, 6, 1, 3]

YELLING

Iterate over an array of strings. For each string, print out the YELLING version of it. Look into how to convert a string to uppercase!

Medium Practice

Sum of All

Write a function that takes one argument, an array of Integers. No empty arrays will be passed in. The function should return the sum of all of the numbers in an array. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 145.

Calculate Total Pay

Trisha gets paid $22 each time she walks a dog. The array below holds 7 numbers, the number of dog walks she took each day last week. Write a function that calculates her total pay.

var dogWalks = [4, 5, 2, 2, 6, 1, 3]

Spicy Practice

Sum of Two

Write a function that takes one argument, an array of Integers. No empty arrays will be passed in. The function should return the sum of the two lowest positive numbers given an array of minimum 4 integers. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

Find the Odd (or Even) One Out

Write a function that takes in one argument, an array of Integers. The array must have at least 3 elements. All numbers except for one of them will be either even or odd. You job is to return that one number that is the exception. Below are some example inputs and outputs. Make sure your function works on them all.

Input: [1, 3, 5, 6], Output: 6

Input: [10, 15, 20, 30, 40, 50], Output: 15

Input: [19, 5, 42, 1, 77], Output: 42

Explore

Take the following steps using the code snippet below.

  • What do you think index stands for in the code?
  • Can you figure out what is happening after the in keyword?
  • Take a few minutes to jot down your thoughts and guesses! Then try it out in an Xcode Playground.
var animals = ["red panda", "penguin", "polar bear"]

for index in 0..<animals.count {
  print("I love \(animals[index])")
}