Unit 4 - Loops & Algorithms

Unit 4 - Loops & Algorithms#

Topics#

  • for

  • while

  • do while

  • break, continue

Examples#

// return index of first occurrence of E
int findE(String s) {}

// return the number of Es in the string
int countE(String s) {}

// return sum 1 + ... + n
int sum(int n) {}

// return the String obtained by killing every other letter
String binimate(String s) {}

Demo#

Extra practice#

  1. Write a function to interlace 2 strings:

interlace("abc", "123") -> "a1b2c3"
interlace("bed", "ras") -> "breads"
  1. Write a function to find the position of the 2nd “a” in a string:

find2nd("banana") -> 3
find2nd("happy birthday") -> 12
  1. Write a function to add a specified number of “na” strings to “ba”:

addNa(0) -> "ba"
addNa(1) -> "bana"
addNa(2) -> "banana"
addNa(3) -> "bananana"
  1. Write a function to calculate the sum of powers of 2:

sumPowers(0) -> 0
sumPowers(1) -> 0+1 = 1
sumPowers(2) -> 0+1+2 = 3
sumPowers(3) -> 0+1+2+4 = 7
sumPowers(4) -> 0+1+2+4+8 = 15