Вы находитесь на странице: 1из 46

Loops

CSIS1117 Computer Programming

Content

While loop
Type casting
For loop
Increment/decrement
Nested loop
Do-while loop
Break statement
Switch statement

c1117 lecture 6

Looping constructs

Consider a problem: If we want to find the sum of


3 input positive integers.

You may write something like:

int
int total
total =0;
=0; int
int x;
x;
cout
cout <<
<< "Enter
"Enter 33 positive
positive integers:
integers: ";
";
cin
cin >>
>> x;
x; total
total == total
total ++ x;
x;
cin
cin >>
>> x;
x; total
total == total
total ++ x;
x;
cin
cin >>
>> x;
x; total
total == total
total ++ x;
x;
cout
cout <<
<< The
The sum
sum is
is <<
<< total
total <<
<< endl;
endl;

How about finding the sum of an arbitrary no. of


positive integers?

c1117 lecture 6

Looping constructs

Now we want to find the sum of a sequence of


positive integers. The user can type as many input
as he wants until zero is entered.

Then you may want something like:


int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
if(
if( xx >> 0)
0)
{{ total
total == total
total ++
if(
if( xx >> 0)
0)
{{ total
total == total
total ++
if(
if( xx >> 0)
0)
{{ total
total == total
total ++
...
...

c1117 lecture 6

x;
x;

x;
x; cin
cin >>
>> x;
x; }}
x;
x; cin
cin >>
>> x;
x; }}
x;
x; cin
cin >>
>> x;
x; }}

We dont
know how
many times
it takes!!
4

While loop

While loop help to execute one or a group of


statements (the body) repeatedly while a
condition is satisfied.

The previous program can be written as:


int
int total
total =0;
=0; int
int x;
x;
Condition
cin
>>
x;
cin >> x;
while(x
while(x >> 0){
0){
total
total == total
total ++ x;
x;
Body
cin
>>
x;
cin >> x;
}}
cout
cout <<
<< "The
"The sum
sum is:
is: "" <<
<< total
total <<
<< endl;
endl;

c1117 lecture 6

While loop

see sum-loop.cc

In evaluating a while loop

the condition is evaluated first


If the result is false, the body of the loop is skipped and
the while loop is terminated.
If the result is true, the body is executed once, then the
whole while loop is executed again.

Each round of execution of a loop is called an


iteration.

c1117 lecture 6

While loop
While condition the while body is executed only if
the condition is evaluated to be true

while
while (( condition
condition ))
single_statement1;
single_statement1;
next_statement;
next_statement;

while
while (( condition
condition )) {{
group_statement1;
group_statement1;
group_statement2;
group_statement2;
....
....
}}
next_statement;
next_statement;

While body it can be a single or a block statement(s).


c1117 lecture 6

While loop
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

x;
x;

Memory
address
1004

10

x
total

1008
x;
x;

10
10

Main memory

Command prompt
c1117 lecture 6

While loop
true!
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

Condition return
true, the body is
executed.
c1117 lecture 6

x;
x;

Memory
address
1004

10

x
total

1008
x;
x;

10
10

Main memory

Command prompt
9

While loop
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

Read in the

2nd

input

x;
x;

Memory
address
1004

15

1008

10

total

x;
x;

10
10
15

Main memory

Command prompt
c1117 lecture 6

10

While loop
true!
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

The while loop is


executed again, and the
condition is checked.
c1117 lecture 6

x;
x;

Memory
address
1004

15

1008

10

total

x;
x;

10
10
15
15

Main memory

Command prompt
11

While loop
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

Read in the

3nd

input

x;
x;

Memory
address
1004

-1

1008

25

total

x;
x;

10
10
15
15
-1

Main memory

Command prompt
c1117 lecture 6

12

While loop
false!
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

The condition return


false, the while loop is
terminated.
c1117 lecture 6

x;
x;

Memory
address
1004

-1

1008

25

total

x;
x;

10
10
15
15
-1
-1

Main memory

Command prompt
13

While loop
false!
int
int total
total =0;
=0; int
int
cin
cin >>
>> x;
x;
while(x
while(x >> 0){
0){
total
total == total
total ++
cin
cin >>
>> x;
x;
}}

The body wont be


executed.
c1117 lecture 6

x;
x;

Memory
address
1004

-1

1008

25

total

x;
x;

10
10
15
15
-1
-1

Main memory

Command prompt
14

Example 1

Write a program to read in a string and print it in


the reverse order. e.g. abcd dcba.
How we can do it? We can locate the last character
and print it out. Then locate the second last
character, print it out until the first character

Assignment

tnemngissA

We can use a while loop to solve this problem


c1117 lecture 6

15

Writing loop statement

We usually need to involve variables in the


program for counting the no. of iteration that have
been passed so far. These variables are commonly
called loop variables.

e.g. in this example, we need a loop variable to count


the no. of characters that have been printed.

In writing loop statement, we need to consider:

What are the statements that needed to repeat.


What is the condition for controlling the loop.
What loop variable(s) is/are needed.
How many iterations it taken (if it is known).

c1117 lecture 6

16

Example 1

Idea: We can design a loop scanning from the last


character of the string to the first character, and
print them out one by one.
Loop variable: representing the no. of characters
that have been printed
Body: print out the last nth character where n is
specified by the loop variable.
No of iteration: the length of the string, ie.
s.length().
Condition: execute the body if the loop variable is
small than s.length()

c1117 lecture 6

17

Example 1
The no. of character printed before the
loop is zero.
string input;
cin >> input;
int i = 0;
while (i < input.length()){
cout << input[input.length()- i - 1];
i = i + 1;
}

Update the loop variable so that


the loop can terminate.

See reverse.cc

c1117 lecture 6

18

Writing loop statement

Note that some of the statements in the body


should update some variables used in the loop
condition.

Make sure that the condition eventually becomes false


and hence the loop can terminate.
If not, the loop is infinite.
e.g. if the statement i = i+1 is missing, the loop can
not be terminated. See infinite.cc as an example.

int i
while
cout
}
c1117 lecture 6

= 0;
(i < input.length()){
The condition is
<< input[input.length()- i - 1];
always true, the loop
will not stop.
19

Remember to initialize variables used in the


condition before starting the loop.
The condition is evaluated before each loop
iteration.

If the loop body has been executed n times, the


condition should be checked n+1 times, the last
checking is evaluated to be false and the loop is
terminated.

If the condition fails at the very beginning, the


loop body is not executed at all.

c1117 lecture 6

20

Example 2

Write a program to take a non-negative integer n


and report the value of n! (n-factorial).
n! =

when n=0

n(n-1)(n-2)2*1

when n>0

We need to take n multiplications in calculating n!. We


can write a loop looping from 1 to n (takes n iterations),
and perform one multiplication in each iteration.
Loop variable: represents the no. of multiplication that
has be done. Its initial value is 0.

c1117 lecture 6

21

Example 2

Body: calculate the multiplication specified by the loop


variable, and increment the loop variable by one.
No of Iteration: Equal to the no. of multiplication, ie. n.
Condition: execute the body if the loop variable is
smaller than n.

Notice that if the body is executed n times, the


condition is checked n+1 times, for the loop
variable changing from 1 to n+1.

c1117 lecture 6

22

Example 2
The body is executed n
times, from i = 1 to n.
int
cin
int n;
n;
cin >>
>> n;
n;
int
int ii == 0;
0; int
int result
result == 1;
1;
while(
while( ii << n){
n){
result
result == (i
(i ++ 1)
1) ** result;
result;
ii == ii ++ 1;
1;
}}
cout
cout <<
<< "The
"The factorial
factorial is:"
is:" <<
<< result
result <<
<< endl;
endl;

The condition is checked n+1 times, from i = 1 to


n+1 (The last checking is for termination).

See factorial.cc

c1117 lecture 6

23

Example 3

Write a function that takes a positive integer x and


returns true if it is a prime number.

A prime number is a positive integer (greater than 1)


that has no positive integer divisors other than 1 and
itself.
e.g. the only divisors of 13 are 1 and 13, so 13 is a
prime, while 24 has divisors, 1, 2, 3, 4, 6 ,8, 12 and 24,
so 24 is not a prime.
We can write a while loop scanning from 2 to x -1, and
check if there are any divisors within the range.

c1117 lecture 6

24

Example 3

Loop variable: represents the current value for checking.


Its initial value is 2.
Body: check if x is divisible by the value specified by the
loop variable.
No of iterations: x 2, scanning from 2 to x -1
Condition: The body is executed if the loop variable is
no greater than x.

We can write a function, which take an unsigned


int as parameter, return true if it is a prime, and
false otherwise.

c1117 lecture 6

25

Example 3
bool
bool isPrime(unsigned
isPrime(unsigned int
int
unsigned
unsigned int
int ii == 2;
2;
while(
while( ii << x){
x){
if(x
if(x %% ii ==
== 0)
0) return
return
ii == ii ++ 1;
1;
}}
return
return true;
true;
}}

x){
x){

false;
false;

Can we do better?

Notice that we are not necessary to check all the even


number, as 2 is the common divisor for all even
numbers greater than 2.

c1117 lecture 6

26

Example 3

The number of iterations can be divided by half!!


bool
bool isPrime(unsigned
isPrime(unsigned int
int x){
x){
if(x
if(x ==
== 2)
2) return
return true;
true;
if(x
if(x %% 22 ==
== 0)
0) return
return false;
false;
unsigned
unsigned int
int ii == 3;
3;
while(
while( ii << x){
x){
if(x
if(x %% ii ==
== 0)
0) return
return false;
false;
ii == ii ++ 2;
2;
}}
return
return true;
true;
}}

Increment the loop variable by 2, as


we only check the odd numbers.

c1117 lecture 6

27

Example 3

Again, can we do better?


Given a positive integer x, we can check if it is a
prime by dividing it with 2 to x, if there exist a
divisor in the range, then x is not a prime.

Why x is the largest potential divisor?


If y is a divisor of x, and y > x. It means that there
must exist another divisor z, where z < x, such that
yz = x.

Therefore:

To check 137, divide it by 3, 5, 7, 9, 11


To check 193, divide it by 3, 5, 7, 9, 11, 13

c1117 lecture 6

28

Example 3

Warning is given by
compiler due to the
//
// Assume
Assume xx is
is greater
greater than
than 33 incompatible type.
bool
bool isPrime(unsigned
isPrime(unsigned int
int x){
x){
unisgned
unisgned int
int ii == 3;
3;
unsigned
unsigned int
int sqrt_x
sqrt_x == sqrt(x)
sqrt(x) ++ 1;
1;
while(
while( ii << sqrt_of_x){
sqrt_of_x){
if(x
if(x %% ii ==
== 0)
0) reutrn
reutrn false;
false;
ii == ii ++ 2;
2;
}}
return
return true;
true;
}}
Why we need to increment 1 here?

See prime.cc for the full program

c1117 lecture 6

29

Type casting

We have used sqrt() to find the upper limit of the


factor to be tested.
Note that sqrt() returns a double value.
Assigning a double value to an int, warning
message is given, a typecast is used to tell the
compiler that the loss of precision is acceptable.

This can help to fix the warning message.

unsigned int sqrt_x = static_cast<int>sqrt(x)+1;

Tell the compiler explicitly that you want to


change the value returned by sqrt() to type int.
c1117 lecture 6

30

Precision problem
unsigned int sqrt_x = static_cast<int>sqrt(x)+1;

Why we need to increment 1? It is due to


the precision problem in computer.

A floating point value cannot be represented


exactly in the computer, so error may occur.

sqrt(19 * 19) may return a value like 18.99999..


Error may happen if we try to cast the the value.
static_cast<int>sqrt(19 * 19);

c1117 lecture 6

18
18
31

Type casting

string is not a build-in type, we cannot cast any


types to string or vice versa.
How about bool to int?

bool int: true 1, false 0


int bool: 0 false, non-zero true

How about char to int?

Casting char to int is based on the ASCII character set.


char 'c' is corresponding to 99 in ASCII code
char ch
int x =
cout <<

= 'c';
static_cast<int>(ch);
"x = " << x << endl;

xx == 99
99

See casting.cc as an example

c1117 lecture 6

32

for loop

If the no. of iterations is known before loop begins,


we can use for loop to rewrite the while loop.

The program in reversing the string can be simplified as


follow:

string
cin
string input;
input;
cin >>
>> input;
input;
int
int ii == 0;
0;
while
while (i
(i << input.length()){
input.length()){
cout
cout <<
<< input[input.length()input[input.length()- ii -- 1];
1];
ii == ii ++ 1;
1;
}} string input;
cin
string input;
cin >>
>> input;
input;
for(int
for(int ii == 0;
0; ii << input.length();
input.length(); ii == ii ++ 1){
1){
result
result == ii ** result;
result;
}}
c1117 lecture 6

33

for loop

Let look at the for statement piece by piece.


Syntax
for(expr0; expr1; expr2)
{...}

expr0: tells how the variable is initialized.


expr1: the condition that is used to check if the loop
should end.
expr2: tells how the loop control variable is updated
after each iteration of the loop body.

c1117 lecture 6

34

The program to calculate the n-factorial can also


be written in for loop.
int n;
cin >> n;
Updating the loop
int i = 0; int result = 1;
variable after
while( i < n){
each iteration
result = (i + 1) * result;
i = i + 1;
}
for (int i = 0; i < n; i = i + 1){
result = (i + 1) * result;
}

Initializing the
loop variable

c1117 lecture 6

Condition for checking


the end of loop
35

Scoping rule

The variables declared inside a for statement can only


be referred to within the for statement.
for (int i = 0; i < n; i = i + 1){
int j;
...
}

Both the variables i and j are the local


variables of the for statement.

See for-scope.cc as an example

c1117 lecture 6

36

Increment/decrement

It happens quite often that we need to increment


or decrement a variable by one.

e.g. in updating the loop variables.


k = k + 1;
i = i - 1;

They can be rewritten using the variants of assignment


operators.
k += 1;
i -= 1;

// k = k + 1;
// i = i 1;

We can also use the increment or decrement operators.


++k;
--i;

c1117 lecture 6

37

Nested loop

There are many problems that we need to write a


loop in which one or more statements are
themselves loops.

For example, if we want to print a flag composing of 10


lines of characters, each line consisting of 10 stars.
for(int
for(int ii == 0;
0; ii << 10;
10; ++i){
++i){
for
for (int
(int jj == 0;
0; jj << 10;
10; ++j)
++j)
cout
cout <<
<< "*";
"*";
cout
cout <<
<< endl;
endl;
}}

See flag.cc as an example

c1117 lecture 6

38

do-while loop

The body of a while/for loop only execute if the


condition is true.
If the body of the loop is executed before the first
checking of the condition, we can use do-while
loop, in which, the body is executed at least once.
do
do {{
group_statement1;
group_statement1;
group_statement2;
group_statement2;
....
....
}} while
while (condition);
(condition);
next_statement;
next_statement;

c1117 lecture 6

Semicolon
should be
added here
39

Example

Prompt for a number between 0 to 100; repeat the


loop until the number within the range is entered.

We notice that the loop stop only if a number within the


range is entered, so the body should be executed at
least once.
int
int num;
num;
do{
do{
cout
cout <<
<< "pls
"pls enter
enter aa number
number in
in
range
range [0..100]"
[0..100]" <<
<< endl;
endl;
cin
cin >>
>> num;
num;
}} while
while (num
(num << 00 ||
|| num
num >> 100);
100);

c1117 lecture 6

40

break

break: Sometime we want to exit a loop before it


ends in a normal way.

For example, the loop might contain a check for


improper input and if some improper input encountered,
then we may want to simply end the loop.
A break statement exits the inner-most loop

Problem: enter positive numbers, add them up,


stop when 0 entered.

Without break, we may need to duplicate some codes.

c1117 lecture 6

41

break
int
int num,
num, sum;
sum;
cout
cout <<
<< Enter
Enter aa
cin
cin >>
>> num;
num;
while(num
while(num >> 0){
0){
sum
sum +=
+= num;
num;
cout
cout <<
<< "Enter
"Enter
cin
cin >>
>> num;
num;
}}
cout
cout <<
<< "The
"The sum
sum

number
number (0
(0 to
to end)
end) :";
:";

aa number
number (0
(0 to
to end)
end) :";
:";

is
is "" <<
<< sum
sum <<
<< endl;
endl;

These two pieces of codes are duplicated in the


program
c1117 lecture 6

42

break
int
int num,
num, sum;
sum;
while(true){
while(true){
cout
cout <<
<< "Enter
"Enter
cin
cin >>
>> num;
num;
if(num
if(num ==
== 0)
0)
break;
break;
sum
sum +=
+= num;
num;
}}
cout
cout <<
<< "The
"The sum
sum

aa number
number (0
(0 to
to end)
end) :";
:";

Check and exit


the loop if the
input is zero
is
is "" <<
<< sum
sum <<
<< endl;
endl;

Use break, we can eliminate the code duplication problem.

See loop-and-half.cc as an example.

c1117 lecture 6

43

Switch statement

switch statement help to implement multiway


branches.

An alternative to cascaded if/else statements, we


always can rewrite a switch statement by if/else
statement.
When a switch statement is executed, one of a number
of different branches is executed.
The selection criteria allows only integral values, e.g. int,
bool, char, etc, but cannot be used for strings.
Usually a case is ended with a break.
Use default to catch the remaining cases.

See dayofweek-switch.cc, monthdays-switch.cc.

c1117 lecture 6

44

Switch statement
switch(label){
switch(label){
Which alternative is
case
case constant_1:
constant_1:
Statement_sequence_1
executed depends on
Statement_sequence_1
break;
the label,
break;
case
statement_sequence_1
case constant_2:
constant_2:
Statement_sequence_2
Statement_sequence_2
is executed if
break;
break;
label=constant_1
...
...
case
case constant_n:
constant_n:
Statement_sequence_n
colon must be applied
Statement_sequence_n
break;
for each case.
break;
default:
default:
Default_statement_sequence
Default_statement_sequence
}}
c1117 lecture 6

45

Switch statement

The following program read in a grade and print


out comments for different grades.

char
char grade;
grade; cin
cin >>
>> grade;
grade;
switch(grade){
switch(grade){
case
case 'A':
'A':
cout
cout <<
<< "Excellent!"
"Excellent!" <<
<< endl;
endl; break;
break;
case
case 'B':
'B':
cout
cout <<
<< "Very
"Very good!"
good!" <<
<< endl;
endl; break;
break;
case
case 'C':
'C':
cout
cout <<
<< "Passing."
"Passing." <<
<< endl;
endl; break;
break;
case
case 'F':
'F':
cout
cout <<
<< "Fail."
"Fail." <<
<< endl;
endl; break;
break;
default:
default:
cout
cout <<
<< "It
"It is
is not
not aa possible
possible grade"
grade" <<
<< endl;
endl;
}}
c1117 lecture 6

46

Вам также может понравиться