Topic 6 Reading
Topic 6 Reading
Topic 6 Reading
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
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.
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.
2. for-loops (mainly a "counting loop" construct – do the following ten times –but can
serve in more general roles)
Repeat-loops are the least common; for-loops can become a bit complex; so, it is usually
best to start with "while" loops.
While loop:
Syntax is as follows:
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.
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 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
while (true)
{
cout << "hi";
}
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;
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.
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.
int main()
{
int sum = 0, num;
Remember:
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.
Try typing out the program in Dev C++ and see the results for yourself:
int main()
{
//declare and initalize
float minimum, maximum, average = 0.0;
float sum = 0.0, count = 0, score;
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;
A for loop is like a while statement, except that it requires three statements/expressions in
the parenthesis. Its syntax is as follows:
Figure 3: gives a simple example of using a for loop with start, range and increment.
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
Figure 4: shows a flow chart for a “for loop” for the above code.
Program Run
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.
cout<<“i=“<<i<<“,j=“<<j<<endl;
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
If you have lots of time on your hand, you may try writing an infinite for loop! Just type:
for (;;)
cout << “Hi “;
{
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;
Characters: So far we’ve known that char variables can hold only a single character.
Have to use single quotes when initializing
Example:
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:
Also make note that the increment value part uses something strange, count++, j-- etc.
What are these?
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.
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
counter = counter + 1;
counter++;
++counter;
counter += 1;
and
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.
Dinesh 03/02/2004
*/
#include <iostream>
int main()
int n, sum = 0, i;
cin >> n;
sum += i;
cout << "\nThe sum of the first " << n << " numbers is "
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?
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.
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:
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
}
Figure 7: gives a breakdown of the “while loop” and defines each line of code.
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:
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.
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.