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