Ryerson University Department of Computer Science CPS 125 Alexander Ferworn Week 5 Flow of Control: Looping (or Iteration) What we will cover this week o some stuff about libraries o loops o while o do while o for o nested loops o break o continue o goto Libraries ---------- o As was mentioned before, one of the reasons C is such a small language is that it defers many operations to a large runtime library. o The runtime library is a collection of object files containing the machine code for a function that performs one of a wide variety of services. o The functions are divided into groups o For each group there is a header file (or .h file) that contains information needed to use the functions. stdio.h is such a file The following examples show how you can figure out how to use a function described in a reference text; #include <math.h> double pow(double x, double y); The pow() function returns the value of x raised to the power of y. What this means; o The #include tells you what library you need to include in you source C file. o the "double" in front of the function name tells you what the type is of the thing that pow() returns...in this case pow() returns a double value. o pow() is the name of the function o the stuff in the () are arguments to pow()..things it needs to calculate the answer. o functions want their arguments to have certain types in this case pow wants x to be double and y to be double. This is all the information you need to use pow() #include <math.h> void main() { double val1,val2, val3; val1 = 3.0; val2 = 2.0; val3 = pow(val1,val2); } Here is sqrt(); #include <math.h> double sqrt(double x); The sqrt() function returns the nonnegative square of root x. If x is negative a domain error occurs. Here is rand(); #include <stdlib.h> int rand(void); The rand() function returns an integer between 0 and RAND_MAX... Loops ----- C gives you a choice of three types of loop, while, do while and for. o The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed. o The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once. o The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers. The while Loop The while loop repeats a statement until the test at the top proves false. -an example: simple /* print out the even numbers from 0 to 102 */ void main() { short ival=0; while(i<=102) { printf("%d\n",ival); ival = ival + 2; } } -an example: a bit backwards /* print out the even numbers from 102 to 0 */ void main() { short ival=102; while(ival) { printf("%d\n",ival); ival = ival - 2; } } -an example: complex #include <stdio.h> /* Program to guess an integer number from 1 to 10 by asking clever questions. Alex Ferworn CPS125 Winter 97 */ void main() { char ans; /* char is character type..stored in 1 byte */ short next=5; /* this is the next range of numbers ot check */ short inc=3; /* this is the increment to get the next number after next */ short upbound=10; /* the maximum thing in the bound */ short lowbound=1; /* the minimum thing in the bound */ while((next>0) && (next<10)) { if((next>upbound) || (next<lowbound)) printf("That's impossible!\n"); printf("Greater than or less than %d? (g = greater, l = less)\n", next); scanf("%c",&ans); fflush(stdin); switch(ans) { case 'g': case 'G': lowbound = next+1; next = next + inc; inc = 1; break; case 'l': case 'L': upbound = next-1; next = next - inc; inc = 1; break; default: printf("The number was %d!\n",next); next = 11; } } } -an example: Knowing when the input will stop using EOF (End Of File); /* keep reading and printing the contents of a file */ #include <stdio.h> void main() { short ival; while(scanf("%d",&ival) != EOF) printf("%d",ival); } The do while Loop ----------------- o This is very similar to the while loop except that the test occurs at the end of the loop body. o This guarantees that the loop is executed at least once before continuing. o Such a setup is frequently used where data is to be read. o The test then verifies the data, and loops back to read again if it was unacceptable. -an example: simple /* mall rat code */ ... do { printf("Enter 1 for yes, 0 for no :"); scanf("%d", &input_value); } while ((input_value != 1) && (input_value != 0)); The for Loop ------------- o The for loop works well where the number of iterations of the loop is known before the loop is entered. o The head of the loop consists of three parts separated by semicolons. 1) The first is run before the loop is entered. This is usually the initialisation of the loop variable. 2) The second is a test, the loop is exited when this returns false. 3) The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter. -an example: #include <stdio.h> void main() { long fact=1; short input,j; printf("Enter a number to find the factorial of\n"); scanf("%d",&input); for(j=2;j<input;j++) fact = fact *j; printf("The factorial was %d\n",fact); } o The three statements at the head of a for loop usually do just one thing each, however any of them can be left blank. o A blank first or last statement will mean no initialisation or running increment. o A blank comparison statement will always be treated as true. o This will cause the loop to run indefinitely unless interrupted by some other means. This might be a o return or a break statement. o It is also possible to squeeze several statements into the first or third position, separating them with commas. o This allows a loop with more than one controlling variable. o The example below illustrates the definition of such a loop, with variables hi and lo starting at 100 and 0 respectively and converging. -an example: for (hi = 100, lo = 0; hi >= lo; hi--, lo++) The for loop is extremely flexible and allows many types of program behaviour to be specified simply and quickly. a while can always replace for. for(<exp1>;<exp2>;<exp3>) statement; becomes, <exp1> while(<exp2>) { ... <exp3> } an example; for(i=0;i<100;i++); becomes i=0; while(i<100) i++; Nested loops ------------- o Similarly to ifs and switches you can nest loops. an example: /* what does the following code do? */ ... for(i=0;i<10;i++) for(j=0;j<10;j++) printf("%d%d\n",i,j); ... The same example but spaced out a bit: ... for(i=0;i<10;i++) { for(j=0;j<10;j++) { printf("%d%d\n",i,j); } } ... notes: o You need to put one complete loop into another...they cannot overlap. The break Statement -------------------- o We have already met break in the discussion of the switch statement. o It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. o With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. o A break within a loop should always be protected within an if statement which provides the test to control the exit condition. for example: ... while(1) /* infinite loop */ { printf("Enter 1 to exit\n"); scanf("%d",&ans); if(ans == 1)break; } ... The continue Statement ----------------------- o This is similar to break but is encountered less frequently. o It only works within loops where its effect is to force an immediate jump to the loop control statement. -In a while loop, jump to the test statement. -In a do while loop, jump to the test statement. -In a for loop, jump to the test, and perform the iteration. Like a break, continue should be protected by an if statement. You are unlikely to use it very often. an example; ... /* print out all the odd numbers from 1 to 101 */ for(i=1;i<=101;i++) { if(!(i%2)) continue; printf("%d",i); } The goto Statement ------------------- o C has a goto statement which permits unstructured jumps to be made. o Its use is not recommended because its hard to debug code with lots of jumping around. it works like this; goto <label>; ... <label>: and example ... /* this is a stupid program */ over: for(i=0;i<1000;i++) printf("%d",i); goto over; ... o Actually, you can simulate any type of loop using only goto and if then. ... for(i=0;i<2,i++) printf("%d",i); ... becomes... ... goto end; again: printf("%d",i); i++; end: if(i<2) goto again; ...