Topic 6 Reading

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Topic 6 – Loops

Table of Contents
Learning Outcomes: ................................................................................................................... 2
What Is the Purpose of a Loop? ................................................................................................. 3
Repetition in C++: 3 Forms ..................................................................................................... 3
How to Create an Infinite Loop? ............................................................................................ 5
How Do You Avoid Writing These Kinds of Loops? ................................................................ 5
Example Two: Loop to Print Even Numbers Between 2 and 100;...................................... 6
Sentinel Controlled while Loops ............................................................................................ 6
Example: Program to Find the Sum of Positive Numbers ................................................. 6
Using &&, || and! .................................................................................................................... 16
Quick Question 1:..................................................................................................................... 17
Review Exercises ...................................................................................................................... 18

CS111: Introduction to Computing Science 1|P a g e


Learning Outcomes:
At the end of this topic, students should be able to understand the following:

 to implement while, for, and do loops


 to understand nested loops
 to implement programs that make understanding better these loops

In a loop, a part of a program is repeated over and over, until a specific goal is reached.
Loops are important for calculations that require repeated steps and for processing input
consisting of many data items. In this chapter you will learn about loop statements in C++,
as well as techniques for writing programs that process input and simulate activities in the
real world.

CS111: Introduction to Computing Science 2|P a g e


What Is the Purpose of a Loop?
A loop is a statement that is used to execute one or more statements repeatedly until a goal
is reached. Sometimes these one-or-more statements will not be executed at all if that’s the
way to reach the goal.
C++ has these three looping statements:
 while
 for
 do

Along with conditionals (if …else if …else…), this is one of the basic structures of
programming. Loops can be created to execute a block of code for a fixed number of times.
(e.g. 9 or 19 or 90 times).

Alternatively, loops can be created to repetitively execute a block of code until a condition
changes to a wanted state.

For instance, the loop may continue until a condition changes from false to true, or from
true to false. In this case, the block of code being executed must update the condition being
tested in order for the loop to terminate at some point. If the test condition does not
change somehow within the loop, the loop will never terminate - the so known 'endless
loop'. This is logical error.
Loop constructs permit more interesting programs.

Repetition in C++: 3 Forms

1. while-loops (while condition X is true keeping doing the following ...)

2. for-loops (mainly a "counting loop" construct – do the following ten times –but can
serve in more general roles)

3. repeat-loops (do the following ... while condition Z still true)

Repeat-loops are the least common; for-loops can become a bit complex; so, it is usually
best to start with "while" loops.

CS111: Introduction to Computing Science 3|P a g e


Figure 1: shows the “while loop” structure and what each lines mean.

While loop:
Syntax is as follows:

while (tested condition is satisfied)


{
block of code
}

The while loop is used to execute a block of code, as long as some condition(s) is(are) true. If
the condition is false from the start, the block of code is not executed at all.
The while loop tests the condition before it's executed so sometimes the loop and the
statements inside may never be executed if initially the condition is not met.

The condition is always in the form of a Boolean expressions or anything that has or results
in a value of either true or false

Note: In all constructs, curly braces {} should be used if the construct is to execute more
than one line of code. The above program executes only one line of code so it is not really
necessary to enclose them in curly braces. (Same rules apply to if...else constructs) but you
can use them to make the program seem more understandable or readable.

Here is a simple example of the use of the while loop.

It prints out numbers from 1-100.

CS111: Introduction to Computing Science 4|P a g e


int count = 1; //initialize counter

while (count <= 100)


{
cout << count << endl;
count = count + 1; // Notice this statement
}

Note that no semi-colons (;) are to be used after the while (condition) statement. These
loops are very useful because the condition is tested before execution begins.

We call this a Pre-Test loop.

We also call this type of loops where the number of times to execute the statements in the
loop is known in advance as Counter Controlled Loops.
Notice the condition in the while loop results in truth 100 times but on the 101 st pass it
evaluates to false. This triggers the end of the while loop.

More so, in order for the loop to end, the condition being tested must be modified in some
way.

For example: in the above program, variable count is modified and the modified value is
tested on each pass of the loop;

Video Links:

1. http://www.youtube.com/watch?v=KLKhsaOPnLk
2. http://www.youtube.com/watch?v=8Cy7shy-Jjo
3. https://www.youtube.com/watch?v=EXwBcBJyWZw

How to Create an Infinite Loop?

Just omit the statement count = count + 1; in the above program.


Or simple write:

while (true)
{
cout << "hi";
}

How Do You Avoid Writing These Kinds of Loops?


You can’t!!!
Just have to be VERY careful when creating any type of loops. For that you have to
understand the structure of loops well.

CS111: Introduction to Computing Science 5|P a g e


Example Two: Loop to Print Even Numbers Between 2 and 100;

int counter = 2; //start from 2

while (counter <= 100)


{
cout << counter << endl; //print even number
counter = counter + 2; //increment by two
}

A slight variation of Counter Controlled loops

Example: if we want to ask the user to tell us how many even numbers to print (up to which
number), we can make it a variable and ask the user for its value when the program is run.
Such as:

counter = 2;

cout << “Enter number of terms: “;


cin >> numTerms;

while (counter <= numTerms)


{
cout << counter << endl; //print even number
counter = counter + 2; //increment by two
}

Sentinel Controlled while Loops

Unlike counter controlled loops where the number of times the loop must execute is known
in advance, sentinel controlled loops are terminated when the user types a terminating
number or character.

Example: Program to Find the Sum of Positive Numbers

Let us assume that all numbers we are interested in are >=0 but we don’t know how many
numbers there are and whether in any particular sequence.

We can type in the numbers one after the other and when we get to the end we can type in
a negative number which will stop the loop.

CS111: Introduction to Computing Science 6|P a g e


#include <iostream>

using namespace std;

int main()
{
int sum = 0, num;

cout << "Enter Number: ";


cin >> num;
while (num >= 0){
sum = sum + num;
cout << "\nEnter Number: ";
cin >> num;

cout << "\nSum is: " << sum << endl;


system("PAUSE");
}

Remember:

The variable in the condition must be updated.


The only way to know when to finish the loop is to ask the user for a new number. It could
be a negative.
Statements like:

counter = counter + 1;
sum = sum + num;
monkey = monkey + 2;

I call them accumulators; for instance, the value of num is added to whatever is in sum.

CS111: Introduction to Computing Science 7|P a g e


Figure 2: Tabulates the uses of a while loop giving an ascending, descending and no output if improperly used.

Try typing out the program in Dev C++ and see the results for yourself:

CS111: Introduction to Computing Science 8|P a g e


Code: Student mark processor.
/*
Dinesh 02/02/2004
Student mark processing program;
Average, minimum and maximum calculation;
*/
#include <iostream>
Using namespace std;

int main()
{
//declare and initalize
float minimum, maximum, average = 0.0;
float sum = 0.0, count = 0, score;

cout << "Enter a score: ";


cin >> score;
maximum = score;
minimum = score;

while (score >= 0.0)


{ //process value
sum = sum + score;
count = count + 1;
if (score > maximum)
maximum = score;
else if (score < minimum)
minimum = score;

cout << "\nEnter a score: ";


cin >> score; //get next value
}

if (count == 0) //avoid division by zero


cout << "\nNo data entered." << endl;
else
{
average = sum / count;
cout << "\nThere were " << count << " scores." << endl;

cout << "Average = " << average << endl;


cout << "Maximum score = " << maximum << endl;
cout << "Minimum score = " << minimum << endl;
}

system("PAUSE");
}
Problem Solving
Consider this question:

int n = 738;
int sum = 0;
int digit;
while(n>0){
digit=n % 10;
sum = sum + digit;
n = n/10;
}
cout << "Sum: " << sum;

CS111: Introduction to Computing Science 9|P a g e


 What is the hand trace?
 What is computed?

Work this out for yourself!


FOR…loops

In simple words….To execute statements a certain number of times…

A for loop is like a while statement, except that it requires three statements/expressions in
the parenthesis. Its syntax is as follows:

CS111: Introduction to Computing Science 10 | P a g e


for (initialization(s); test_condition(s);
increment_value)
statement;
OR
for (initialization(s); test_condition(s);
increment_value)
{
statement;
statement;
statement;
etc;
}

Notice that each expression must be terminated by a semi-colon (;)

The simplest way to understand for loops is to study several examples.


First, here is a for loop that counts from 1 to 10.

for (count = 1; count <= 10; count++)


{
cout << count << endl;
}

Figure 3: gives a simple example of using a for loop with start, range and increment.

C++ for Everyone


by Cay Horstmann
Copyright © 2012 by John Wiley & Sons. All rights reserved

CS111: Introduction to Computing Science 11 | P a g e


A very good example of a for loop is given below from the textbook regarding calculating
money when initially it’s invested till its maturity date:

for (int year = 1; year <= nyears; year++)


{
Update balance.
Print year and balance.
}

Web Reference:
Web references:

http://www.processing.org/reference/for.html

Video Links:

1. http://www.youtube.com/watch?v=8Cy7shy-Jjo
2. http://www.youtube.com/watch?v=b-eYJEYYAsk
3. http://www.youtube.com/watch?v=sBO8yvyyBI0

The flow chart below belongs to the corresponding program:


Flowchart of a for Loop

Figure 4: shows a flow chart for a “for loop” for the above code.

C++ for Everyone


by Cay Horstmann
Copyright © 2012 by John Wiley & Sons. All rights reserved

CS111: Introduction to Computing Science 12 | P a g e


1 #include <iostream>
2
3
4 using namespace std;
5
6 int main()
7 {
8 const double RATE = 5;
9 const double INITIAL_BALANCE = 10000;
10 double balance = INITIAL_BALANCE;
11 int nyears;
12 cout << "Enter number of years: ";
13 cin >> nyears;
14
15 cout << fixed << setprecision(2);
16 for (int year = 1; year <= nyears; year++)
17 {
18 balance = balance * (1 + RATE / 100);
19 cout << setw(4) << year << setw(10) << balance<<endl;
20 }
21
22
23 }

Program Run

Enter number of years: 10


1 10500.00
2 11025.00
3 11576.25
4 12155.06
5 12762.82
6 13400.96
7 14071.00
8 14774.55
9 15513.28
10 16288.95

CS111: Introduction to Computing Science 13 | P a g e


Figure 5: gives more examples of writing “for loops” and the avlues of “i” that is printed out.

C++ for Everyone


by Cay Horstmann
Copyright © 2012 by John Wiley & Sons. All rights reserved

The test conditions may be unrelated to the variables being initialized and updated. Here is
a loop that counts until a user response terminates the loop.

for (count = 1; response != 'N'; count++)

cout << count << endl;


cout <<"Silly man, you still want to continue? (Y/N): “;
cin >> response;
}

More complicated test conditions are also allowed.


Suppose the user of the last example never enters "N", but the loop should terminate when
100 is reached, regardless.

for (count = 1; (response != 'N') && (count <= 100); count++)


{
cout << count << endl;
cout <<"Silly man, you still want to continue? (Y/N): “;
cin >> response;

It is also possible to have multiple initializations and multiple actions.


This loop starts one counter at 0 and another at 100, and finds a midpoint between them.
(This is advanced material!).

CS111: Introduction to Computing Science 14 | P a g e


for (i = 0, j = 100; j != i; i++, j--) ;//note, where’s the
statement?

cout<<“i=“<<i<<“,j=“<<j<<endl;

All of the constituent parts of the statement are optional.

The initialization, condition, increment sections of the for loop can be blank. For instance,
suppose we need to count from a user specified number to 100. The first semicolon is still
required as a place keeper

cout << "Enter a number to start the count: ”;


cin >> count;

for ( ; count <= 100 ; count++)


{

cout << count << endl;

If you have lots of time on your hand, you may try writing an infinite for loop! Just type:

for (;;)
cout << “Hi “;

The actions are also optional.


Here is a silly example that will repeatedly echo a single number until the user terminates
the loop;

for (number = 5; response != 'N' && response != ‘n’;)

{
cout << number << endl;;
cout << “You still want to look at this? (Y/N) \n");
cin >> response;
}

Note: Any for loop can be represented using a while loop. For instance, if we try to write a
similar structure for a while loop, we’d have:

initializations;
while (tested_conditions)

{
statements;
increment counter value;

CS111: Introduction to Computing Science 15 | P a g e


Some finer observations:
It’s also possible to write compound logical expressions in the condition part.

Using &&, || and!


Example:

if (gender == ‘m’ && age >= 50)



while (value >= 0 || sum <= 100)

Characters: So far we’ve known that char variables can hold only a single character.
Have to use single quotes when initializing

Example:

char gender = ‘m’;

When used in logical comparison statements must use single quotes too.

Example:

if gender == ‘m’
cout << “Chicken”;

But if you want to output characters to screen, enclose them with double quotes “”

Example:

cout << “Hi Dad! How you doing!”;

Also make note that the increment value part uses something strange, count++, j-- etc.
What are these?

Contractions in C++ (Assignment statements revisited)

C++ is famous for its contractions. You have seen the following two common ones:

Increment Decrement
a = a + 1; b = b – 1;

Remember we used similar statement as above for our counter: count = count + 1
Shorthand versions of these are:

Increment Decrement
a++ or ++a b-- or --b

If the assignment is on its own there isn't a difference between them but if they are used in
an expression the order matters.

CS111: Introduction to Computing Science 16 | P a g e


++a means increment and then use the value of a.
a++ means use the value of a and then increment

a = 3; is equivalent to a = 3;
b = ++a; a = a + 1;
b = a;

a = 3; is equivalent to a = 3;
b = a++; b = a;
a = a + 1;

It is safer not to use the construct in an expression but only on its own when the order
doesn’t matter. i.e.

number = 1;
cout << 1 + 3 + number++; Prints out: 5

number = 1;
cout << 1 + 3 + ++number; Prints out: 6

Another common expression is: a = a + n; which can be chopped into :


a += n;
Hence these expressions are all equivalent:

counter = counter + 1;
counter++;
++counter;
counter += 1;

and

sum = sum + num;


sum += num;

Quick Question 1:
Write the C++ contraction for the following code:
twosTime = twosTime * 2;
num = num / x;
sum = sum + 10;
value = value + 1;

Given below is a program which you could copy on Dev C++ and see what it does. This is an
example of using a for loop.

CS111: Introduction to Computing Science 17 | P a g e


/*

Dinesh 03/02/2004

Summing arithmetic progression

*/

#include <iostream>

using namespace std;

int main()

int n, sum = 0, i;

cout << "Enter a value for n: ";

cin >> n;

for (i=1; i<=n; i++)

sum += i;

cout << "\nThe sum of the first " << n << " numbers is "

<< sum << endl << endl;

system("PAUSE");

Review Exercises
1. You put $10,000 into a bank account that earns 5 percent interest per year. How
many years does it take for the account balance to be double the original
investment?

Could you solve this problem by hand?

Ans: Sure. You figure out the balance as follows:

CS111: Introduction to Computing Science 18 | P a g e


You keep going until the balance is at least $20,000. Then the last number in the year
column is the answer.

Of course, carrying out this computation is intensely boring to you or your younger brother.
But computers are very good at carrying out repetitive calculations quickly and flawlessly.
What is important to the computer is a description of the steps for finding the solution. Each
step must be clear and unambiguous, requiring no guesswork.
Here is such a description:

Start with a year value of 0, a column for the interest, and a balance of $10,000.

Repeat the following steps while the balance is less than $20,000
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest)
Add the interest to the balance.

Report the final year value as the answer.

CS111: Introduction to Computing Science 19 | P a g e


This informal description is called pseudocode. There are no strict requirements for
pseudocode because it is read by human readers, not a computer program.

Figure 6: shows flow chart that explains the algorithm

In C++, the while statement implements such a repetition.

while (condition)
{
statements
}

The code keeps executing the statements while the condition is true. In our case, we want
to increment the year counter and add interest while the balance is less than the target
balance of $20,000:

while (balance < TARGET)


{

year++;
double interest = balance * RATE / 100;
balance = balance + interest;
}

CS111: Introduction to Computing Science 20 | P a g e


Explanation:

Figure 7: gives a breakdown of the “while loop” and defines each line of code.

C++ for Everyone


by Cay Horstmann
Copyright © 2012 by John Wiley & Sons. All rights reserved

Important:

When you define a variable inside the loop body, the variable is created for each iteration of
the loop and removed after the end of each iteration. For example, consider the interest
variable in this loop:

while (balance < TARGET)


A new interest
{ variable is
year++; created in each
double interest = balance * RATE / 100;
balance = balance + interest;
} // interest no longer defined here

In contrast, the balance and years variables were defined outside the loop body. That way,
the same variable is used for all iterations of the loop.

CS111: Introduction to Computing Science 21 | P a g e


Figure 8: is a step by step breakdown and memory allocation of “balance, year and interest”.

C++ for Everyone


by Cay Horstmann
Copyright © 2012 by John Wiley & Sons. All rights reserved

Work out the code now? (See page 135 of textbook for guidance)

2. Using the same question above, how would you implement a “for loop”?

The “for loop” neatly groups the initialization, condition, and update expressions
together. However, it is important to realize that these expressions are not executed
together.

CS111: Introduction to Computing Science 22 | P a g e


Figure 9: gives the execution of a “for loop”

(See page 145 of the textbook for guidance)

Whats Next? ---proceed to lab question!

CS111: Introduction to Computing Science 23 | P a g e

You might also like