cs31 lecture 10

10 do ai i done for i in 110 do print ai done 22 more

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: tion contains (usually) a variable, called the loop iterator Example: for i in 1..10 do print i done 21 A new data structure: vectors Loops are often applied on data that can be indexed by the loop iterator These are called vectors (arrays) Example: for i in 1..10 do A[i] := i done for i in 1..10 do print A[i] done 22 More on vectors Usually, can be seen as an ordered collection of variables of the same type The notation [<expr>] is used to determine which element of the vector we access It exists in C++ and in most languages (i.e. arrays) A vector has a size (number of elements), noted vector.size Example: A.size 23 Back to for loops: illustrative example Problem: sort a vector of integer numbers in increasing order 24 Algorithm for sorting Algorithm BubbleSort: Input: • v: vector of integer numbers (unsorted) Output: • v: vector of integer numbers (sorted in increasing order) • for i in 0..v.size-2 do • for j in i+1..v.size-1 do if v[i] > v[j] then • tmp := v[j] • v[j] := v[i] • v[i] := tmp • endif • • endfor • endfor 25 More on for loops 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 Can be used to scan a set Example: for elem in SetA do 26 While loops Syntax: while <condition> do <instructions> done In English: “while the condition is true, do the block of instructions” Example: while (i <= 10) do print i i := i + 1 done 27 Differences between while loops and for loops There is no assumption of a loop iterator with while loops If you use one, the increment must be done explicitly If the condition of the while loop relates to a loop iterator, then it can be easily transformed into a for loop In general, while loops are less constrained, but require more information from the user 28 Example: keyboard input Problem: read a number from the user, with a guarantee that it is an integer number Algorithm ReadInt: Output: • i: integer number typed by the user 1.str := readFromKeyboard() 2.while (not isInteger(str)) do 3. str := readFromKeyboard() 4.done 5.return convertStrToInt(str) 29 Do loops Syntax: do <instructions> while <condition> In English: “do the block of instructions while the condition is true” Exam...
View Full Document

This note was uploaded on 04/03/2014 for the course CS 31 taught by Professor Melkanoff during the Fall '00 term at UCLA.

Ask a homework question - tutors are online