cs31 lecture 5

For i in 1vsize 1 do 2 for j in i1vsize do for 3 iff

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: easing order) 1. for i in 1..v.size-1 do 2. for j in i+1..v.size do for 3. iff v[i] > v[j] then i 4. tmp := v[j] tmp 5. v[j] := v[i] v[j] 6. v[i] := tmp v[i] 7. endif endif 8. endfor endfor 9. endfor 8 More on for loops x for <iterator> in <lb>..<ub> do Uses only one iterator, which is an integer counter lb and ub defines the range of values this iterator takes Without further argument, it increments by step of 1 for i in 1..10 step 2 => increments by step of 2 x Can be used to scan a set Example: Example: for i in SetA do for 9 While loops x Syntax: while <condition> do <instructions> <instructions> done x In English: “while the condition is true, do the block of In instructions” instructions” x Example: while (i <= 10) do print i print i := i + 1 := done 10 Differences between while loops and for loops x There is no assumption of a loop iterator with while loops x If you use one, the increment must be done explicitly x If the condition of the while loop relates to a loop iterator, If then it can be easily transformed into a while loop then x In general, while loops are less constrained, but requires In more information by the user more 11 Example: keyboard input x Problem: read a number from the user, with a guarantee Problem: that it is an integer number that Algorithm ReadInt: Output: • i: integer number typed by the user 1. str := readFromKeyboard() 2. while (not isInteger(str)) do 3. str := readFromKeyboard() str 4. done 5. return convertStrToInt(str) 12 Do loops x Syntax: do <instructions> <instructions> while <condition> x In English: “do the block of instructions while the In condition is true” condition x Example: do do print i print i := i + 1 := while (i <= 10) while 13 Example: keyboard input x Problem: read a number from the user, with a guarantee Problem: that it is an integer numb...
View Full Document

Ask a homework question - tutors are online