The for Statement A most versatile loop

Slides:



Advertisements
Similar presentations
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Advertisements

Copyright © by Curt Hill Expressions and Assignment Statements Part 2.
Computer Science 1620 Loops.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Chapter 5: Control Structures II (Repetition)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
C++ for Engineers and Scientists Third Edition
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright Curt Hill A Quick Introduction to Looping Breadth not Depth.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Chapter 05 (Part III) Control Statements: Part II.
Statement Level Flow of Control Iteration Structures Copyright © by Curt Hill.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Copyright © Curt Hill The Compound Statement C-Family Languages and Scope.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
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.
Copyright Curt Hill The Assignment Operator and Statement The Most Common Statement you will use.
Copyright © Curt Hill Flow of Control A Quick Overview.
Copyright © Curt Hill The Assignment Operator and Statement The Most Common Statement you will use.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
C++ LANGUAGE MULTIPLE CHOICE QUESTION
The Second C++ Program Variables, Types, I/O Animation!
Review 1.
Flow of Control An Overview
REPETITION CONTROL STRUCTURE
Unit 3 Lesson 9 Repetition Statements (Loops)
Selection (also known as Branching) Jumail Bin Taliba by
More important details More fun Part 3
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Loop Structures.
Chapter 2.2 Control Structures (Iteration)
JavaScript: Control Statements.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
LOOPS.
Lecture 4B More Repetition Richard Gesick
Control Structures – Selection
Outline Altering flow of control Boolean expressions
Chapter 8 JavaScript: Control Statements, Part 2
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 6: Repetition Statements
Computing Fundamentals
Control Structures Part 2
CPS120: Introduction to Computer Science
Control Structure Testing
Chapter 4: Control Structures I (Selection)
The Java switch Statement
Chapter8: Statement-Level Control Structures April 9, 2019
Objectives You should be able to describe: The while Statement
Repetition Statements (Loops) - 2
Javascript Chapter 19 and 20 5/3/2019.
CSC215 Lecture Control Flow.
Controlling Program Flow
The IF Revisited A few more things Copyright © Curt Hill.
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

The for Statement A most versatile loop Copyright ©1999-2012 Curt Hill

The for The for is the most popular of the C family of language loops This is because the initialization, test and advancement are all obvious as part of the header of the statement Many other languages have a similar statement but this one has very few restrictions on the pieces It is a leading decision loop Copyright ©1999-2012 Curt Hill

The generalized for The general form is: for(initialization;test;advancement) one statement The for is a reserved word The parentheses are required The three items are quite flexible Must be separated by a semicolon The one statement is the body of the loop Copyright ©1999-2012 Curt Hill

The Initialization Always executed and always prior to first execution of the test Usually is a simple assignment but may be more complicated The same restrictions as on any assignment statement for (c = abs(3*i); c< … The variable may also be declared there Copyright ©1999-2012 Curt Hill

Control Variable A typical for has the same variable referenced in: The initialization The test The advancement for(i=0; i<n; i++)… Such a variable is known as the control variable Its value controls the iteration of the for Copyright ©1999-2012 Curt Hill

Variable Declaration in a For The variable in the initialization may be declared at that time: for(int j = 0; j < k; j++) It does not have to be a pre-existing variable Thus the for and the compound statement allow declarations within them This is the only location that allows a declaration within the for Copyright ©1999-2012 Curt Hill

Scope So where is the variable known? The variable declared in a for is known only in the for header and the one statement that follows it The variable is created by the for It is destroyed when the for is exited Consider the next example Copyright ©1999-2012 Curt Hill

Scope of a for control variable int j = 5, k; cin >> k; int sum = 0; for(int j = 2; j<k;j++){ sum = sum*j – k/2; k += 2; } cout << k << “\n”; int val = 1; for(int k = 1;k<j;k++) val = val*k; cout << val << “\n”; // larger scope // scope of j // scope of k Copyright ©1999-2012 Curt Hill

Final words on initialization The control variable does not have to be any particular type It may also be left out Suppose that the variable that you want as a control variable is already properly set Leave out the initialization Retain the semicolon int a,b=2; cin >>a; for(;b<a;b++)… Copyright ©1999-2012 Curt Hill

The test The test is evaluated before every execution of the body of the loop If it is true then the body is executed Otherwise the loop is exited The test is any boolean expression May include comparisons Of any type on any variables May include boolean operators &&, || or ! May also be a boolean variable May be any numeric Copyright ©1999-2012 Curt Hill

More on the test It is usually some test on the control variable Does not have to be related to either the initialization or advancement k = 1; for(int i = 1;k>0;i++){ cin >> k; cout << i << “: “ << k; } Copyright ©1999-2012 Curt Hill

Advancement Third piece of the for header Only executed after the body of the loop Always before the test on the second and subsequent times through the loop May be any expression Usually a ++ or – applied to control variable Copyright ©1999-2012 Curt Hill

Advancement examples The usual is count by constant one: for(i=0;i<j;i++) … for(i=0;i<j;i--) … By any constant: for(double f=0;f<g;f+=0.25) … The count by n: for(i=0;i<j;i+=n) … Power of 2 for(i=1;i<j;i*=2) … Something else: for(d=1.0; d<m; d+=ln(d)) Copyright ©1999-2012 Curt Hill

The Body of the Loop is one statement Compound statement Assignment Function or Method call Another for Nested loops are also interesting Any other statement Empty statement How can the body be empty? Copyright ©1999-2012 Curt Hill

Empty statement How can the body be empty? If we do all the work in the header Suppose we want to compute the factorial: n! = 1*2*3*…*n int fact = 1,n; cin >> n; for(int i=1;i<n;fact*=++i); cout << fact; // not in for Copyright ©1999-2012 Curt Hill

Common Error Sometimes we want the body of the for to be empty Much more frequently we put a semicolon there by accident: for(i=1;i<=n;i++); fact *= i; The assignment on fact is only executed once since the empty statement is the body of the loop Copyright ©1999-2012 Curt Hill

Nested Loops Nested loops are complicated from an execution viewpoint, but not from syntax There is nothing like the else matching problem of the if statement The only thing to remember is that the inner loop must not interfere with the outer loop’s test and advancement Copyright ©1999-2012 Curt Hill

Nested Interference Consider the following two problems: for(i=0;i<10;i++) for(i=0;i<12;i++)… The outer loop is nullified The inner loop leaves i larger than the test requirements of the outer loop for(i=0;i<10;i++) for(i=0;i<5;i++)… This is an infinite loop The inner loop always leave i at 5 Outer loop gets it to 6 but is then reset to 5 by the inner loop Copyright ©1999-2012 Curt Hill

Control error problem 1 We can get similar problems without nesting Modification of the control variable in the loop: for(i=0;i<5;i++){ … i--; … } This is an infinite loop Copyright ©1999-2012 Curt Hill

Control error problem 2 Modification of the control variable in another way: for(i=0;i<5;i++){ … i++; … } This will terminate but is deceptive The double counting makes it hard to read Copyright ©1999-2012 Curt Hill

Moral of story Do not change the control variable except in the header If the control variable needs to be changed in multiple places or not at end of loop use a while Programmers reading the code will not look for another change The best you can get is hard to read code The worst is an infinite loop There are better ways to get that if desired Copyright ©1999-2012 Curt Hill

For flow chart a Suppose the following loop: for(a;b;c) d; c b d true false Copyright ©1999-2012 Curt Hill

Order of execution Suppose the following loop: for(a;b;c) d; The order of execution is: a, b, (d, c, b)* Thus, these are possible: a, b a, b, d, c, b a, b, d, c, b , d, c, b a, b, d, c, b , d, c, b , d, c, b … Copyright ©1999-2012 Curt Hill

For Equivalent to a While The while is the most general loop of many languages, such as Pascal or VB Not so in the C family of languages Any while may be converted to an equivalent for: while(cond)… can be written as for(;cond;)… just leaving out the initialization and advancement Copyright ©1999-2012 Curt Hill

String Processing Fors are frequently used to process strings and arrays s[i] is the ith character of the string s Process an AnsiString: for(int i=1;i<=s.Length(); i++){ char ch = s[i]; // process ch } Copyright ©1999-2012 Curt Hill

Example: counting blanks Count the blanks in string s int blanks=0; for(int i=1;i<=s.Length(); i++){ char ch = s[i]; if(ch==‘ ‘) blanks++; } // end for Count control characters by changing == to < or <= Copyright ©1999-2012 Curt Hill

Equality tests Beware Not just real number equality comparisons but all If the value is not hit, then infinite loop Don’t do: for(i=0,i!=5;i+=2) instead for(i=0,i<=5;i+=2) especially when counting by things other than one Copyright ©1999-2012 Curt Hill

The Comma Operator In C family comma is an operator The unusual operator It appears that is was first intended to be the way to bundle statements together Perhaps before braces There are some things that you can do with commas and others you should do with braces Copyright ©1999-2012 Curt Hill

What does it do? The comma operator cuts off expression evaluation It specifies that the thing on the left is executed first and the thing on the right second Because of this there is no carryover from one side of the statement to the other Does not define pieces as statements Copyright ©1999-2012 Curt Hill

More Unlike use of the semicolon, it does not constitutes a statement Usually used only in places where you need to do multiple thing but can only do one thing and cannot use braces: The initialization and incrementation of for loops Anywhere else a pair of braces is not acceptable Very low precedence Below = Copyright ©1999-2012 Curt Hill

Example 1 In a for doing several things, with comma: for(i=5,s=0.8;i<10;i++,s+=k) This presumes i and s are declared else where A declaration forces all types to be the same for(int i=5,j=2;i<10;j+=k*++i) Is legal but for(int i=5,double j=2;i<10;i++) Is not Copyright ©1999-2012 Curt Hill

Example 2 Can also be used elsewhere: if(a>b) cout << “True”, b++, a--; The comma separates the cout from b and a No error but no output of b and a Although this is better: if(a>b){ cout << “True”; b++; a--; } Copyright ©1999-2012 Curt Hill

Last thoughts The for control variable usually has no real world meaning One of the few variables where a one character name is acceptable Indentation of the for body is also a good idea This gives better readability We will also later consider the break and continue Copyright ©1999-2012 Curt Hill