Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Loops Iteration Repetition Counting Loops Also known as.

Similar presentations


Presentation on theme: "Introduction to Loops Iteration Repetition Counting Loops Also known as."— Presentation transcript:

1

2 Introduction to Loops Iteration Repetition Counting Loops Also known as

3 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 }

4 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.

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

6 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.

7 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?

8 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

9 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); }

10 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 -------------------------- 1 1 1 2 4 8... 10 100 1000

11 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

12 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

13 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; }

14 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

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

16 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!

17 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

18 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

19 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

20 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.

21 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

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

23 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? 301 401 501 302 402 502 303 403 503 604 704 114 214 310 410 510

24 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 ?

25 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

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

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

28 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!

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

30 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

31 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

32 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

33 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: 7.07000 Maximum value: 7.07

34 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 2 3 4 5no

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

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

37 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

38 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.

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


Download ppt "Introduction to Loops Iteration Repetition Counting Loops Also known as."

Similar presentations


Ads by Google