Unformatted Document Excerpt
Coursehero >>
Maryland >>
Montgomery College >>
CS 100
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
2007 Copyright Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 1
Chapter
5
Looping
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
5.1
The Increment and Decrement Operators
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
The Increment and Decrement Operators
++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;
++ can be used before (prefix) or after (postfix) a variable: ++val; val++;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 4
The Increment and Decrement Operators
-- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1;
-- can be also used before (prefix) or after (postfix) a variable: --val; val--;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 5
(Program Continues)
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 6
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 7
Prefix vs. Postfix
++ and -- operators can be used in complex statements and expressions In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 8
Prefix vs. Postfix - Examples
int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays it num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 9
Notes on Increment, Decrement
Can be used in expressions: result = num1++ + --num2; Must be applied to something that has a location in memory. Cannot have: result = (num1 + num2)++; Can be used in relational expressions: if (++num > limit) pre- and post-operations will cause different comparisons
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 10
5.2
Introduction to Loops: The while Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Introduction to Loops: The while Loop
Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 12
while Loop How It Works
while (expression) statement; expression is evaluated if true, then statement is executed, and expression is evaluated again if false, then the the loop is finished and program statements following statement execute
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 13
The Logic of a while Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 14
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 15
How the Loop in Lines 9 through 13 Works
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 16
Flowchart of the Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 17
while is a Pretest Loop
expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { cout << "Hello\n"; number++; }
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 18
Watch Out for Infinite Loops
The loop must contain code to make expression become false Otherwise, the loop will have no way of stopping Such a loop is called an infinite loop, because it will repeat an infinite number of times
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 19
An Infinite Loop
int number = 1; while (number <= 5) { cout << "Hello\n"; }
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 20
5.3
Using the while Loop for Input Validation
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Using the while Loop for Input Validation
Input validation is the process of inspecting data that is given to the program as input and determining whether it is valid. The while loop can be used to create input routines that reject invalid data, and repeat until valid data is entered.
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 22
Using the while Loop for Input Validation
Here's the general approach, in pseudocode:
Read an item of input. While the input is invalid Display an error message. Read the input again. End While
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 23
Input Validation Example
cout << "Enter a number less than 10: "; cin >> number; while (number >= 10) { cout << "Invalid Entry!" << "Enter a number less than 10: "; cin >> number; }
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 24
Flowchart
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 25
Input Validation Example from Program 5-4
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 26
5.4
Counters
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Counters
Counter: a variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (also known as the loop control variable) Must be initialized before entering loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 28
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 29
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 30
5.5
The do-while Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
The do-while Loop
do-while: a posttest loop execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression)
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 32
The Logic of a do-while Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 33
do-while Example
int x = 1; do { cout << x << endl; } while(x < 0);
Although the test expression is false, this loop will execute one time because do-while is a posttest loop.
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 34
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 35
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 36
do-while Loop Notes
Loop always executes at least once Execution continues as long as expression is true, stops repetition when expression becomes false Useful in menu-driven programs to bring user back to menu to make another choice (see Program 5-7 in the book)
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 37
The for Loop
Useful for counter-controlled General loop Format: for(initialization; test; update) statement; // or block in { }
No semicolon after 3rd expression or after the )
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 38
for Loop - Mechanics
for(initialization; test; update)
statement; // or block in { } Perform initialization Evaluate test expression If true, execute statement If false, terminate loop execution Execute update, then re-evaluate test expression
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 39
for Loop - Example
int count; for (count = 1; count <= 5; count++)
cout << "Hello" << endl;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 40
A Closer Look at the Previous Example
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 41
Flowchart for the Previous Example
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 42
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 43
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 44
A Closer Look at Lines 13 through 14 in Program 5-8
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 45
Flowchart for Lines 13 through 14 in Program 5-8
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 46
When to Use the for Loop
In any situation that clearly requires an initialization a false condition to stop the loop an update to occur at the end of each iteration
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 47
The for Loop is a Pretest Loop
The for loop tests its test expression before each iteration, so it is a pretest loop. The following loop will never iterate:
for (count = 11; count <= 10; count++) cout << "Hello" << endl;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 48
for Loop - Modifications
You can have multiple statements in the initialization expression. Separate the statements with a comma: Initialization Expression
int x, y; for (x=1, { cout << << << } y=1; x <= 5; x++) x << " plus " << y " equals " << (x+y) endl;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 49
for Loop - Modifications
You can also have multiple statements in the test expression. Separate the statements with a comma: Test Expression
int x, y; for (x=1, { cout << << << } y=1; x <= 5; x++, y++) x << " plus " << y " equals " << (x+y) endl;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 50
for Loop - Modifications
You can omit the initialization expression if it has already been done:
int sum = 0, num = 1; for (; num <= 10; num++) sum += num;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 51
for Loop - Modifications
You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop.
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 52
5.7
Keeping a Running Total
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Keeping a Running Total
running total: accumulated sum of numbers from each repetition of loop accumulator: variable that holds running total
int sum=0, num=1; // sum is the while (num <= 10) // accumulator { sum += num; num++; } cout << "Sum of numbers 1 10 is" << sum << endl;
Slide 5- 54
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
(Program Continues)
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 55
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 56
5.8
Sentinels
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Sentinels
sentinel: value in a list of values that indicates end of data Special value that cannot be confused with a valid value, e.g., -999 for a test score Used to terminate input when user may not know how many values will be entered
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 58
(Program Continues)
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 59
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 60
5.9
Using a Loop to Read Data from a File
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Using a Loop to Read Data from a File
The stream extraction operator >> returns true when a value was successfully read, false otherwise Can be tested in a while loop to continue execution as long as values are read from the file: while (inputFile >> number) ...
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 62
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 63
5.10
Deciding Which Loop to Use
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Deciding Which Loop to Use
while: pretest loop; loop body may not be executed at all do-while: posttest loop; loop body will always be executed at least once for: pretest loop with initialization and update expression; useful with counters, or if precise number of repetitions is needed
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 65
5.11
Nested Loops
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Nested Loops
A nested loop is a loop inside the body of another loop Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl;
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 67
Lines from Program 5-14
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 68
Nested Loops - Notes
Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops.
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 69
5.12
Breaking Out of a Loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
Breaking Out of a Loop
Can use break to terminate execution of a loop Use sparingly if at all makes code harder to understand and debug When used in an inner loop, terminates that loop only and goes back to outer loop
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 71
5.13
The continue Statement
Copyright 2007 Pearson Education, Inc. Publishing as Pearson AddisonWesley
The continue Statement
Can use continue to go to end of loop and prepare for next repetition while, do-while loops: go to test, repeat loop if test passes for loop: perform update step, then test, then repeat loop if test passes Use sparingly like break, can make program logic hard to follow
Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 5- 73
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more.
Course Hero has millions of course specific materials providing students with the best way to expand
their education.
Below is a small sample set of documents:
Maryland - BSCI - 207
Topic 4. Thermodynamics & Enzyme CatalysisCh. 3Thermodynamics: study of the changes in energy accompanying events in the physical universe. Review the first and second law of thermodynamics. Of what significance is thermodynamics it to biology, a
York University - STATS - 2320
Assignment 2Muhammad Ali Saleem 209 419 730Diane ZornADMS 3660 STAKEHOLDER TABLEPrimary Stakeholders-Interests/StakesMay face bankruptcy if they are ordered by the court to pay fines and compensation to the class members. Their business models will
York University - STATS - 2320
STAKEHOLDER TABLE Primary Stakeholders Interests/StakesSecondary StakeholdersInterests/Stakes
Adirondack Community College - BIOL - 1362
CHAPTER 2 DifferentiationSection 2.1 Section 2.2 Section 2.3 Section 2.4 Section 2.5 Section 2.6 The Derivative and the Tangent Line Problem . . . . . 95 Basic Differentiation Rules and Rates of Change . . 109Product and Quotient Rules and Higher-
Spring Hill - BIOL - 1362
CHAPTER 1 Limits and Their PropertiesSection 1.1 Section 1.2 Section 1.3 Section 1.4 Section 1.5 A Preview of Calculus . . . . . . . . . . . . . . . . . . . . 46 Finding Limits Graphically and Numerically . . . . . . . . 47 Evaluating Limits Analyti
HKUST - CS - 105
Tutorial 6: Quick Sort & heap sort Quick sort Heap sort Empirical AnalysisIntroductionQuick sort, like merge sort, is based on the divide-and-conquer paradigm. Intuitively, it operates as follows.Divide:CHOOSE A PIVOT ELEMENT in the list. P
Maryland - BSCI - 363
Scientists Find Oldest Human Samples Uncovered in the Americas Discovery Raises Questions About Theory of How Land Mass Was Populated 4/3/08 Scientists have found and dated the oldest human remains ever uncovered in the Americas - a discovery that pl
Wake Forest - LAW - 254
Updated by Andrew Appleby Taxation of Corporations and Shareholders Professor Shores Fall 2007I.INTRODUCTION.A. Federal Income Tax's relation to corporate tax: 1. Transaction with an individual B buys a house for $1000 (1,000 cash + 9,000 nonr
Washington University in St. Louis - BIO - 381
Biochemistry 2008 1st semester Final study question lists 1. _ amino acids are almost never found in the interior of a protein, but the protein surface may consist of _ amino acids. 2. Electrostatic interactions among amino acid residues on proteins
University of Texas - EM - 319
University of Texas - EM - 319
University of Texas - EM - 319
University of Texas - EM - 319
Akademia Ekonomiczna w Poznaniu - ACC - 101
CHAPTER 4 Process Costing and Hybrid Product-Costing SystemsANSWERS TO REVIEW QUESTIONS4-1 In a job-order costing system, costs are assigned to batches or job orders of production. Job-order costing is used by firms that produce relatively small nu
Punjab Engineering College - EE - 101
Punjab Engineering College - EE - 101
Metro State - ICS - 311
Database Development ProcessChapter 2 MIS 2403 Dr. Segall Spring 2002Information Systems Architecture"A conceptual blueprint or plan that expresses the desired future structure for the information systems in an organization."2Information Syste
MNSU - CS - 310
CS 320 Computer Architecture Spring 2008 Unit 2 Basic ConceptsFurman Haddix, Ph.D. Assistant Professor Minnesota State University, MankatoUnit 2 Basic Concepts ObjectivesComputer Organization and Architecture Machine Language Generations of Computers P
Metro State - ICS - 311
MIS 2403: The Seven Steps (Rules) for Creating EER DiagramsChapter 6: Logical Database Design and the Relational Model Dr. Segall Spring 2001The 7 STEPS FOR EERSTEP 1: Map Regular EntitiesComposite Attributes Multivalued AttributesSTEP 2: Map WEAK En
Metro State - ICS - 311
Normalizing RelationsTransforming ER Diagrams into RelationsMIS 2403: Intro to Data Base MIS 3413: Advanced Database Concepts Dr. Segall Spring 2001Data Normalization First normal form: Any multivalued attributes (repeating groups) havebeen removed,
Metro State - ICS - 311
MIS 2403: Introduction to Database ManagementINSTRUCTOR'S NOTESChapter 1: The Database Environment: A Basic Overview Spring 2002 Dr. Richard S. SegallWelcome to MIS 2403!Learning Objectives Database skillsUnderstanding & Designing databases Intro to
Rutgers - ENGLISH - 101
New Jersey Assessment of Skills and Knowledge2007 Grade 7 MATHEMATICS REFERENCE SHEETUse the information below to answer questions on the Mathematics section of the 2007 Grade Seven Assessment of Skills and Knowledge (NJ ASK 7). The sum of the measures
Rutgers - ENG - 101
World Peace It is the final round of the beauty pageant and the competitors are sneaking to find ways to win the crown. It is time for the questions and it is up to the contestant to sound as charming as ever, even if she does not truly mean it. The
Rutgers - ENG - 101
Get Up Off Your Feet! Democracy is defined as the free and equal right of every person to participate in a system of government, often practiced by electing representatives of the people by the people. It is a country with a government that has been
Rutgers - COMM - 101
Family 2 Transcript Start Time 9:51Problematic Joke1 2 3 4 5 6 7 8 9Gma: This sounds like a joke (.01) Gma: Severeal weeks ago, I went in the [(locker room)] We always have something to say to each other, so she tells me Helen? Several weeks ag
Rutgers - HIST - 122
For the final project, I want to do a craft project that demonstrates what is American about America. For the most part, I find that Americans are all about finding new things and developing new ideas. Were constantly developing new technologies and
Punjab Engineering College - EE - 101
SUNY Buffalo - PHI - 407
ECO 407Macroeconomic Theory Grade:_ Name:_QUIZ 6 Part I [45 points]1. The Solow model implies that differences in total factor productivity are even more important in explaining differences in income across countries than the production model of Chapt
Punjab Engineering College - PHI - 407
ECO 407 NAME_Macroeconomic TheoryJan. 31, 08 Student Number_QUIZ 2 Answer KeySection I1. How do you compare GDPs across different economies? [15points] International comparisons of GDP involve two conversions. First, we need exchange rates to convert
Punjab Engineering College - PHI - 407
ECO 407 Name: _Macroeconomic Theory Student Number: _QUIZ 3 Part I- Short essay [45 Points]Result: _ 1. What are some costs and benefits of economic growth? Write a small paragraph arguing that the benefits exceed the costs._ _ _ _ _ _ _2. What is a
Punjab Engineering College - PHI - 407
ECO 407 Macroeconomic TheoryName:_QUIZ 4 Part I [45 points]1. How does the national income identity show up in our production model? _ _ _ _ _ _ _ Consider the following production function Y = AK L . What is the level of output per person? According
Punjab Engineering College - PHI - 407
ECO 407 Macroeconomic TheoryName:_QUIZ 5 Part I [45 points]1. What is the main difference between the Solow model and the model from chapter 4 (production model)? What is the relationship between saving and investment? Show this result in our model, n
Academy of Design Tampa - HIST - 101
Chapter 1 The Nature and Method of EconomicsI. Definition of Economics A. The social science concerned with the efficient use of limited or scarce resources to achieve maximum satisfaction of human materials wants. B. Human wants are unlimited, but the m