Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Loops10-10-2011Opening DiscussionMinute essay commentsMidterm covers topics through today.IcP selection is weighted by how many you have left to do.while LoopThe simplest loop is the while loop.while(condition) st at ementThe condition is evaluated first. If it is true the statement (possibly a block) executes.This repeats until the condition is false.do-while LoopThe partner to the while loop is the do-while loop.do {statement} while(condi t ion)This loop is post-check instead of the pre-check of the normal while loop.Always happens once.The while loop might never happen.The for LoopThe most commonly used loop in most languages is the for loop. The Scala version is a bit different from most.Often used for counting:for(i <- 1 to 10) { ... }In general it is a “for each” loop that goes through a collection.for(e <- coll) { ... }Variable takes on value of each element in the collection.Range TypeRange types provide an easy way to make collections for counting.“to” and “until” operate on numeric types to produce ranges.1 to 100 until 10Use “by” to change the stepping in a range.1 to 100 by 210 to 1 by -1'a' to 'z' by 3yieldThe for loop can be used as an expression if you put yield between the end of the for and the expression after it.for(e <- coll) yield ex prWhat you get back will be a collection that is generally of the same type as what you iterated over.if GuardsYou can put conditions in the for that will cause some values to be skipped.for(n <- nums; if(n%2==0)) ...Multiple GeneratorsYou can also put multiple generators in a for loop.for(i <- 1 to 10; j <- i to 10) ...You can combine as many generators and guards as you want. You can also declare variables in the middle of the for.The thing you assign into is like a val so it can be a “pattern”. We have only seen this with tuples so far.Multidimensional ArraysYou can have collections of collections. A common example would be something like Array[Array[Double]] to represent a matrix.Both fill and tabulate can be used to make these.val ident=Array.tabulate(3,3)((i,j) => if(i==j) 1.0 else 0.0)Minute EssayAny questions?Midterm is on Wednesday. The review session will be 5:00-6:00pm Monday here and 7:00-8:00 Tuesday on
View Full Document