Repetition and Loops

Lessons

Credits for Lecturing and Authoring
Looping Statements
While Structure
While Example
Do ... While Structure
While vs. Do While...
For Loops
General Form of a for Statement
Steps in Executing a for Loop
For Loop Rules
Flowcharting for Loops

Credits for Lecturing and Authoring

Authored by: John Even

Edited by: Lex Jacobson

Faculty Supervisor: Al Day

Some Material Derived From Lessons Authored by Dr. James Hilliard and Prof. Martha Selby

HTML Documentation by Larry Genalo Jr.

Date Last Updated: 7/24/96

Looping Statements

Looping statements allow the computer to repeat a series of steps.

e.g. while Loop, do while Loop, for Loop

while Structure

while Example

/* Sum all integers greater than 0 whose
squares are less than 1000.*/
#include 
int
main (void)
{
     int sum=0, n=1;
     while (n*n<1000) { sum="sum" + n; n="n+1;" } return (0); } 

do ... while Structure

while vs. do while...

Use a do while loop whenever you want the loop body to be executed at least once, otherwise use a while loop.

for Loops

A special statement that constructs an iterative loop (a loop that is repeated a specified number of times).

General Form of a for Statement

Steps in Executing a for Loop

  1. Control variable assigned initial value.
  2. Check if loop repetition condition is true. If it is not, do NOT execute the loop, and jump to the statement following the body of the loop.
  3. Execute the body of loop.
  4. Change the value of the Control variable.
  5. Repeat steps 2, 3, and 4 until the loop condition checked in step 2 is false.

for Loop Rules

for (i=INITIAL;i&ltLIMIT;i+=STEP)

  1. INITIAL, LIMIT, and STEP can be:
    Positive OR Negative;
    Integer OR Double;
    Constants OR Variables OR Expressions
  2. DO NOT change the value of i, the control variable, inside the loop, unless there is no step function in the for statement.
  3. Changing the value of INITIAL inside the loop has no effect on the number of times the loop is executed.
  4. After the for loop is completed, the control variable, i, contains the last value that exceeded the LIMIT.
  5. You can have a for loop without an initialization statement and without a change of the loop control variable: for (;i<6;) The variable must then be initialized elsewhere, and updated WITHIN the for loop.
Note: This kind of loop is essentially a while loop.

Example 1:

for (i=1; i<=5, i++) { printf("%d\n", i); } RESULTS: 1 2 3 4 5 

Example 2:

for (num=10; num>1; num-=2)  {
         printf("%d\n", num);
 }

  RESULTS:
	10
	 8
	 6
	 4
	 2

Example 3:

for (n=10; n<1; n++) { printf("%d\n", n); } RESULTS: (Nothing Loop not executed) 

Flowcharting for Loops

There are a number of different ways to represent for loops in a flowchart.
Four ways to flowchart the following for loop will be shown.

for (i=1; i<30; i+="2)" { sum="sum+1;" }