15
Lesson 10 Ricardo Salazar, Pic 10A

Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

Lesson 10Ricardo Salazar, Pic 10A

Page 2: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

(3.8) The do-while loop● The while loop is like an if block that is repeated, but

like any if statement, it might not actually run.● To make sure the block will run at least once, an extra

condition is needed (e.g. response = "y" )● Often we need a block of code to run at least once.

E.g: 'gato' game.● In these cases use the do-while loop.

Syntax: do{

-- STATEMENTS --}while( statement );

- Braces: CHECK!

- Indentation: CHECK;

- Semi-colon: WAIT!WHAAAAAAAT?

; is needed in this case!!!

Page 3: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The 'gato' game (barebones)● In Lesson 9 we proposed several versions of the

INSIDE_BLOCK that draws O's or X's.● To handle the repetition of the game we need an extra

loop.

string response = "y"; string response;while ( response == "y" ) { do{ -- INSIDE_BLOCK -- -- INSIDE_BLOCK -- cout << "Play again (y/n)? "; cout << "Play again (y/n)? "; cin >> response; cin >> response;} }while( response == "y" );

● The while loop weeds the initializationstring response = "y";

● The do-while loop doesn't but it needs the extra ( ; )● It is up to you to decide which one to use.

Page 4: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

(3.7) The for loop● Some other times we want a loop that runs a fixed

number of times (e.g. Draw nine shapes). ● It can be done with while and a counter.

int turn = 1; // initialize counterwhile ( turn <= 9 ) { // condition to stop -- DRAW_SHAPE -- turn++; // update counter}

● The same result is obtained with a for loop.In this case: for ( int turn = 1 ; turn <= 9 ; turn++ ){ -- DRAW_SHAPE -- } Braces: CHECK

Indentation : CHECK

Semi-colons: CHECK-CHECK???

Page 5: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The for loop (cont)● Syntax:

for ( initialization ; stopping_condition ; update){ -- STATEMENTS --}

● Note the semi-colons. They split the arguments into:○ Initialization○ Stopping condition○ UpdateThey all are regular C++ statements and the stopping condition is interpreted as a boolean value.

● The initialization could create a counter, or use an existing one.- for ( int i = 0 ; ... ; ... )- for ( double r = 3.14 ; ... ; ... )- int j=1; for ( j = 1 ; ... ; ... ; )

Page 6: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The for loop (examples)● Display all even numbers from 1 to 100

for( int i=2 ; i <= 100 ; i = i + 2 ) cout << i << "\n";

● Count down from 2018 to 0int j;for( j = 2018 ; j >= 0 ; j-- ) cout << j << " ";cout << endl;

● Add all numbers from 1 to a positive number specified by the user. The addition is performed 'backwards'.

int n; // reads the number, serves as counterint sum = 0; // accumulatorcin >> n;for ( ; n > 0 ; n-- ){ sum = sum + n; // same as sum += n;}cout << "Sum: " << sum << endl;

Page 7: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The for loop (your turn)What is the output of the following snippets?

for ( i=1 ; i<3 ; i++ ) cout << "Hi, there!"; cout << "\n";

int j=0;int n=1;for( n-- ; j<=5 ; j = 2*j-2 ); n += 2;cout << "n = " << n;

int j;for(int k=0; k <= 10 ; k++ ){ j=1; for( ; j<5 ; j+=2 ){ cout << 10*j + k; cout << endl; }}

Watch out for OBOE's...string s = "ovahC";const int N = s.length();for ( int k=N-1 ; k>0 ; k-- ){ cout << s.substr(k,1); cout << " ";}cout << endl;

Displays: C h a v _

And avoid bad style...int j = 1;int sum = 0; for ( ; j <= 10 ; ){ sum += j; j++; }cout << "Sum from 1 to 10 = ";cout << sum;

// Unless you are testing your// students and want to confuse// them :P

Page 8: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

When to use what? ● Use a while loop if a piece of code needs a test in order

to run for the first time.○ Want to start a series of games of 'gato'?

If answer is yes, play the game [repeatedly].If answer is no, move on.

● Use a do-while if you want code run at least once.○ Play 'gato', then ask user if another game is desired.

● Use a for loop if you know in advance how many fixed times a code needs to be run.○ Play 'gato' 100 times regardless of what user has to say

about it.

Page 9: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The factorial (revisited)● At the end of the day all three loops are equivalent if

code is to be run at least once.Recall the factorial of N > 0 is

N! = (1)(2)…(N-1)(N)

Write a snippet that computes the factorial of N,

- Using a while loop- Using a do-while loop- Using a for loop

// do-while loop

int factorial = 1;do{ factorial *= N; N--;}while( N >= 1);cout << factorial;

// while loop

int factorial = 1;while( N >= 1 ){ factorial *= N; N--;}cout << factorial;

// for loop

int factorial = 1;for(int i=1;i<=N;i++) factorial *= i;

cout << factorial;

The factorial is computed from N down to 1.

The factorial is computed from 1 up to N.

Page 10: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

More examples● Print out a rectangular table that represent fractions with

numerators between 1 and 7 and denominators between 2 and 5.

1/2 2/2 3/2 4/2 5/2 6/2 7/21/3 2/3 3/3 4/3 5/3 6/3 7/31/4 2/4 3/4 4/4 5/4 6/4 7/41/5 2/5 3/5 4/5 5/5 6/5 7/5

- Code:for (int denom = 2; denom<=5 ; denom++){ for (int num = 1 ; num<=7 ; num++ ){ cout << num <<"/" << denom << "\t"; } cout << endl;}

Page 11: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

More examples● Write a snippet of code that displays the following

triangular matrix1 0 0 0 02 1 0 0 03 2 1 0 04 3 2 1 05 4 3 2 1

● Notice:- The number in row i, column j is 0 if j>i and it is i-j+1

otherwise.for (int row=1 ; row<=5 ; row++){ for (int col=1 ; col<=5 ; col++){ if ( col > row ) cout << 0 << "\t"; else cout << row - col + 1 << "\t"; } cout << endl;}

Page 12: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

(3.3) The dangling else● We can check several alternatives with an if/else

sequence of statements… but we have to be carefulif ( firstName == "Ricardo" ) if ( lastName == "Salazar " ) cout << "You are Ricardo Salazar\n";else cout << "Your first name is not Ricardo\n";// What happens if the input is Ricardo Sanchez???

● The indentation is misleading. An else always pairs up with the previous if.

if ( firstName == "Ricardo" ) if ( lastName == "Salazar " ) cout << "You are Ricardo Salazar\n"; else cout << "Your first name is not Ricardo\n";

● To fix it use braces to enclose the nested if.

Page 13: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The switch statement● A sequence of if/else statements can be replaced

with a switch statement.

switch ( int_type ){ case value1: -- BLOCK_1 -- break; case value2: -- BLOCK_2 -- break; . . . default: -- LAST_BLOCK -- break;}

if ( int_type == value1){ -- BLOCK_1 --}else if (int_type == value2){ -- BLOCK_2 --} . . .else{ -- LAST_BLOCK --}

Do not forget the break, this is typically a logic error.

Page 14: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The switch statement (cont)● It is particularly good with menus, but be aware that it

only works with int and char types.● Example: A basic calculator.

Enter two numbers:Number 1: 4Number 2: 3

Operations1) to add2) to multiply3) to divide

Choice: 2

The result is 12

int choice;cin >> choice;cout >> "The result is ";

switch (choice){ case 1: cout << x+y; break; case 2: cout << x*y; break; case 3: cout << x/y; break; default: cout << "Error!"; break; }

Notice thebreak statements!

Page 15: Lesson 10 - University of California, Los Angelesrsalazar/pic10a/lessons/lesson10.pdf · Lesson 10 Ricardo Salazar, Pic 10A (3.8) The do-while loop The while loop is like an if block

The switch statement (cont)● It doesn't work with string…

string response;cin >> response;switch (response) { // ERROR! case "yes":

● but you can use the following trick:char response; // !!! clear the buffer afterwards !!!cin >> response;

switch (response) { case 'y': case 'Y': cout << "You said yes!\n"; break; case 'n': case 'N': cout << "You said no!\n"; break; default: cout << "Menso! (You dummy!)\n"; cout << "You said something else.\n"; break;}

Notice the missing breaks!!!

This is called stacking