## Computing Concepts with C++ Essentials, 2nd ed. Laboratory Notebook Chapter 6 - Iteration

### Cay S. Horstmann Geof Pawlicki

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.

#### Lab Objectives

To gain experience with

• loops as repeated decisions
• types of common code that can be treated iteratively
• loop conditions and termination
• programming loops and choosing between while, for and do/while statements
• using loops to process character, word and line input
• nested loops

### P1. Simple Loops

Frequently, a decision needs to be made whether or not to do something again. Here is a program that computes the number of digits needed to represent a number in base 10, just like the function digits() from the preceding lab. But instead of using recursion, it uses multiple if statements.

```/* PURPOSE:  Count number of digits needed to express an integer in base 10
using multiple if statements
REMARKS:  Compare to Ch.5 digits()
*/

#include <iostream>
using namespace std;

int main()
{  int input;

cout << "Input an integer between 1 and 9999: ";
cin >> input;

int temp = input;
int d = 1;

assert ( input >= 1 and input <= 9999 );

if (temp > 9)
{  temp = temp / 10;
d++;
}

if (temp > 9)
{  temp = temp / 10;
d++;
}

if (temp > 9)
{  temp = temp / 10;
d++;
}

if (temp > 9)
{  temp = temp / 10;
d++;
}

cout << input << " can be expressed in " << d << " digits" << "\n";

return 0;
}

```

But having to write

```   if (temp > 9)
{   temp = temp / 10;
d++;
}
```

four times, even using copy/paste, is clearly repetitive! It also only works for input <= 9999. One would like to have a way of testing that the input is still greater than 1, and executing the succeeding control block if it is. Replacing if with while does it.

```/* PURPOSE:  Count number of digits needed to express an integer in base 10
using while loop
*/

#include <iostream>
using namespace std;

int main()
{  int input;

cout << "Input an integer: ";
cin >> input;
int d = 1;
int temp = input;

while (temp > 9)
{  temp = temp / 10;
d++;
}

cout << input << " can be expressed in " << d << " digits" << "\n";
}
```

The fractions 1/2, 1/4, 1/8, ... get closer and closer to 0. Change the previous program to count the number of divisions by two needed to be within 0.0001 of zero.

### P2. Loop Termination

Which values of nyear cause the following loops to terminate?

```/* PURPOSE: Count number of year between a user-input year and the
year 2000.
*/

int main()
{  int nyear;
millennium = 2000;

cout << "Please enter the current year";
cin >> nyear;

while (nyear != millennium)
{  nyear++;
}

cout << " Another "<< millenium - nyear << "years to the millenium." << "\n";
return 0;
}

```

Re-write the preceding program so that the while loop will terminate for any integer input.

### P3. for Loops

A variable that counts the iterations of a loop is called a loop index. In the preceeding examples nyear serves as an index, counting the number of years to the millenium. This type of loop is frequently written using the for idiom.

```for ( loop_index = start_value ; condition ; index_increment )
```

Write a program controlled by two for loops which produces the following listing of inclusive dates, from the 5th Century B.C. through the 5th Century A.D.

```Century 5 BC  400-499
Century 4 BC  300-399
Century 3 BC  200-299
Century 2 BC  100-199
Century 1 BC  1-99
```

Write the same program with a single loop for( i = -5 ; i <= 5 ; i++ ) and an if in the body of the loop.

### R1. Other Loops

One loop type might be better suited to a purpose than another. The following usages are idiomatic.

 for Known number of iterations while Unknown number of iterations do while At least one iteration

Convert to a do while loop

```/* PURPOSE: Program to compute a running sum of user-input integers
*/

#include <iostream>
using namespace std;

int main()
{  int sum = 0;
int n = 1;

while( n != 0 )
{  cout << "Sum =  " << sum  << "\n";
cout << "Please enter a number, 0 to quit ";
cin >> n;

sum += n;
cout << "Sum =  " << sum  << "\n";
}
return 0;
}
```

Is this an improvement? Why?

Convert the inner while loop to a for loop

```/* PURPOSE: Program to compute the first integral power to which 2 can be
raised that is greater than that multiple of a user-input integer.
*/

#include <iostream>
using namespace std;

int main()
{  int i = 1;
int n = 1;

while(true)
{  cout << "Please enter a number, 0 to quit ";
cin >> n;
if (n == 0) return 0;
i = 1;
while ( n * n > pow(2,i))
{   i++;
}
cout << "2 raised to " << i
<< " is the first power of two greater than " << n << " squared\n";
}
}
```

Is this an improvement? Why?

Convert to a while loop:

```#include <iostream>
using namespace std;

int main()
{  int i;

for(i = 1; i <= 10; i++)
{  cout << i << " squared equals " << i * i << "\n";
}
return 0;
}
```

Is this an improvement? Why?

### P4. Iterating through a string

Many word-processors can check spelling. One of the corrections applied is to swap 'e' for 'i' if 'i' occurs immediately before 'e' and immediately after 'c'. For example, concieve is corrected to conceive. Complete a function string i_before_e(string word) that carries out this correction. That is, your function should return the corrected string (or the original string if no correction needed to be applied.)

```string i_before_e(string word)
{  string r = "";
for (i = 0 ; i < word.length() ; i++ )
{ /*
*/
}
return r;
}
```

Write a test harness to test the preceding function by feeding it many inputs.

```#include <iostream>
#include <string>
using namespace std;

int main()
{  bool done = false;

while (not done)
{  /*
*/
}
return 0;
}
```

### R2. Tracing Loops

1) What is the output of each of the following loops?

2) In each example, leave the loop as it is and change the expression following cout << so that the program will display "1 2 3 4 5 ".

```#include <iostream>
using namespace std;

int main()
{  for ( i = 0 ; i < 5 ; i++ )
{   cout << i << " ";
}
cout << "\n";
return 0;
}
```
```#include <iostream>
using namespace std;

int main()
{  int decimals = 1;
while (decimals < 100000)
{  cout << decimals << "\n";
decimals *= 10;
}
return 0;
}
```
```#include <iostream>
using namespace std;

int main()
{  int i = 5;
do
{  cout << i << "\n"
i--;
}  while( i > 0 )
return 0;
}
```

### P5. Nested Loops

Write a program to draw a top view of 24 beer cans, that is 24 circles, arranged in a 4 x 6 grid like this: