Control Structures Repetition or Iteration or Looping Part II.

Slides:



Advertisements
Similar presentations
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Advertisements

Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Objectives You should be able to describe:
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Control Structures Repetition or Iteration or Looping Part II.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Control Structures Looping Part 2 Part I The C++ for Statement Meaning: 1.Evaluate all initialization expressions 2.Evaluate expression, if true: a)Execute.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Control Structures RepetitionorIterationorLooping Part I.
Overview Go over parts of quiz? Another iteration structure for loop.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Control Structures RepetitionorIterationorLooping Part I.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Advanced loop controls. Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Introduction to Computer Programming
REPETITION CONTROL STRUCTURE
Unit 3 Lesson 9 Repetition Statements (Loops)
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 2.2 Control Structures (Iteration)
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
While Loops.
TOPIC 4: REPETITION CONTROL STRUCTURE
Outline Altering flow of control Boolean expressions
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 2.2 Control Structures (Iteration)
Chapter 6: Repetition Statements
Control Structures Repetition or Iteration Looping Part I.
Objectives You should be able to describe: The while Statement
Repetition Statements (Loops) - 2
Control Statements Paritosh Srivastava.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Control Structures Repetition or Iteration or Looping Part II

Loop Controls Counter-controlled loops repeat a specific number of times Event-controlled loops repeats until something happens in the loop body to change the evaluation of the expression

Sentinels These are used in event-controlled loops. The loop can be executed any number of times. It stops only when a specifie event occurs. *

Running Totals // count =1 while (count <=4) { } cout > num; total = total + num; cout “The total is now “ << total << endl; count++; *

num = 0; num != 999 while ( num != 999 ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num; } Flag Example

flag = 1; flag while ( flag ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num; if( num > 999) flag = 0; } Flag Example

count <=4 while ( count <=4 ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num;count++; } Sentinel Example cout << “\nEnter a number: “; cin >> num; } primary read num != 999 * *

More Examples count = 1; total = 0; cout << "Enter a number: "; cin >> num; while (count <= 4) {total = total + num; cout << "Enter a number: "; cin >> num; count++; } count--; average = total / count; cout << "\nThe average is " << average << '\n';

break and continue Statements Interrupt the normal flow of control. break causes an exit from innermost enclosing loop or switch statement. continue cause current iteration of a loop to stop and the next iteration to begin immediately. continue may only be used in while, for, and do loops. * * *

The break Statement int j =50; 1 while (j < 80) 2 { 3 j += 10; 4 if (j == 70) 5 break; 6 cout << “j is “ << j<< ‘\n’; 7 } 8 cout << “We are out of the loop.\n”;

The break Statement Output j is 60 We are out of the loop. Sequence of execution:

The continue Statement int j =50; continue 1 while (j < 80) 2 { 3 j += 10; 4 if (j == 70) 5 continue; 6 cout << “j is “ << j<< ‘\n’; 7 } 8 cout << “We are out of the loop.\n”;

The continue Statement Output j is 60 j is 80 We are out of the loop. Sequence of execution:

break and continue while ( ) { statement-1; if( )continue statement-2; } statement-3; while ( ) { statement-1; if( )break statement-2; } statement-3; *

The do Statement Variant of the while statement Syntax do while do statement while (expression); next statement

The do Statement Exit the do 0 or False loop Test the expression statements to execute 1 or True

do Example: do { cout > age; if (age <=0) cout << “Invalid age.\n”; while (age <=0) else cout << "DO SOMETHING\n"; } while (age <=0) ; do Statments

cout << "Enter your age: "; cin >> age; while while (age <= 0) { if (age <=0) { cout << "Invalid age.\n"; cout << "Enter your age: "; cin >> age; } else cout << "DO SOMETHING\n"; } do vs. while

sum = 0; cnt = 1; do {I/O sum += cnt; cnt++; } while (cnt <=n); sum = 0; cnt = 1; I/O // priming read while (cnt <=n) {I/O sum += cnt; cnt++; } do vs. while

do  while  for sum = 0; cnt = 1; do { sum += cnt; cnt++; } while (cnt <=n); sum = 0; cnt = 1; while (cnt <=n) { sum += cnt; cnt++; } sum = 0; cnt = 1 for (cnt = 1; cnt <= n; cnt++) sum += cnt;

Guidelines for choosing: + If simple count-controlled, use a for. + If event-controlled and body is executed at least once, use do. + If event-controlled and nothing is known about the first execution, use while. + When in doubt use while.

Validity Checking Validity checking or data validation is a way of notifying the user of invalid data. You should validate every input value for which any restrictions apply. *

Common Errors Using = in place of = = Placing a ; after the for’s parentheses Using a, to separate items in a for expression - you need a ; Omitting the final ; in the do statement

Common Errors != versus == This changes the logic, be especially careful when used with && or || ( ) && ( ) && ( ) versus ( ) || ( ) || ( ) } note this

Debugging Syntax errors vs. Logic error Prevention - plan first! Valuation tables Display values C++ Debugger *

A Sample Problem Write a program that accepts a user determined number of experiments with a user determined number of scores for each experiment. It displays the average of the scores for each experiment.

How many experiments are there? 2 How many scores are there for each? 3 Enter the scores for experiment 1: Enter result of test 1 : 98 Enter result of test 1 : 56 Enter result of test 1 : 34 The average for experiment 1 is 63 How many scores are there for each? 4 Enter the scores for experiment 2: Enter result of test 2 : 21 Enter result of test 2 : 32 Enter result of test 2 : 16 Enter result of test 2 : 29 The average for experiment 2 is 25 Press any key to continue

Plan for Sample Program I/O - # experiments for I/O - # scores for I/O - enter scores increment total average scores display average * * *

{int exper, test, howmany1, howmany2; double total, score, avg; cout << "How many experiments are there? "; cin >> howmany1; for (exper =1; exper<=howmany1; exper=exper +1) {cout << "How many scores are there for each? "; {cout << "How many scores are there for each? "; cin >> howmany2; cin >> howmany2; cout << "\tEnter the scores for experiment " cout << "\tEnter the scores for experiment " << exper <<": \n"; total = 0; << exper <<": \n"; total = 0; for (test = 1; test <=howmany2; test = test +1) for (test = 1; test <=howmany2; test = test +1) {cout << "Enter result of test " << test <<" : "; {cout << "Enter result of test " << test <<" : "; cin >> score; cin >> score; total = total + score; } total = total + score; } avg = total/(test-1); avg = total/(test-1); cout << "The average for experiment " << exper cout << "The average for experiment " << exper << " is " << setprecision(2) << avg << "\n\n"; << " is " << setprecision(2) << avg << "\n\n"; } } }

Reverse_digits example Write a program to reverse the digits of a positive integer. For example is the number is 8735, the displayed number should be * Hint: Use a do statement and continually strip off and display the units digit of the number (number % 10). After the units digit is displayed, dividing the number by 10 strips off the current units digit and sets up number for the next iteration. Thus, (8735 % 10) is 5 and (8735 / 10) is 873. The do statement executes until number is zero.

Palindrome Example A palindrome is a phrase (number or text) that reads the same backwards as forwards. For example, the following are palindromes: 12321, madam i'm adam. Write a program that reads a five-digit integer and determines whether or not it is a palindrome. Ask the user if another possible palindrome is to be entered.

The End the end