Академический Документы
Профессиональный Документы
Культура Документы
PROBLEM SOLVING
CST1101
LOOPS
Lesson 5
Lecture 4
CST1101
Printing Numbers
Using a IF/THEN/ELSE
Long Way
PRINT 1
PRINT 2
PRINT 3
PRINT 10
PRINT 11
PRINT 12
..
PRINT 99
PRINT 100
NUMBER:
1. NUMBER = 1
2. PRINT NUMBER
3. IF (NUMBER = 100)
THEN {STOP}
ELSE {ADD 1 TO NUMBER
GO TO 2}
Lecture 4
CST1101
Printing Numbers
Lets allow our user to tell
us the starting number, and ending number
Using a IF/THEN/ELSE
NUMBER:
FIRST:
LAST:
1.
2.
3.
4.
Lecture 4
CST1101
Lecture 4
CST1101
Printing Numbers
FOR LOOP
FOR (INDEX = START ; INDEX < LAST ; ADD STEP VALUE)
{
(instructions)
}
1. INPUT FIRST, LAST
2. FOR (NUMBER = FIRST; NUMBER <= LAST; ADD 1 to NUMBER)
{
PRINT NUMBER
}
Lecture 4
Notes
1. The end of loop body (}) instruction
adds one (the step value) to the
index (NUMBER) and jumps back
to instruction 2
2. Every time we get to instruction 2
we check that NUMBER is still <=
LAST
CST1101
CST1101
Printing Numbers
FOR LOOP
FOR (INDEX = START ; INDEX < LAST ; ADD STEP VALUE
{
(instructions)
}
1. INPUT FIRST, LAST, STEP
2. FOR (NUMBER = FIRST; NUMBER < LAST; ADD STEP to NUMBER)
{
PRINT NUMBER
}
CST1101
Lecture 4
CST1101
Printing Numbers
Using a WHILE Loop
There is another way to think about
a loop like this in many programming
languages:
NUMBER:
1.
2.
3.
4.
WHILE LOOP
While a condition is true,
Keep doing the loop
1. INPUT FIRST, LAST
2. STORE FIRST IN NUMBER
3. WHILE (NUMBER < LAST)
{
ADD 1 TO NUMBER
}
Lecture 4
CST1101
10
CST1101
11
Printing Numbers
Using a WHILE Loop
There is another way to think about
a loop like this in many programming
languages:
NUMBER:
1.
2.
3.
4.
WHILE LOOP
While a condition is true,
Keep doing the loop
1. INPUT FIRST, LAST
2. NUMBER = FIRST
3. WHILE (NUMBER < LAST)
{
PRINT NUMBER
ADD 1 TO NUMBER
}
Lecture 4
CST1101
12
Lecture 4
CST1101
13
Printing Numbers
There is another way to think about
a loop like this in many programming
languages:
WHILE LOOP
While a condition is true,
Keep doing the loop
Lecture 4
CST1101
14
Lecture 4
CST1101
15
X OO
X
O X X
CST1101
16
CST1101
17
X OO
X
O X X
CST1101
18
CST1101
19
X OO
X
O X X
CST1101
20
Lecture 4
CST1101
21
Lecture 4
CST1101
22