cs31 lecture 10

Technically all three can be expressed with a while

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: ple: do print i i := i + 1 while (i <= 10) 30 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.do 2. str := readFromKeyboard() 3.while (not isInteger(str)) 4.return convertStrToInt(str) 31 Why multiple kinds of loops? Technically, all three can be expressed with a while loop Other loop kinds are syntactic sugar But, depending on the exact behavior expected, one kind of loop will lead to the most clear / most compact code 32 Typical errors Writing the loop iterator in the loop body for a for loop Example: for i in 1..10 do print i i := i + 1 done Having a loop upper bound / exit condition which never happens (infinite loop) Example: i := 0 do print i 33 And now in C++! For loops, While loops and Do loops are available in C++ The syntax is precisely defined, esp. for the for loops There is in C++ an equivalence between all three loops Example: all are while loops in GCC 34 for loops in C++ Syntax for ([<init>]; [<test>]; [<increment>]) <instructions> It can be seen as: <init> while (<test>) do <instructions> <increment> done 35 for loops in C++ Example: int i; for (i = 0; i < 10; ++i) std::cout << i << std::endl; Some properties: The <init> statement is executed only once, and can contain variable declarations The <test> is executed at each iteration, including the first one. The loop iterates while this test is true The <test> can be an arbitrarily complex expression that can be converted to int 36 More examples Example: multiple initializations: for (int i = 1, j = 2; j <= 10 && i < 100; i++) Example: multiple increments: for (int i = 1, j = 2; j <= 10 && i < 100; i++, j++) Example: infinite loop: for (int i = 1, j = 2; ; i++, j++) 37 While loops Straightforward adapting from algorithmic language! Syntax: while (<condition>) <instructions> Example: while (i < 10) std::cout << i++ << std::endl; 38 Do loops Straightforward adapting from algorithmic language! Syntax: do <instructions> while (<condition>) Example: do std::cout << i++ << std::endl; while (i < 10); 39 A reminder about blocks of instructions A block of more than one instruction is encapsulated in { and } Example: { std::cout << i << std::endl; i = i + 1; } In loops in C++, <instructions> is either a single instruction, or a block of instructions encapsulated in { } 40 More C++...
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