cs31 lecture 17

10 do print i print i i 1 done x having a loop upper

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: t all programs contain loops x Typical uses: Traverse input data Do a repetitive treatment Sort an array … 38 Different kinds of loops x For loop (algo, C++)
 x Do loop (algo, C++)
 x While loop (algo, C++)
 x Repeat until loop (algo)
 39 Why multiple kinds of loops? x Technically, all three can be expressed with a while loop x Other loop kinds are syntactic sugar x But, depending on the exact behavior expected, one kind But, of loop will lead to the most clear / most compact code of 40 Typical errors x Writing the loop iterator in the loop body for a for loop Example: for i in 1..10 do print i print i := i + 1 := done x Having a loop upper bound / exit condition which never Having happens (infinite loop)
 happens Example: i := 0 do print i print i := i + 1 := while (i >= 0)
 while 41 And now in C++! x For loops, While loops and Do loops are available in C++ x The syntax is precisely defined, esp. for the for loops x There is in C++ an equivalence between all three loops Example: all are while loops in GCC 42 for loops in C++ x Syntax for ([<init>]; [<test>]; [<increment>])
 <instructions> <instructions> x It can be seen as: <init> while (<test>)
 do <instructions> <instructions> <increment> <increment> done done 43 for loops in C++ x Example: for (i = 0; i < 10; ++i)
 std::cout << i << std::...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online