Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Similar documents
Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Lab Instructor : Jean Lai

Why Is Repetition Needed?

REPETITION CONTROL STRUCTURE LOGO

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Chapter Four: Loops II

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Name SECTION: 12:45 2:20. True or False (12 Points)

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Unit 7. 'while' Loops

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Chapter 3 - Functions

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

CS 103 Lecture 3 Slides

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

1 Unit 8 'for' Loops

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Functions and Recursion

C++ Programming: From Problem Analysis to Program Design, Third Edition

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

do { statements } while (condition);

Partha Sarathi Mandal

Name Section: M/W T/TH Number Definition Matching (8 Points)

Programming Language. Functions. Eng. Anis Nazer First Semester

Name Section: M/W T/TH Number Definition Matching (6 Points)

n Group of statements that are executed repeatedly while some condition remains true

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

Increment and the While. Class 15

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Chapter 10 - Notes Applications of Arrays

CS2141 Software Development using C/C++ C++ Basics

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

LAB: WHILE LOOPS IN C++

C++ Final Exam 2017/2018

Chapter 17 - Notes Recursion

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Fundamentals of Programming CS-110. Lecture 2

CSCE 206: Structured Programming in C++

A SHORT COURSE ON C++

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Introduction to Programming

Introduction to Programming

CS242 COMPUTER PROGRAMMING

Chapter 5: Control Structures II (Repetition)

Input And Output of C++

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to Programming EC-105. Lecture 2

Example 3. #include <iostream> using namespace std; int main()

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Problem Solving: Storyboards for User Interaction

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

C++ Quick Reference. switch Statements

WARM UP LESSONS BARE BASICS

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ basics Getting started with, and Data Types.

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

BITG 1113: Array (Part 1) LECTURE 8

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

DELHI PUBLIC SCHOOL TAPI

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Object oriented programming

Lab # 02. Basic Elements of C++ _ Part1

The following expression causes a divide by zero error:

C++ For Science and Engineering Lecture 12

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Ch 6. Functions. Example: function calls function

Local and Global Variables

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Transcription:

Chapter 5 Looping

Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Advantages of Computers Computers are really quick Computers don't get bored They can do the same thing over and over and be happy

Loops What is the effect of a loop? { some C++ code; some C++ code; some C++ code; some C++ code; some C++ code; some C++ code; some C++ code; as long as some condition is true

While loops while ( num < 10 ) { cout << num = << num << endl; num = num + 1; Bool Exp True False Code Block

While loops while ( num < 10 ) cout << Hello there \n ; As before if there is only one line in the body of the loop, the { are not needed. But...what is the problem? Bool Exp True Code Block False

While loops while ( num < 10 ) cout << Hello there \n ; As before if there is only one line in the body of the loop, the { are not needed. But...what is the problem? Infinite Loop: a loop that doesn't end Bool Exp True Code Block False

What is a difference between if and while Which of the following is the if (left or right)? Bool Exp Bool Exp True False True False Code Block Code Block

What is a difference between if and while Which of the following is the if (left or right)? Bool Exp while Bool Exp if False True Code Block False True Code Block

Class Exercise Ask the user for 10 integers Return to the user the total of the 10 integers and their average Things to think about: What part needs to be repeated? This will go in the loop body How many variables do you need? Please enter 10 numbers num 1: 23 num 2: 56... num 10: -34 The total of your 10 numbers is: 345 The average for the 10 numbers is: 34

Answer int num = 1, total = 0, temp; cout << Please enter 10 numbers \n while ( num <= 10 ) { cout << num << num << : ; cin >> temp ; total = total + temp; num += 1; cout << The total of your 10 numbers is: << total << endl; cout << The average of your 10 number is: << ( total / 10 ) << endl;

Counter Controled Loop Counter Controled Loop uses a variable (num) to count and control when the loop stops int num = 1, total = 0, temp; cout << Please enter 10 numbers \n while ( num <=10 ) { cout << num << num << : ; cin >> temp ; total = total + temp; num = num + 1; cout << The total of your 10 numbers is: << total << endl;

Another Class Exercise Most of the time our DOS screen is 80 characters wide To help with making a pretty display, make a loop that will print 80 numbers across the screen...but always print from 1 to 10 ( 0 will represent a 10) 123456789012345...67890

Answer int count = 1, output = 1; while ( count <= 80 ) { cout << output ; count = count + 1; output = output + 1; if (output > 9 )// reset output to 0 if over 9 output = 0;

Another Answer int count = 1, output = 1; while ( count <= 80 ) { cout << output ; count = count + 1; // reset output to 0 if over 9 output = ( output > 9? 0 : output + 1 );

Another Answer int num = 1 ; while ( num <= 80 ) { cout << ( num % 10 ) ; num = num + 1;

While loops You can put any kind of code in the code block... Bool Exp True False Code Block

While loops You can put any kind of code in the code block......even other loops Bool Exp True Code Block False Bool Exp True Code Block False

Embedded loops (a loop inside of another loop) In everyday life we have an embedded loop:???? Bool Exp Bool Exp True Code Block False True Code Block False

Embedded loops (a loop inside of another loop) In everyday life we have an embedded loop: Time minutes Bool Exp hours Bool Exp True False True False Code Block Code Block

Creating Some Time Output int hour = 0, min; while ( hour < 24 ) { min = 0; while ( min < 60 ) { cout << hour << ':' << min << endl; min = min + 1; // end of minute loop hour = hour + 1; // end of hour loop

int hour = 0, min; Now What is the Output? while ( hour < 24 ) { min = 0; while ( min < 60 ) { cout << (hour < 10? '0' : ) << hour; cout << ':' ; cout << (min < 10? '0' : ) << min << endl; min = min + 1; // end of minute loop hour = hour + 1; // end of hour loop

Random Numbers Generating random numbers is often useful In a game, player do not want the same behavior/moves each time In a simulation of a complex system, random numbers can be used to help generate random events Car crash in a simulation of a highway system Likelihood of a gene in cell mutation Weather simulation

Random numbers in real life Examples Generate a random number sequence in the range 1 to 6 Use a six-sided die ( 色子 shǎi zi) Each roll represents a new random number Generate a random number sequence in the range 1 to 2 Use a fair coin Heads: 1, Tails: 2

Random Numbers We can write an algorithm for generating what looks like random numbers 30 21 9 28 29... Because it s an algorithm, we know the rules for generating the next number The generated numbers are not really random They are properly called pseudo-random numbers

Stdlib Library Provides functions for generating pseudo-random numbers rand() Returns a pseudo-random unsigned int in the range of 0 to RAND_MAX (32,767) #include <iostream> #include <cstdlib> using namespace std; int main() { int i = 1; while( i <= 5) { cout << rand() << endl; ++i; return 0;

Program Output Output 41 18467 6334 26500 19169

Output #1 41 18467 6334 26500 19169 Output #2 41 18467 6334 26500 19169 Program Output for two runs Every time the program is run we will get the same random numbers

Different Sequences To produce a different sequence, use another function (seed random) void srand(unsigned int); Example srand(10); cout << rand() << endl;

Different Sequences Consider seed.cpp int main() { cout << "Enter a seed: "; unsigned int seed; cin >> seed; srand(seed); int i = 1; while(i <= 5) { cout << rand() << endl; ++i; return 0;

Different Sequences To automatically get a different sequence each time Need a method of setting the seed to a random value The standard method is to use the computer's clock as the value of the seed The function time() can be used Returns an integer value time(0) returns a good value for generating a random sequence

Randseed.cpp #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand( time(0) ); int i = 1; while(i <= 5) { cout << rand() << endl; ++i; return 0;

Output #1 Program Output for two runs 26534 17998 26189 13533 22067 Output #2 26779 4928 22514 16041 9228 Every time the program is run we will get the different random numbers

Sentinel Controlled Loops Continue doing the loop until a special value (the sentinel) is encounter

Sentinel Controlled Loops Continue doing the loop until a special value (the sentinel) is encounter Example: Before we asked the user for 10 numbers and then we told the user total of the 10 numbers average of the 10 numbers

Sentinel Controlled Loops Continue doing the loop until a special value (the sentinel) is encounter Example: Before we asked the user for 10 numbers and then we told the user total of the 10 numbers average of the 10 numbers Now we want the user to enter as many numbers as they want a negative number is the signal that they are done ( the sentinel )

int count = 1, total = 0, input = 0; Will this work? cout << Please enter some positive numbers that I will average \n ; cout << Enter a negative number to signal that you are done \n ; while ( input >= 0 ) { cout << # << count << : ; cin >> input; total = total + input; count = count + 1; count = count 1; try try it it with: with: 5 7-1 -1 if ( count > 0 ) { cout << The total of your << count ; cout << numbers is: << total << endl; cout << The average of your << count cout << number is: << ( total / count ) << endl;

int count = 1, total = 0, input = 0; Will this work? No cout << Please enter some positive numbers that I will average \n ; cout << Enter a negative number to signal that you are done \n ; while ( input >= 0 ) { cout << # << count << : ; cin >> input; total = total + input; count = count + 1; count = count 1; try try it it with: with: 5 7-1 -1 if ( count > 0 ) { cout << The total of your << count ; cout << numbers is: << total << endl; cout << The average of your << count cout << number is: << ( total / count ) << endl;

int count = 0, total = 0, input = 0; Will this work? cout << Please enter some positive numbers that I will average \n ; cout << Enter a negative number to signal that you are done \n ; while ( input >= 0 ) { total = total + input; count = count + 1; cout << # << count << : ; cin >> input; count = count 1; try try it it again again with: with: 5 7-1 -1 if ( count > 0 ) { cout << The total of your << count ; cout << numbers is: << total << endl; cout << The average of your << count cout << number is: << ( total / count ) << endl;

int count = 0, total = 0, input = 0; Will this work? cout << Please enter some positive numbers that I will average \n ; cout << Enter a negative number to signal that you are done \n ; while ( input >= 0 ) { total = total + input; count = count + 1; cout << # << count << : ; cin >> input; try try it it again again with: with: -5-5 count = count 1; if ( count > 0 ) { cout << The total of your << count ; cout << numbers is: << total << endl; cout << The average of your << count cout << number is: << ( total / count ) << endl;

Infinite loops ( 无限循环 wú xiàn xún huán) Common Infinite Loops while ( ch = y ) {...... Remember: non-zero numbers true zero false

Infinite loops ( 无限循环 wú xiàn xún huán) Common Infinite Loops while ( ch = y ) {...... or int i = 0 while ( i < 10 ) {...... // forgot i++; Remember: non-zero numbers true zero false

Other equality notes == is great for comparing integers, but should not be used for floating-point numbers instead use comparison operators ( <, <=, >, >= ) float f; if ( f == 100 ) // f: 100.00000000001 // do something if ( f >= 100 ) // do something // instead do this

Looping Control Structures Three different commands while statement do-while statement...

The Do-While Statement Syntax do code block while (bool expr); True Code Block Bool Exp False

Using a do while loop char reply; do {... // some code... cout << "Do you want to continue?(y):"; cin >> reply; while(reply == 'y');

Why use a...? What is the advantage of a while: do...while:

Why use a...? What is the advantage of a while: do...while: body will execute 0 N times body will execute 1 N times

Looping Control Structures Three different commands while statement do-while statement for statement

Common use of loop int cnt = 0; // initialize while ( cnt < 10 ) { // check...; // do something...body of loop...; cnt++; // update

The for loop Syntax for (initialization ; bool expression ; update action) body of the loop Example for (int i = 0; i < 3; i++) { cout << "i is " << i << endl;

Executed once at the beginning of the for loop's execution Initialization Bool Exp true false The Bool Exp is evaluated at the start of each iteration of the loop Body Update Action

Execution Example i 0 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl;

Execution Example i 0 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl;

Execution Example i 0 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0

Execution Example i 0 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0

Execution Example i 1 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0

Execution Example i 1 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0

Execution Example i 1 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1

Execution Example i 1 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1

Execution Example i 2 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1

Execution Example i 2 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1

Execution Example i 2 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1 i is 2

Execution Example i 2 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1 i is 2

Execution Example i 3 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1 i is 2

Execution Example i 3 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1 i is 2

Execution Example i 3 for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; cout << "all done" << endl; i is 0 i is 1 i is 2 all done

Embedding for loops Just like while loops, for loops can also be embedded inside other loops in fact, due to there compactness (information being easier to read) many embedded loops will be for loops

int cntr1 =0, cntr2 =0, cntr3 =0,cntr4 =0, cntr5 =0; cntr1++; for (int i = 1; i <= 10; ++i) { cntr2++; for (int j = 1; j <= 20; ++j) { cntr3++; cntr4++; cntr5++; What is the output? cout << cntr1: << cntr1 << endl << cntr2: << cntr2 << endl << cntr3: << cntr3 << endl << cntr4: << cntr4 << endl << cntr5: << cntr5 << endl;

Answer: cntr1: 1 cntr2: 10 cntr3: 200 cntr4: 10 cntr5: 1 Press any key to continue

Class Exercise Write code to display a grid. For each position, display the location s row and column number. Put two blanks between each location. Ex: 1,1 1,2 1,3... 1,9 2,1 2,2... 2,9... 8,1 8,2... 8,9 9,1 9,2 9,3...9,9

One solution to grid exercise for(int row = 1; row < 10; row++ ){ for(int col = 1; col < 10; col++) { cout << row <<, << col << ; // end of col loop cout << endl; // end of row loop

Another use of break break can be used to exit a loop // in some game while ( life > 0 ) {... // play game cout << Do you want to quit(q): ; cin >> userresponse; if (userresponse == q ) break; // end while loop not the best example

A better solution // in some game userresponse = c ; while ( life > 0 && userresponse!= q ) { // play game... cin >> userresponse; // end while loop

The best solution // in some game do { // play game... cin >> userresponse; while ( life > 0 && userresponse!= q );

Another use of break break will only exit out of one loop (if embedded) for ( int row = 1; row < 10; row++ ) { for ( int col = 1; col < 10; col++) { // do something if (???? ) break; // col loop // this will stop the col loop // row loop

Continue, the brother of break the key word, continue, will cause execution to skip to the boolean expression while( something == true ) { // do something if ( x > 0 ) continue; // skip to end of block // do some more... // end of while

Continue, the brother of break the key word, continue, will cause execution to skip to the boolean expression while( something == true ) { // do something if ( x > 0 ) continue; // skip to end of block // do some more... // end of while

Using break and continue in loops First look for a solution that does not use break or continue Only use break and continue if it is the only solution or it makes the code easier to understand Note: always avoid using goto... there is almost always a better way