Lecture 4 Repetition Structures
Lecture 4 Repetition Structures
Structures - Repetition
BJ Furman
17SEP2012
The Plan for Today
Review control structures
Sequence
Selection
Repetition
Repetition structures
While
Do/While
For
Repetition structure example
Learning Objectives
Explain the three basic types of control
structures
Explain how the three kinds of repetition
structures work
Apply the concept of repetition control
structures to a practical problem
Control Structures - Review
All programs can be written in terms of three
control structures (like building blocks)
Sequence
‘Built-in’ to C
Unless otherwise directed, one statement after the next is
executed
Selection (three types: IF, IF-ELSE, SWITCH)
Depending on a condition, select between one statement or
another
If var1 is greater than 10, do this…, else do that…
Repetition (three types: WHILE, DO-WHILE, FOR)
Depending on a condition, execute one or more statements
repeatedly
Selection Structure - Review
Three kinds of selections structures
IF (also called, ‘single-selection’)
if condition is true
Perform action
if condition is false, action is skipped
IF/ELSE (also called, ‘double-selection’)
if condition is true
Perform action
else (if condition is false)
Perform a different action
SWITCH (also called ‘multiple-selection’)
Allows selection among many actions depending on the
value of a variable or expression
Repetition Structure
t=0
Often need to repeat
an action or calculation
Ex. Find and print the
distance traveled by an
object dropped from a t=10
height at t = 0 sec each
second over the next
10 seconds A dynamics problem (ME 101)
Repetition structures
are often called ‘loops’
F m a
mg
1 2
d gt v0t d 0 Equation
of motion
2
3 Types of Repetition Structures
while
do/while
for
while tests a condition at the beginning of the loop
condition must first be true for the loop to run even once
do/while tests a condition at the end of the loop
loop will run at least once
for facilitates initializing and incrementing the variable
that controls the loop
Especially helpful for:
Looping for a known number of times
Loops that count or that need to increment a variable
while Loop – Pseudocode wording
WHILE condition is TRUE, repeat:
Statement1
Statement2
Etc.
END WHILE
while Loop - Flowchart View
Statement is
executed while
condition is true
Note that the TRUE
condition statement
condition must
first be true in
order for the FALSE
statement to
be executed
even once
while loop C syntax
General form of a while loop:
while(condition) /* while condition is TRUE (i.e., ! = 0) */
statement1; /* execute this statement */
When condition becomes false (i.e. == 0),
looping stops and the next statement is
executed
Compound statement form:
while(condition)
{
statement1;
statement2;
statement3; // etc.
}
Distance Dropped Program Development
d (distance traveled)
t (time) T 1
(Are these good names?) t <= 10? d gt 2
2
3. Initialize variables
F print t, d
4. While time is less than
or equal to 10 s t = t +1
calculate d while
print time loop
print distance Stop
increment time
5. Stop
Solution Code
free_fall_d_vs_time.c
Implements the program for the freely falling
mass
Practice - Procedure
Procedure
Divide into groups of 4
Introduce yourselves
Together (all four in the group)
Define the problem
Determine inputs and outputs
Split into pairs (sub-groups)
One pair – pseudocode the algorithm
Other pair – flowchart the algorithm
Swap one from each pair and share pseudocode and
flowchart
Write code from flowchart or pseudocode
Practice - Problem
Write a program that calculates the
average exam score for a class
Specifications
Prompts user for the number of scores to average
Prompts user for each score
TRUE
condition
FALSE
for Loop Structure
General form of a for loop:
for(expression1; expression2; expression3)
statement1; /* execute this statement */
expression1 initializes the variable controlling the loop
i = 0;
expression2 is the condition for continuing the loop
i <= 10;
expression3 increments the control variable
i++ /* same as i=i+1 */
Note that there is NO semicolon after expression3! or after the
closing parenthesis
To execute more than one statement in the for loop, enclose them
in curly braces { }
for Loop Structure – Flow Chart
Initializes the loop
control variable:
ex. i = 0;
expression1
F
Increments the
loop control
variable:
ex. i++
for Loop Example
double_it.c
Prints out a table of integers from 0 to 10 in
one column and twice their value in a second
column
break and continue Statements
break immediately continue skips
exits from a loop remaining statements
Recall its use in the in the body of a
switch selection structure
int x;
repetition structure
for(x=1; x<=10; x++)
int x, y;
{
for(x=1; x<=10; x++)
if(x == 5)
{
break;
if(x == 5)
printf("%d ", x);
{
}
y = x;
printf("Broke out at x == %d\n",x);
continue;
}
1 2 3 4 Broke out at x == 5
printf("%d ", x);
}
printf("Skipped x == %d\n",y);
1 2 3 4 6 7 8 9 10 Skipped x == 5
Adapted from Deitel & Deitel, C How to Program, 3rd ed., p. 119
Appendix – Recap of Selection Structures
Selection Structure
Three kinds of selections structures
if (also called, ‘single-selection’)
if condition is true
Perform action
if condition is false, action is skipped
if/else (also called, ‘double-selection’)
if condition is true
Perform action
else (if condition is false)
Perform a different action
switch (also called ‘multiple-selection’)
Allows selection among many actions depending on the
value of a variable or expression
IF statement (single-selection)
Syntax
if(expression) /* if expression is TRUE (not equal to zero) */
statement1; /* then execute this statement */
statement2; /* otherwise execute this statement */
Notes
Indent statements
Can have multiple statements
Enclose a ‘block’ of statements using { } (curly braces)
if( x <= 2 )
{
statement1;
statement2;
}
statement3;
IF statement example
Pseudocode (notice indentation!)
If speed is greater than 65 mph
print “You’re speeding!”
C code
if(speed > 65)
printf(“You’re speeding!\n”);
C code with statement block
if(speed > 65)
/* statements below executed only if speed > 65 is true */
{
printf(“You’re speeding!\n”);
printf(“Slow down!\n”);
printf(“Keep speed below 65 MPH\n”);
{
Single Selection IF - Flowchart
connector
flow line
action symbol
decision symbol
TRUE
Speed > 65 Print “You’re speeding!”
FALSE
IF-ELSE statement - Double Selection
Syntax
if(expression) /* if expression is TRUE */
statement1; /* execute this statement */
else /* else execute the following statement */
statement2;
Notes:
If expression is non-zero, statement1 is executed, then the
program continues with the statement after statement2,
i.e., statement2 is skipped
If expression is equal to zero, statement1 is skipped and
statement2 is executed, then the program continues with
the statement after statement2
Double-Selection IF - Flowchart
FALSE TRUE
Print “Within limit” Speed > 65 Print “Over speed limit!”
IF-ELSE statement example
Pseudocode (notice indentation!)
If speed is greater than 65 mph
print “Over speed limit!”
else
print “Within speed limit”
C code
if(speed > 65)
printf(“Over speed limit!\n”);
else
printf(“Within limit\n”);
Relational Operators
Operations Associativity
::
Important for constructing () [] left to right
the decision expression Function_name() right to left
. -> left to right
‘ ! ` ++ -- + - * right to left
Practice &(type) sizeof
* / % .* ./ left to right
5 < 7 result is ____ + - left to right
<< >> left to right
5 > 7 result is _____ < <= > >= left to right
7 <= 7 result is ____ == != left to right
& left to right
8 >= 7 result is ____ ^ left to right
5 == 5 result is ____ | left to right
&& left to right
5 == 7 result is ____ ^^ left to right
5.0 == 5 result is ___ || left to right
Or
Adapted from Deitel & Deitel, C How to Program, 6th ed., p. 111
Review
References
Darnell, P. A. & Margolis, P. E. (1996) C, a
software engineering approach, 3rd ed.,
Springer, New York.
Cheng, H. H. (2010). C for Engineers and
Scientists: An Interpretive Approach,
McGraw-Hill, New York.
Deitel, H. M. & Deitel, P. J. (2001). C How
to Program, 3rd ed., Prentice-Hall, New
Jersey.
Nesting selection structures
/* File: ifc.c */
Selection structures #include <stdio.h>
int main ()
can be stacked and {
int i;
nested to handle i = 10;
if(i==2 || i == 4)
more sophisticated {
printf("i = 2 or 4\n");
}
decision/action else if(i == 10)
{
functionality }
printf("i = 10\n");
else
{
printf("i = %d\n", i);
}
return 0;
}
() [] left to right
Function_name() right to left
. -> left to right
‘ ! ` ++ -- + - * right to left
&(type) sizeof
* / % .* ./ left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
^^ left to right
|| left to right
?: right to left
= += -= *= /= %= |= right to left
<<= >>=
, left to right