Nested and Flag Controlled Loops


Lessons


Nested and Flag Controlled Loops

Authored by: Lex Jacobson & John Even

Faculty Supervisor: Al Day

Some material derived from lessons authored by Prof. Martha Selby

HTML Documentatiion by Larry Genalo Jr.

Date Last Updated: 8/7/95


Nested Loops:


Nested For Loops:

Example:
				Results
for (m=1; m<=4; m++) { (m) (n) for (n="1;" n<="3;" n++) { 1 1 printf("%d %d\n", m, n); 1 2 } 1 3 } 2 1 2 2 2 3 3 1 Note: Inside loop is 3 2 executed 3 times for 3 3 each of the 4 times the 4 1 outside loop is executed! 4 2 4 3 


Loop structures can become complicated and hard to follow. It can sometimes be difficult and confusing to place an expression in its ususal spot.

Many times a flag can help to simplify the condition.

A flag is type int variable used to represent whether or not a certain event has occured. It is often initialized to 0 where it remains until the event occurs. When the event occurs, the flag is changed to 1.


The following program uses a while loop to approximate a root of the function 2x2-6.2x+3.6 using the interval-halving method. The variable done is a flag used to determine when the root has been approximated to the desired precision (TOL). When the desired precision is reached, the flag, done changes and looping can stop.