You are on page 1of 1

My library > EE 1301: Introduction to Computing S… >

 4.4: For loops  zyBooks catalog  Help/FAQ  Max Kenney

4.3 More while examples

Students:

 Section 4.4 is a part of 1 assignment: zyBooks - Reading 5 Requirements: PA CA


Due: 10/08/2023, 11:59 PM CDT

4.4 For loops


Basics

A loop commonly must iterate a speciHc number of times, such as 10 times. Though achievable with a while loop, that situation is so
common that a special kind of loop exists. A for loop is a loop with three parts at the top: a loop variable initialization, a loop expression,
and a loop variable update. A for loop describes iterating a speciHc number of times more naturally than a while loop.

Construct 4.4.1: For loop.

for (initialExpression; conditionExpression; updateExpression) {


// Loop body
}
// Statements after the loop

Feedback?

PARTICIPATION
ACTIVITY 4.4.1: For loops.

1 2 3 2x speed

int i; int i;

i = 0; for ( i = 0; i < 5; i = i + 1 ) {
while (i < 5 ) { // Loop body
// Loop body }
i = i + 1;
}

i: 0 (Iterates)
1 (Iterates)
5 iterations
2 (Iterates)
3 (Iterates)
4 (Iterates)
5 (Does not iterate)

Note that semicolons separate the three parts. No semicolon is needed at the end.

Captions 
1. This while loop pattern with i = 0 before, loop expression i < 5, and loop body ending with i = i + 1, iterates 5 times: when i = 0, 1, 2,
3, and 4.
2. The pattern is so common that a special construct, a for loop, exists to collect the three parts in one place at the loop's top,
improving readability and reducing errors.
3. Note that semicolons separate the three parts. No semicolon is needed at the end.

Feedback?

The statement i = i + 1 is so common that the language supports the shorthand ++i, with ++ known as the increment operator. (Likewise, --
is the decrement operator, --i means i = i - 1). As such, a standard way to loop N times is shown below.

Figure 4.4.1: A standard way to loop N times, using a for loop.

int i;
...
for (i = 0; i < N; ++i) {
...
}

Feedback?

PARTICIPATION
ACTIVITY 4.4.2: For loops.

1) What are the values of i for each iteration of:


Correct
for (i = 0; i < 6; ++i) {
... i starts with 0. When i reaches 6, the loop body will not be
} entered because 6 < 6 is false.
1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6

2) How many times will this loop iterate?


Correct
for (i = 0; i < 8; ++i) {
... The iterations will be for i of 0, 1, 2, 3, 4, 5, 6, and 7;
} counting those yields 8 iterations.
7 times
8 times
9 times

3) Goal: Loop 10 times


Correct
for (i = 0; _____; ++i) {
... The 10 iterations will have i of 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
} (Because counting started at 0, iterating with i = 10 would
yield 11 iterations.).
i<9
i < 10
i < 11

4) Goal: Loop 99 times


Correct
for (i = 0; _____; ++i) {
... The iterations will have i of 0, 1, ..., 97, 98.
}

i < 99
i <= 99
i == 99

5) Goal: Loop 20 times


Correct
for (____; i < 20; ++i) {
... Because the comparison is i < 20, then i should start with
} 0. (If the comparison was i <= 20, then i should start with
1).
i=0
i=1

6) Goal: Loop numYears times (numYears is an int variable).


Correct
for (i = 0; _____; ++i) {
... The desired number of iterations is commonly in a
} variable like numYears. If numYears is currently 5, then
the loop will iterate with i as 0, 1, 2, 3, and 4 (so 5
numYears
iterations).
i <= numYears
i < numYears

Feedback?

PARTICIPATION
ACTIVITY 4.4.3: For loops.

Write for loops using the following form:

for (i = 0; i < 10; ++i) {

Note: Using a variable other than i is not accepted by this activity.

1) Complete the for loop to iterate 5 times. (Don't forget the semicolon).
Correct
for (i = 0; i<5; ++i) {

... i < 5;
}
The loop will iterate with i of 0, 1, 2, 3, and 4, so 5
iterations.
Check Show answer

2) Complete the for loop to iterate 7 times.


Correct
for ( i=0;i<7; ++i) {

... i = 0; i < 7;
}
The loop will iterate with i of 0, 1, 2, 3, 4, 5, and 6, so 7
iterations.
Check Show answer

3) Complete the for loop to iterate 500 times. (Don't forget the
parentheses). Correct

for (i=0;i<500;i++) { (i = 0; i < 500; ++i)

... The loop will iterate with i of 0, 1, ..., 488, and 499, which
} is 500 iterations.

Check Show answer

4) Complete the for loop to iterate numDogs times. numDogs is an int


variable. Correct

for (i = 0; i<numDogs; ++i) { i < numDogs;

... The loop will iterate with i of 0, 1, ..., numDogs-1. So if


} numDogs is 5, the loop will iterate with i as 0, 1, 2, 3, and
4 (so 5 times).
Check Show answer

Feedback?

Note: Actually two increment operators exist: ++i (pre-increment) and i++ (post-increment). ++i increments before evaluating to a
value, while i++ increments after. Ex: If i is 5, outputting ++i outputs 6, while outputting i++ outputs 5 (and then i becomes 6). This
material primarily uses ++i for simplicity and safety, although many programmers use i++, especially in for loops.

Example: Savings with interest

The following program outputs the amount of a savings account each year for 10 years, given an input initial amount and interest rate. A for
loop iterates 10 times, such that each iteration represents one year, outputting that year's savings amount.

Figure 4.4.2: For loop: Savings interest program.

#include <iostream>
using namespace std;

int main() {
double initialSavings; // User-entered initial savings
double interestRate; // Interest rate
double currSavings; // Current savings with interest
Enter initial savings: 10000
int i; // Loop variable Enter interest rate: 0.05

cout << "Enter initial savings: "; Annual savings for 10 years:
cin >> initialSavings; $10000
$10500
cout << "Enter interest rate: "; $11025
cin >> interestRate; $11576.2
$12155.1
$12762.8
cout << endl << "Annual savings for 10 years: " << endl; $13401
$14071
currSavings = initialSavings; $14774.6
for (i = 0; i < 10; ++i) { $15513.3
cout << "$" << currSavings << endl;
currSavings = currSavings + (currSavings * interestRate);
}

return 0;
}

Feedback?

PARTICIPATION
ACTIVITY 4.4.4: Savings interest program.

Consider the example above.

1) How many times does the for loop iterate?


Correct
5
The loop is:
10 for (i = 0; i < 10; ++i) {
...
}
Those values cause 10 iterations.

2) During each iteration, the loop body's statements output the current
savings amount, and then _____. Correct
The loop body is:
increment i
cout << "$" << currSavings << endl;
update currSavings currSavings = currSavings + (currSavings
* interestRate);

The second statement updates currSavings for the next


year, by adding the interest amount. Note that ++i is in
the loop header; that update implicitly occurs after the
loop body.

3) Can the input values change the number of loop iterations?


Correct
Yes
For this loop, the number of iterations is Hxed at 10. In
No other programs, the number of iterations may depend on
input values.

Feedback?

Example: Computing the average of a list of input values

The example below computes the average of an input list of integer values. The Hrst input indicates the number of values in the subsequent
list. That number controls how many times the subsequent for loop iterates.

Figure 4.4.3: Computing an average, with Hrst value indicating list size.

#include <iostream>
using namespace std;

// Outputs average of list of integers


// First value indicates list size
// Ex: 4 10 1 6 3 yields (10 + 1 + 6 + 3) / 4, or 5

int main() {
int currValue;
int valuesSum;
int numValues; 4 10 1 6 3
int i; Average: 5

cin >> numValues; // Gets number of values in list ...

5 -75 -50 30 60 80
valuesSum = 0; Average: 9

for (i = 0; i < numValues; ++i) {


cin >> currValue; // Gets next value in list
valuesSum += currValue;
}

cout << "Average: " << (valuesSum / numValues) << endl;

return 0;
}

Feedback?

PARTICIPATION
ACTIVITY 4.4.5: Computing the average.

Consider the example above, with input 4 10 1 6 3. Note: The Hrst input indicates the number of values in the subsequent list.

1) Before the loop is entered, what is valuesSum?


Correct
0
0

Check Show answer valuesSum = 0; appears just before the for loop. The
sum of the values seen so far is 0, because no values
have been seen so far. Such initialization just before a
loop is common.

2) What is valuesSum after the Hrst iteration?


Correct
10
10

Check Show answer valuesSum was initially 0. The Hrst iteration gets
currValue (10) from input, and executes valuesSum +=
currValue, thus assigning valuesSum with 0 + 10 or 10.

3) What is valuesSum after the second iteration?


Correct
11
11

Check Show answer After the Hrst iteration, valuesSum was 10. The second
iteration adds 1, yielding 11. valuesSum will be 11 + 6 or
17 after the third iteration, and 17 + 3 or 20 after the
fourth.

4) valuesSum is 20 after the fourth iteration. What is numValues?


Correct
4
4

Check Show answer The Hrst input was 4, which was gotten from input before
the loop. That value did not change during the loop
iterations.

5) For the following input, how many times will the for loop iterate?
7 -1 -3 -5 -14 -15 -20 -40 Correct

7 7

The Hrst input value (7) is put into numValues. The for
Check Show answer loop then iterates numValues time, getting each value
from the list one at a time, summing those values, then
dividing the sum by numValues to compute the average.

Feedback?

Choosing among for and while loops

Generally, a programmer uses a for loop when the number of iterations is known (like loop 5 times, or loop numItems times), and a while
loop otherwise.

Table 4.4.1: Choosing between while and for loops: General guidelines (not strict rules though).

for Number of iterations is computable before the loop, like iterating N times.

while Number of iterations is not (easily) computable before the loop, like iterating until the input is 'q'.

Feedback?

PARTICIPATION
ACTIVITY 4.4.6: While loops and for loops.

Choose the most appropriate loop type.

1) Iterate as long as user-entered char c is not 'q'.


Correct
while
The iterations are not known before the loop, so use:
for while (c != 'q').

2) Iterate until the values of x and y are equal, where x and y are
changed in the loop body. Correct
The iterations are not known before the loop, so use:
while
while (x != y).
for

3) Iterate 100 times.


Correct
while
The iterations are known before the loop, so use: for ( i =
for 0 ; i < 100; ++i).

Feedback?

CHALLENGE
ACTIVITY 4.4.1: Enter the for loop's output.

493336.3712256.qx3zqy7

Jump to level 1 1

Type the program's output 2

#include <iostream>
3
using namespace std;

int main() {
int i = 0;

for (i = 0; i > -2; --i) {


0-1
cout << i;
}

return 0;
}

1 2 3

Check Next Done. Click any level to practice more. Completion is preserved.

i starts with 0. Each iteration outputs the value of i then decrements i by 1. When i reaches -2, the loop body will not be
entered because -2 > -2 is false.

Yours 0-1

Expected 0-1

Feedback?

CHALLENGE
ACTIVITY 4.4.2: Read and format integers.

493336.3712256.qx3zqy7

Jump to level 1
1

Read integer inCount from input as the number of integers to be read next. Use a loop to read the remaining integers from input.
2
Output all integers on the same line, and surround each integer with angle brackets. Lastly, end with a newline.

Ex: If the input is: 3

2
80 85

then the output is:

<80><85>

1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int inCount;
6 int value;
7 /* Your code goes here */
8 cin >> value;
9 for(int i=0;i<inCount;i++){
10 cout << "<"<<value
11 return 0;
12 }

1 2 3

Check Next level

Feedback?

How was this section? ! | " Provide section feedback

Activity summary for assignment: zyBooks - Reading 5 144 / 146 points


Due: 10/08/2023, 11:59 PM CDT

Completion details 

4.5 More for loop examples

You might also like