The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures



Similar documents
While Loop. 6. Iteration

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

C++ Input/Output: Streams

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Basics of I/O Streams and File I/O

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

JavaScript: Control Statements I

Passing 1D arrays to functions.

Member Functions of the istream Class

Lecture 2 Notes: Flow of Control

Chapter 8 Selection 8-1

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

UEE1302 (1102) F10 Introduction to Computers and Programming

Common Beginner C++ Programming Mistakes

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Conditions & Boolean Expressions

Using C++ File Streams

J a v a Quiz (Unit 3, Test 0 Practice)

PIC 10A. Lecture 7: Graphics II and intro to the if statement

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

6. Control Structures

Appendix K Introduction to Microsoft Visual C++ 6.0

Chapter 2: Elements of Java

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Statements and Control Flow

Unit 6. Loop statements

Chapter 5. Selection 5-1

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

The While Loop. Objectives. Textbook. WHILE Loops

Chapter One Introduction to Programming

if and if-else: Part 1

Computer Programming C++ Classes and Objects 15 th Lecture

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Compiler Construction

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Writing Control Structures

Visual Logic Instructions and Assignments

Compiler Construction

Learning Computer Programming using e-learning as a tool. A Thesis. Submitted to the Department of Computer Science and Engineering.

Informatica e Sistemi in Tempo Reale

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Object Oriented Software Design

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

CS 241 Data Organization Coding Standards

Computer Organization

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Stacks. Linear data structures

Iteration CHAPTER 6. Topic Summary

7.7 Case Study: Calculating Depreciation

C++FA 5.1 PRACTICE MID-TERM EXAM

Moving from C++ to VBA

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Sample CSE8A midterm Multiple Choice (circle one)

Lecture 1 Introduction to Java

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Computer Programming I

Chapter 3 Operators and Control Flow

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Example of a Java program

The if Statement and Practice Problems

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Chapter 9 Text Files User Defined Data Types User Defined Header Files

El Dorado Union High School District Educational Services

Block I Apollo Guidance Computer (AGC)

Answers to Review Questions Chapter 7

F ahrenheit = 9 Celsius + 32

So far we have considered only numeric processing, i.e. processing of numeric data represented

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Repetition Using the End of File Condition

CS106A, Stanford Handout #38. Strings and Chars

13 Classes & Objects with Constructors/Destructors

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Appendix M: Introduction to Microsoft Visual C Express Edition

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

LOOPS CHAPTER CHAPTER GOALS

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Pseudo code Tutorial and Exercises Teacher s Version

COSC 181 Foundations of Computer Programming. Class 6

Java Interview Questions and Answers

COMPUTER SCIENCE 1999 (Delhi Board)

Java Basics: Data Types, Variables, and Loops

Debouncing Switches. Mechanical switches are one of the most common interfaces to a uc.

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Transcription:

The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1

Loops in C++! The while loop in C++ is the most generic form! Syntax! Semantics while (Expression) Statement Executes Statement as long as Expression evaluates to true 3 While Loop (Example)! Recall from our Giving Change Algorithm 1 2.2 If the value of change is >= 100, then perform the following steps. 2.2.1 Add 1 to the value of dollars. 2.2.2 Subtract 100 from the value of change. 2.2.3 Repeat step 2.2! This is a loop! 4 2

While Loop (Example) const int ONE_DOLLAR = 100; // one dollar in cents int dollars = 0; int change = -1; // number of dollars in change // the amount of change cin >> change; while (change >= ONE_DOLLAR) dollars = dollars + 1; change = change - ONE_DOLLAR; 5 Kinds of Loops! Event Controlled Loop Executes until a specified situation! Describes all types of loops! Count Controlled Loop Executes a specified number of times! Sentinel Controlled Loop Executes until a dummy value is encountered in the input 6 3

Event Controlled Loop (Example) int high = 20; int low = 0; while (low < high) low = low + 3; high = high - 2; What is output? cout << "Low: " << low << "High: " << high << endl; 7 Count Controlled Loop (Example) int numgrades = -1; int numread = 0; int grade = 0, total = 0; 7 87 99 82 74 83 88 90 80 8 cout << "Enter the number of grades to read: " << flush; cin >> numgrades; while (numread < numgrades) cin >> grade; total = total + grade; numread = numread + 1; if (numread > 0) cout << "Your average is " << (total * 1.0) / numread << endl; 4

Sentinel Controlled Loop const int SENTINEL = -1; int numread = 0; int grade = 0, total = 0; 87 99 82 74 83 88 90-1 80 9 cout << "Enter grades or " << SENTINEL << " to quit." << endl; cin >> grade; // priming read while (grade!= SENTINEL) total = total + grade; numread = numread + 1; cin >> grade; // read the next grade if (numread > 0) cout << "Your average is " << (total * 1.0) / numread << endl; Exercises! Write a loop to do the following: 1. Read in 10 integers. 2. Find the maximum value. 3. Find the minimum value.! Hints Don't store all 10 values at once, calculate the maximum/minimum so far as you go. Use INT_MIN and INT_MAX to initialize maximum/minimum value so far.! Trace using the following input. 30-209 45 827-93 101-445 79 827 83 10 5

Input Failure! Each input stream (e.g., cin or input file stream) has a state The state is good if every operation has succeeded The state is bad if some operation has failed! Couldn't open a file! Couldn't read in a value of the expected type! Couldn't find delimiting character for ignore or getline! We can test input streams for their state true is good false is bad 11 Input Failure (If Example)! Use the stream variable as part of a boolean expression ifstream In; In.open("Data.txt"); if (In) cout << "The file opened properly." << endl; else cout << "The file was not opened." << endl; 12 6

Input Failure (If Example)! Suppose we try to read an integer, but no integer is there. int age = -1; Age 23 In >> age; if (!In) // could not read the age, age still has the value -1 cout << "The age couldn't be read." << endl; 13 Reading until Input Failure! A common method for reading input is to read until there is an input failure Occurs when you read the end of the file! Read data one set at a time Always leave the read marker at the beginning of the next set. 14 7

const char DELIMITER = ' '; string name = ""; int age = -1; ifstream In("Data.txt"); Read until Input Failure (Correct Example) Joe Missouri 32 Sally White 27 Missy Green 24 15 // Priming read for one data set getline(in, name, DELIMITER); In >> age; In.ignore(INT_MAX, '\n'); while (In) cout << "Name: " << name << "\tage: " << age << endl; // Read the next data set getline(in, name, DELIMITER); In >> age; In.ignore(INT_MAX, '\n'); There's an invisible end of file character here. Name: Joe Missouri Age: 32 Name: Sally White Age: 27 Name: Missy Green Age: 24 Read until Input Failure (Incorrect Example) const char DELIMITER = ' '; string name = ""; int age = -1; Joe Missouri 32 Sally White 27 Missy Green 24 ifstream In("Data.txt"); Name: Joe Missouri Age: 32 Name: Sally White Age: 27 // No priming read Name: Missy Green Age: 24 while (In) Name: Missy Green Age: 24 // Read a data set getline(in, name, DELIMITER); In >> age; In.ignore(INT_MAX, '\n'); cout << "Name: " << name << "\tage: " << age << endl; 16 8

Recovering from Input Failure! When input failure occurs, you cannot read anything else until you reset the state of the stream! Use the clear() function for input streams! Syntax InputStreamVariable.clear(); 17 Recovering from Input Failure (Example) 18 ifstream In("Data.txt"); int anint = -1; 25 15 30 45 Michael Jordan int total = 0; // read integers and total them In >> anint; while (In) total = total + anint; In >> anint; // read the name that follows the integers // Note that final extraction does skip the whitespace! string name = ""; In.clear(); // reset the flags getline(in, name); 9

Exercise! Modify your minimum and maximum calculations to read until input failure instead of reading a fixed number of integers.! Trace through your code with the input 205-90 -103 199 76 823-205 133 144 150 19 End-Of-File Handling! Input streams support the eof()function true if last input operation read end-of-file mark false if last input operation did not read end-of-file mark! Syntax InputStreamVariable.eof() 20 10

End-Of-File Example int anint = 0; char c = '\0'; ifstream In("Input.txt"); In >> anint; In.get(c); while (!In.eof()) cout << anint << endl; In >> anint; In.get(c); Input 1 2 3 1 2 3 With newline Without newline 21 Other Loops! C++ provides alternative syntax for loops for loops do while loops! These alternatives can always be rewritten as while loops Syntatic sugar 22 11

For Loops! A for loop is the preferred syntax for count controlled loops.! Syntax for (Initialization; TestExpression; Update) Statement 23! Initialization is often used to initialize variables! TestExpression determines loop termination! Update executes once an iteration Updates values used in test expression For Loop (Example) int total = 0; int x = 0; while (x < 10) total = total + x; x = x + 1; int x; int total = 0; for (x = 0; x < 10; x = x + 1) total = total + x; 24 12

Increment and Decrement! post-increment (++) and post-decrement (--) operators are used frequently with for loops! Examples i++; // i = i + 1; i--; // i = i - 1;! Can be used in expressions, but should be avoided for readability. 25 For Loop and Increment (Example) int numgrades = -1; int numread = 0; int grade = 0, total = 0; 7 87 99 82 74 83 88 90 80 cout << "Enter the number of grades to read: " << flush; cin >> numgrades; for (numread = 0; numread < numgrades; numread++) cin >> grade; total = total + grade; if (numread > 0) cout << "Your average is " << (total * 1.0) / numread << endl; 26 13

For Loop and Decrement (Example) const char STAR='*'; int numprint; // what to draw cout << "How many stars do you want to print? " << flush; for (cin >> numprint; numprint > 0; numprint--) cout << STAR; cout << endl; Notice the use of an input statement here! 27 Pitfall! Be careful about identifying the statements be executed in the for loop const char STAR='*'; int numprint; // what to draw 28 cout << "How many stars do you want to print? " << flush; for (cin >> numprint; numprint > 0; numprint--) cout << STAR; cout << endl; Only printing the stars is in the loop. 14

Pitfall! Also, watch for extraneous semicolons const char STAR='*'; int numprint; // what to draw cout << "How many stars do you want to print? " << flush; for (cin >> numprint; numprint > 0; numprint--); cout << STAR; cout << endl; One star will always be printed! 29 Do While Loop! Use the do while loop when you are guaranteed to execute at least once.! Flow Statement1 Condition False 30! Syntax True do Statement1 while (Condition); 15

Do While Example! Require the user to enter a non-negative age! While solution cout << "Enter your age: "; cin >> age; while (age < 0) cout << "Your age must be at least 0." << endl; cout << "Enter your age: "; cin >> age; 31 Do While Example! Do While solution do cout << "Enter your age: "; cin >> age; if (age < 0) cout << "Your age must be at least 0" << endl; while (age < 0); The semicolon is required here! 32 16

Exercises! Programming Warm-Up exercises 6, 7, 8, 9 in Chapter 9 on page 488.! Convert the while loop on slide 15 to a do while loop. Which implementation would you prefer to use and why? 33 Nested Loops! Loops can be nested Why? cin >> starcount; while (cin) for (stars = 0; stars < starcount; stars++) cout << '*'; cout << endl; cin >> starcount; Read pages 296-203 34 17

Other Control Statements! Two other control statements break continue! Change control flow in loops and switch statements 35 Break Statement! Stops executing the innermost loop containing the break statement! Flow (while loop) Condition False True Statement1 36 break; 18

Break Example! Loop testing for input failure and sentinel const int SENTINEL = -1; cin >> anint; while (In) if (anint == SENTINEL) break; cout << anint << endl; cin >> anint; 1 2 3-1 4 5 6 37 Better implementation const int SENTINEL = -1; cin >> anint; while (In && anint!= SENTINEL) cout << anint << endl; cin >> anint; Why is this considered better? 38 19

Continue Statement! Skips the rest of an iteration! Flow (while loop) Condition False True Statement3 Statement1 continue; 39 Continue Example! Total positive values const int SENTINEL = 0; int valentered = -1, total = 0; 1-2 3 0 4 5 6 40 while (valentered!= 0) cout << "Enter a positive value or " << SENTINEL << " to quit: " << flush; cin >> valentered; if (valentered < 0) continue; total = total + valentered; 20

Better Implementation const int SENTINEL = 0; int valentered = -1, total = 0; while (valentered!= 0) cout << "Enter a positive value or " << SENTINEL << " to quit: " << flush; cin >> valentered; if (valentered > 0) total = total + valentered; 41 Continue Statement! Skips to the bottom of the loop Update statement is executed in for loops Condition check is evaluated in do while loops 42 21