Introduction to Loops Iteration Repetition Counting Loops Also known as.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Objectives You should be able to describe:
Chapter 5: Control Structures II (Repetition)
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
CPS120 Introduction to Computer Science Iteration (Looping)
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
1 Chapter 9 Additional Control Structures Dale/Weems.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
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.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ 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.
Fundamental Programming Fundamental Programming for Loops.
Control Structures RepetitionorIterationorLooping Part I.
CPS120 Introduction to Computer Science Iteration (Looping)
Control Structures RepetitionorIterationorLooping Part I.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
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.
Control Structures Repetition or Iteration or Looping Part II.
Repetitive Structures
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Chapter 8 Repetition Statements
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
A First Book of ANSI C Fourth Edition
Chapter 2.1 Repetition.
Chapter 6: Repetition Statements
Control Structures Repetition or Iteration Looping Part I.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Looping and Repetition
Presentation transcript:

Introduction to Loops Iteration Repetition Counting Loops Also known as

Purpose To apply the same steps again and again to a block of statements. Recall a block of statement is one or more statement, block usually defined by braces { and }

Most Common Uses of Loops For counting For accumulating For searching For Sorting For displaying tables For data entry For menu processing For list processing For simulations.

Types of loops for (start condition; stop condition; change expression) while (stop condition) do..while(stop condition)

C/C++ Loop Structures Pre-test for loops (most common) When you know how many times (fixed condition) while loops When you don’t know how many times Event controlled (variable condition) Post-test do … while loops When you don’t know how many times, but you know you need at least one pass.

What you need to think about to construct a loop What you are going to control the loop with? A counter Keep repeating a number of times An event Keep repeating until controller takes a particular value. More generally:Keep repeating until something happens (You define the event). Usually a controller variable is needed. What you are going to initialise your controller with? How does your controller change? What is the condition of controller that stops loop?

The for Statement Syntax for (init controller; Ctrl expression; Alter controller){ statements; } Example: for (count=1; count < 7; count++) { cout << “count = ” << count << endl; } next statement; start condition change expressionstop condition

The for Statement Used as a counting loop Used when we can work out in advance the number of iterations. Semicolons separate the items You may declare variable and initialize it example: for (int count = 1; count < 7; count++){ statement(s); }

int num; cout << "NUMBER\tSQUARE\tCUBE\n“; cout << "------\t------\t----\n"; for (num = 1; num < 11; num++) { cout << num << “\t“; cout << num * num << “\t“; cout << num * num * num<<“\n"; } A Simple Example Create a table with a for loop NUMBERSQUARECUBE

for and if Statements working together. Simple search for divisors Given an integer number find all the numbers that divide exactly into it (except 1 and itself). e.g. if number = 12, divisors are 2,3,4,6 Thinks I can use % operator to find divisors

Solution Design Get the number for user By starting with check number= 2 and finish with check number 1 less than number (is this efficient?) find the remainder of dividing number with current check number if remainder is 0 display current check number as a divisor. otherwise don’t display anything

Program segment for finding divisors of an integer cout << “Enter an integer :”; cin >> number; for (j = 2; j < number; j = j + 1){ if (number % j == 0){ cout << j << “ is a divisor of “; cout << number << ‘\n’; } sum = sum + j; }

for (j = 0, j < n, j = j + 3) // commas used when semicolons needed for (j = 0; j < n) // three parts needed for (j = 0; j >= 0; j++) ?????what is wrong here ????? Common errors in constructing for Statements

Infinite loops for (j=0; j>=0; j++) { cout << i << endl; } DEMO1 Chris Be careful with terminating conditions!

Programming convention Use of integers called i,j,k You will see them all the time. Most commonly used as loop controller variables Conventionally used for counters We will see later that counters often have a dual use as array indices. When you see i,j,k declared expect to see a loop!

for -- Null (Empty ) Expressions Example 1: j = 1; sum = 0; for ( ; j <= 10; j = j + 1){ sum = sum + j; } Empty/Null expression Start condition outside for control area

We could do this Example 2: j = 1; sum = 0; for ( ; j <= 10; ){ sum = sum + j; j = j + 1; } Empty/Null expression change expression outside for control area

Still legal!- Nothing but two semi-colons! Example 3: j = 1; sum = 0; for ( ; ; ){ sum = sum + j; j++; if (j > 10) break; } stop condition outside for control area

Nested Loops Recall when a control structure is contained within another control structure, the inner one is said to be nested. for... if... for... You may have repetition within decision and vice versa.

Example int row,col; for (row = 0; row < 5; row++){ cout << "\n" <<row; for (col = 1; col <= 3; col++){ cout <<"\t" << col; } cout << "\t**"; } Nested Loops - Ex.1 for within for

Output ** ** ** ** ** Nested Loops – Example 1 variable row changes from 0 to 4 variable col changes from 1 to 3 for every time row changes

Tracing Execution through Loops 1 for (row = 0; row < 5; row++){ 2cout << "\n" <<row; 3for (col = 1; col <= 3; col++){ 4cout <<"\t" << col; 5} 6cout << "\t**"; 7} Linerowcol 10? 20?

for (exper =1; exper<=4; exper=exper +1) { cout << "\tScores for experiment "<< exper <<":\n"; total = 0.0; for (trial = 1; trial <=6; trial = trial +1) { cout > score; total = total + score; } avg = total/(trial-1); cout << "Avg for experiment "<<exper<< " is “<< avg<< endl; } Nested Loops - Ex. 2 One off problem Why trial – 1 ?

Recall Hand trace of nested loop Inner loop terminated with value 4 one unit greater than terminating condition col <=3 Same situation here, inner loop terminates when value of trial becomes 7 A value one more than items entered! Need to correct by subtracting one

The while Statement Syntax start condition; while (stop condition{ statements; change statement; }

Example of while count = 1; while (count <= 10) { cout << “count = ” << count << endl; count = count + 1; } next statement;

While vs. For while is less rigid than for while more suitable for event control (clearer syntax) i.e. Keep processing until something happens. E.g. the control variable is assigned a specific value. For is more structured For is more suitable for fixed length loops (clearer) For is more common when used to process arrays (see in later lecture on arrays) Can choose either. Many do and just use one or other all the time!

for = while? cnt = 1cnt++ for (cnt = 1; cnt < 7; cnt++){ cout << … } cnt = 1; while (cnt < 7){ cout << … cnt++; }

The while and for Statement ãThe loop control expression is tested before any of the statements are executed ã Possible never to execute any statement; ã while needs a separate control variable initialization before while begins. ãThe body may contain any number of statements, including branches and other loops ãThe control variable is changed any time during loop execution for the while (usual to be last statement though. ãThe control variable is changed after the last statement in the for structure. ãThe statement immediately after the while or for is executed upon exiting

Example List processing Finding the Largest Value âGet the number of items in the list. âChecks to see if that number is positive. â If not positive ask for the number to be entered again âGet the first number and use it to initialise the variable that hold the max value âIncrement a counter âwhile we have more number to enter â get user to input a number. â increment counter â compare number with max - Assigns the largest to max. âend loop âdisplay max Design: Needs a counter and a variable to hold maxvalue and a variable to hold number entered by user

int count = 0, n = 0; double max = 0, x = 0; cout << "The maximum value will be computed.\n"; cout > n; while (n <= 0) { cout > n; } cout > x; max = x;// first value to max count++;//entered a number so increase count by one while (count > x; count++; //entered a number so increase count by one if (max < x) max = x; } cout << “Maximum value: “ << max << “\n”; } could read from a file here

Output The maximum value will be computed. How many numbers do you wish to enter? 4 Enter a real number: 1.01 Enter a real number: -3 Enter a real number: 2.2 Enter a real number: Maximum value: 7.07

Counters cout > x; max = x; count = 1 while (count < n{ cout << “LOOP number: “ cin >> x; if (max > x; if (max < x) max = x; count++; } countnloop executed 15yes no

Running Totals total = 0; count =0 while (count > num; count++; total = total + num; cout << “The total is “ << total; } cout << “Grand total is “ << total << endl;

Choice for or while Personal preference Use for for fixed length loops Use while for variable length loops

Common Errors using = rather than == in test expressions can cause infinite loops. using == with floating point numbers placing a semi colon at end of for statement. for (i=0;i<=10;i++); statement; //only executed once. using comas as separators in a for for (i=0, i<=10, i++) one off problems

Summary A loop is a section of repeating code loop normally controlled by control variable, a condition, an alter statement. Three types of loop, 2 pre-test 1 post test. Conditions may be fixed count or variable count. Always use indentation and braces with loops. Loops are frequently nested.

Demos Infinite Loops Functions of one variable use debugger Tables Counting and accumulating Interactive while Interactive for Menu systems List processing data validation