CS -113
Computer Programming
and Software
Loops - Basics
Outline
• From selection to repetition
• Why do we need loops?
• Counting Loops
• Conditional Loops
• While Loop
• For Loop
• Infinite Loop
Text book 5.1.1, 5.2.1, 5.2.4
From Selection to Repetition
● The if statement and if/else statement allow a block of
statements to be executed selectively: based on a
condition, if condition is true
int inputnumber;
cout << "Please enter a non-negative number" << endl;
cin >> inputnumber;
if (inputnumber < 0) {
cout << inputnumber << " is negative. Wrong Input";
}
1
From Selection to Repetition
● This piece of code does not ask another input if number < 0
● While statement repeatedly executes a block of statements while
the condition is true
int inputnumber;
cout << " Please enter a non-negative number" << endl;
cin >> inputnumber;
while (inputnumber < 0) {
cout << inputnumber << " is negative! Try again" << endl;
cin >> inputnumber;
}
2
From Selection to Repetition
3
Why we need loops?
● We want to find the sum of 10 positive values so we can write:
int num1, num2, num3, num4, num5;
int num6, num7, num8, num9, num10;
int sum;
cin >> num1 >> num2 >> num3 >> num4 >> num5
>> num6 >> num7 >> num8 >> num9 >> num10;
sum = num1 + num2 + num3 + num4 + num5;
sum += num6 + num7 + num8 + num9 + num10;
4
Why we need loops?
● We want to find the sum of 10 positive values.
● Let’s do it with a while loop:
int sum = 0; // this program piece
int i = 1; // calculates the sum of
while (i <= 10) // integers between 1 and 10
{ // inclusively
sum = sum + i;
i = i + 1;
}
5
Walkthrough of the example
su 0 1
m
int sum = 0; i 1 2
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
6
Walkthrough of the example
su 1 3
m
int sum = 0; i 2 3
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
7
Walkthrough of the example
su 3 6
m
int sum = 0; i 3 4
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
8
Walkthrough of the example
su 6 10
m
int sum = 0; i 4 5
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
9
Walkthrough of the example
1
su 15
m 0
int sum = 0; i 5 6
int i = 1;
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
10
Walkthrough of the example
4
su 55
m 5
1
int sum = 0; i 11
int i = 1; 0
while (i <= 10)
{
sum = sum + i;
i = i + 1;
}
11
Example – [Link]
●Write a program to calculate 10 numbers that were given
by the user
●This type of loops are called counting loops
●number of iterations is known
12
Example – [Link]
● What if we want to compute the sum of
● 100 values
● an undetermined number of values
● Read a sequence of integer numbers from keyboard and find their sum
● input should finish when user enters –1
● -1 is the sentinel value in this example
● not to be added to the sum
● This type of loop is called conditional loop
● number of iterations is not known
● depends on input
13
while loop syntax
<initialization>
while (<test>)
{
<statement1>;
...
<statementN>;
<update>
}
14
while loop syntax
int sum = 0; initialization
int i = 1;
while (i <= 10) test
{
sum = sum + i; body
statements
i = i + 1; updat
} e
15
Anatomy of a loop
● Initialize variables used in loop body and loop test (before the loop)
● No general rule; the way of initialization and the initial values are to
be determined according to the application
● The loop test is evaluated before each loop iteration
● NOT evaluated after each statement in the loop body
● Current value of variables are used for the loop test before each
iteration
● The loop body must update some variables used in the loop test so that
the loop eventually terminates
● If loop test is always true, loop is infinite
● Infinite loops must be avoided
16
Basic rule of designing a loop
●Initialization, loop test and update parts should be designed
carefully in order to iterate the loop as many times as
needed, but not one less or one more.
●Unfortunately there is no straightforward rule of designing a
bug-free loop
● you should be able to develop those parts by
understanding and analyzing the underlying problem that
needs a loop
17
for loop
<initialization> for(<initialization>;<test>;<update>)
while(<test>) {
{ <statement1>;
<statement1>; ...
<statementN>;
...
}
<statementN>;
<update>
} ● Initialization, test and update parts are
combined
● Good for counting on an index kind of loops
18
for loop
•Rewrite the same loop: sum of numbers from 1..10
int sum = 0; int sum = 0;
int i = 1;
while (i <= 10) for (int i=1; i <= 10; i=i+1)
{ {
sum = sum + i; sum = sum + i;
i = i + 1; }
}
19
for loop
● initialization statement
● executed once before the loop
● test expression
● boolean expression
● checked each time before entering the loop body
● if true execute loop body, if false terminate loop
● update statement
● executed after the last statement of the loop body
20
for loop
● several statements in initialization and update are separated by comma
for (len = [Link](), k=0; k < len; k+=1)
● initialization and/or test and/or update parts could be missing
● but semicolons are there
int k = 0;
for (; k < len; k+=1)
21
Shorthand for increment/decrement
● Lots of code requires incrementing a variable by one
● Three methods, using = and +, using +=, and using ++
● effectively they are same
num = num + 1;
num += 1;
num++; // post increment
● It is also possible to write ++num;
● pre-increment
● These differ on when the increment is performed, but this difference doesn't
matter when used as an abbreviation for the statement n += 1; in a single
statement
● Similarly there are post-decrement (and pre-decrement)
num = num - 1; num -= 1; num--; 22
Bad Loops
1. for (int i = 10; i < 5; i++) {
cout << "How many times do I print?";
}
2. for (int i = 10; i >= 1; i++) {
cout << "How many times do I print?";
}
3. int i = 1;
while (i < 20) {
cout << "How many times do I print?";
} 26
Bad Loops
● Never executes
● Never stops (infinite loops)
● Example: consider the following modified code from sum10nums
● What’s the problem in the loop below? What is missing?
int num;
int sum = 0;
int count = 1;
while (count <= 10) {
cin >> num;
sum += num;
}
27
Bad Loops
● Never executes
● Never stops (infinite loops)
● Example: consider the following modified code from sum10nums
● What’s the problem in the loop below? What is missing?
int num;
int sum = 0;
int count = 1;
while (count <= 10) {
cin >> num;
sum += num;
}
● count never reaches 10,
because count is not updated in the loop
28
Infinite Loops
● Infinite loop is something that must be avoided
● happens when the loop condition is always true
● same loop body iterates forever
● sometimes you see an output, sometimes you don't
● press Ctrl-C to stop (⌘. on Xcode)
● could be because of a wrong or missing update statement
● could be because of a wrong condition
● could be another reason
29
Infinite Loops
● What is the problem with the code below?
cin >> num;
int start = 0;
while (start != num) {
start += 2;
cout << start << endl;
}
30
Infinite Loops
● What is the problem with the code below?
cin >> num;
int start = 0;
while (start != num) {
start += 2;
cout << start << endl;
}
● cannot say infinite loop, depends on input number
● for example, if num is an odd number, then the loop is infinite
● How to fix?
31
Infinite Loops
● What is the problem with the code below?
cin >> num;
int start = 0;
while (start != num) {
start += 2;
cout << start << endl;
}
● cannot say infinite loop, depends on input number
● for example, if num is an odd number, then the loop is infinite
● How to fix? Check whether num is even before starting the loop.
if (num % 2 == 0){
while (start != num) {
start += 2;
cout << start << endl;
}
}
32
Infinite Loops
● What is the problem with the code below?
cin >> num;
int start = 0;
while (start != num) {
start += 2;
cout << start << endl;
}
● cannot say infinite loop, depends on input number
● for example, if num is an odd number, then the loop is infinite
● How to fix? Check whether num is even before starting the loop.
if (num % 2 == 0){
while (start != num) {
start += 2;
cout << start << endl;
}
}
33
Developing Loops
● Some loops are easy to develop, others are not
● Sometimes the proper loop test and body are hard to design
● Practice helps, but remember:
● Good design comes from experience, experience comes from bad
design
34
Common Problems
● Easy to iterate one more or one less times
● Test each loop with the inputs that cause:
● zero iterations of the loop body
● one iteration of the loop body
● maximum number of iterations
● one less than the maximum number of iterations
● Use the debugger and watch the variables
35