## Introduction to Programming with C++

Objectives

• Learn to use loops in C++
• Learn to format information in tabular form
• Learn new terminology: body of a loop, count-controlled loop, do-while loop, event-controlled loop, for loop, infinite loop, iteration, loop, while loop, declared constant (const), header file, include, predefined function

### Example of Finding Averages

Suppose we have four test scores, and you want to compute the average. You can use the following C++ program computes that average.

 `#include using namespace std;// This program reads and compute the average of 4 integers.int main() { int num1, num2, num3, num4; // numbers to average int sum=0; // sum of the numbers before finding out the average. double average=0.0; // the average // prompt the user for the four scores cout << "Enter four grades separated by spaces, then press 'Enter':" << endl; // read and store four integers (the space in between them allows this syntax ) cin >> num1 >> num2 >> num3 >> num4; // Calculate the average (note 4.0 is used to prevent integer division) sum = num1 + num2 + num3 + num4; average = sum/4.0; // Display the average cout << "The average is " << average << endl; // do a system call to keep the window open. return 0;}`

We could make simple changes to the program to compute the average of six numbers instead, in which after asking the user for six numbers, the line to find the average is:

` average = (num1 + num2 + num3 + num4 + num5 + num6)/6.0;`

However, imagine using this technique to compute the average of 1000 numbers; the code would be very tedious and error-prone as it would be easy to forget a number. A better approach would be to use a loop construct that executes a portion of the code for multiple iterations. A loop is a programming structure that executes repeatedly while the loop condition is true. An iteration is one pass through the execution of the code inside the loop, including the evaluation of the condition.

An Example of a while Loop
Here is a new version of the above program written using a while loop. The major changes to our code will made in the lines that are marked with comments and is in red.

```#include <iostream>
using namespace std;
// This program reads and compute the average of 4 integers using a while loop.
int main() {  int count=1;        // keep track of the number of times we ask for a number  int num=0;          // numbers to average (note there is only one for the current one!)  ```

The syntax for a while loop is:
`while( Boolean_Expression ) {     Statement 1;     Statement 2; 	...     Statement Last; }`

The statements between the curly braces { and } are in what is called the body of the loop. Notice that the loop body in the example above executes when count = 1,2,3,4 and stops when count has the value 5 because it is then no longer less than or equal to four. If the boolean condition is false before the loop starts, the body executes 0 times; in the example above, this would be true if count was greater than four before starting the loop.

Sometimes, you may want to execute the loop body at least once regardless of the value in the counter variable. In such a case you have to use a do while loop. The syntax for this kind of loop is:

`do {    Statement 1;     Statement 2; 	...     Statement Last; } while( Boolean_Expression ); `

### Types of C++ Loops

There are two types of loops. The first type is controlled by a counter variable and is referred to as a count-controlled loop. The second type is controlled by a particular event and is referred to as an event-controlled loop. The above example uses a count-controlled while loop. However, in C++ it is more typical to use a for-loop as a count controlled loop, as shown in the following code fragment where the while loop is replaced by a for loop:
```// The for-loop is always controlled by a counter variable. The loop parts are:// 1) initialize the count variable to start with 1 (this is only done once)
// 2) check to see if count is still <= 4
// 3) execute the loop body if the condition is true
// 4) increment (add one to) count
for( count = 1; count<=4; count++) {
cin >> num;     sum = sum + num;
// updating the count is done automatically in the last part of the for-loop 	}```

Note that the for and while loops are equivalent in terms of what they do but look different.

In both count-controlled and event-controlled types of loop, there is always a Boolean expression that leads the flow of the computation into the body of the loop or out of it. To explain the difference between these two types of loops, consider the following two applications:

• Count-Controlled: Read 10 integers and compute their sum. A counter must keep the count until 10 numbers are read. Note that the number of inputs are set to 10 in advance and cannot change.
• Event-Controlled: Read integers and compute their sum for as long as the user keeps entering an integer value. In this case, the event that stops the loop is the occurrence of a letter, so there could be an arbitrary number of inputs.

If you wish to have a good working loop, there are three things that you have to always remember to insert:

1. initialization: Be sure that the variable that controls the loop has a valid value. Otherwise, the loop can start with a garbage value and may result in unpredictable behavior.
2. condition check: the Boolean expression must correctly check the controlling variable to determine if the loop body repeats.
3. change: The controlling variable must change inside the loop so that the condition check will eventually evaluate to false. If the condition does not change in the body of the loop, then the loop condition will check the exact same thing an infinite number of times and you will have what is called an infinite loop. You will have to terminate your program in this case using Ctrl-C.

Note that while and do-while loops are typically used for event-controlled loops and for-loops are typically used for count-controlled loops in C++. The for-loop is not covered in your text until a later chapter, but we thought you might like to see it now in case you want to use it for this assignment.

### An Introduction to Formatting Program Output

You have already see that you can use `cout` for output. Download the source code OutputFormat.cpp into your C++ source code folder. Note the use of the three lines:
 `cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2); `
These lines changed the format of subsequent output so that it has two places past the decimal point. For now, you can just use them as a set to precede the output you want to have formatted. Try commenting them out and see how the output changes.

### Creating Tables

One of the things suited to loops is generating tabular data. Before computers were readily available, people had to calculate logarithms, sines and cosines, and other common mathematical functions by hand. There were books containing long tables where you could find the values of various functions. Creating these tables was slow and boring, and the result tended to have errors.

When computers appeared, one of the initial reactions was, "This is great! We can use the computers to generate the tables, so there will be no more errors." Unfortunately, soon thereafter computers and calculators were so pervasive that the tables became obsolete. Well, almost obsolete. It turns out that for some operations, computers use tables of values to get an approximate answer, and then perform computations to improve the approximation. In some cases, there have been errors in the computer-generated tables, most famously in the tables the original Intel Pentium used to perform floating-point division. (This has been fixed!)

To format the text, so that it is displayed nicely on the screen, we use the so-called “Escape Sequences”.

The backslash preceding a character tells the compiler that the character following the \ does not have the same meaning as the character appearing by itself.

Such a sequence is called an “Escape Sequence”.

The sequence is typed is as two characters with no space between the symbols.

#### A very short list of Escape Sequences:

`New line:       \nHorizontal tab: \tAlert (beep!) : \a //Beep!Backslash:      \\Double-quote    \”`

The following program outputs a sequence of values in the left column and their squared values in the right column:
 `double value = 1.0; cout << "value" << "\t" << "square of value"; //This makes the header line in the output while( value < 10.0 ) { cout << value << "\t" << value*value << endl; value = value + 1.0;}`
Note that `"\t"` represents a tab character. A tab character causes the cursor to shift to the right until it reaches one of the tab stops, which are normally every eight characters. As we will see in a minute, tabs are useful for creating columns of text.

The output of this program is:

`value	square of value1 	12	43	94	165	256	367	498	649	81`

If we wanted to find the squares of only the numnber that are powers of two, we could modify our program like this:

`double value = 1.0; cout << "value" << "\t" << "square of value"; //This makes the header line in the output while( value < 100.0 ) {    cout << value << "\t" << value*value << endl;    value = value * 2.0;  // calculate the next power of two}`

The result is:

`value	square of value1 	12	44	168	6416	25632	102464	4096`

Note that because we are using tab characters between the columns, the position of the second column does not depend on the number of digits in the first column.

```//    This program displays three rows of numbers. #include <iostream>     // Required for input-output operations #include <iomanip>      // Required for setw using namespace std;int main(){     int num1 = 2897, num2 = 5,    num3 = 837,         num4 = 34,   num5 = 7,    num6 = 1623,         num7 = 390,  num8 = 3456, num9 = 12;     cout << "Display the numbers on 3 rows using 2 blank spaces\n";     cout << num1 << "  " << num2 << "  " << num3 << endl;     cout << num4 << "  " << num5 << "  " << num6 << endl;    cout << num7 << "  " << num8 << "  " << num9 << endl << endl;    cout << "Display the numbers on 3 rows using \\t plus 2 blank spaces\n"; nbsp;   cout << num1 << "\t  " << num2 << "\t  " << num3 << endl;     cout << num4 << "\t  " << num5 << "\t  " << num6 << endl;    cout << num7 << "\t  " << num8 << "\t  " << num9 << endl << endl;     cout << "Displays the numbers on 3 rows using setw (defined in iomanip)\n";     cout << setw(6) << num1 << setw(6) << num2 << setw(6) << num3 << endl;    cout << setw(6) << num4 << setw(6)  << num5 << setw(6) << num6 << endl;    cout << setw(6) << num7 << setw(6)  << num8 << setw(6) << num9 << endl << endl;     cout << "Using \"setw\" with data of different types\n";     int intValue = 3928;    double doubleValue = 91.5;     cout << "(" << setw(5) << intValue << ")" << endl;     cout << "(" << setw(8) << doubleValue << ")" << endl;     cout << "(" << setw(16) << " John Smith" << ")" << endl << endl;     cout << "Using \"setprecision\" in the iomanip library to round decimal numbers\n";    double quotient, number1 = 132.364, number2 = 26.91;    quotient = number1 / number2;    cout << quotient << endl;    cout << setprecision(5) << quotient << endl;     cout << setprecision(4) << quotient << endl;     cout << setprecision(3) << quotient << endl;     cout << setprecision(2) << quotient << endl;     cout << setprecision(1) << quotient << endl;     return 0;}```

Please discuss the design of the algorithms for assignment in your group of four, using your team roles.

Then implement your program individually.  Consultations are encouraged, but not code-sharing.

An elderly member of your family has decided to take a retirement trip to visit London, England this coming May.  She has purchased a guidebook and is busy with her planning. You would like to use your newly discovered C++ programming skills to give her some useful tables for her upcoming travels.

 Chart 1 on Temperature Conversion: In London and throughout the world, except in the U.S. and a handful of other countries, the Celsius temperature scale (rather than the Fahrenheit scale) is used for practically all purposes. When your relative is in London, you would like for her to be able to listen to the weather forecast and know what to expect. You know from searching the Internet, that you can convert for her with F° = C° × 9⁄5 + 32. From the BBC website, you know that London's record low in May was -1°C and the record high in May was 30°C. As a gift, you plan to create a conversion chart, so she can look up a Celsius temperature and know what that temperature is in Fahrenheit. Be sure to include every degree Celsius between -1°C  and 30°C. Display the converted Fahrenheit value with 1 digit after the decimal.

Chart 2 on Currency Conversion:
In London, the British Pound (GBP) is the standard currency. If your relative were to buy Pounds today, she would pay \$1.56 US Dollars (USD) for each 1.00 Pound, but the Pound tends to fluctuate against the US Dollar, (as you can see in the chart), so you have decided to write a program which allows you to input the number of US Dollars for 1.00 Pound. That way, you can run your program for her now and then again right right before she leaves for London. Because you can't buy much for 1 Pound, echo the exchange rate and then list the Pounds in multiples of 5's.... 5.00, 10.00, 15.00, 20.00,..., 200.00.

Create a program where the source file is called YourUserNameA3.cpp that creates these charts:

• Temperature Conversion: The table of temperatures should list Celsius temperatures first followed by the corresponding Fahrenheit temperatures in a nicely lined up table under appropriate labels beginning with -1°C and increasing to 30°C.
• Currency Conversion: After echoing the exchange rate input by the user, the currency conversion table should list Pounds first followed by the corresponding US Dollars in a nicely lined up table under appropriate labels, beginning with 5.00 Pounds, and increasing by 5s until 200.00 Pounds. Format both the Pound and the Dollar to show two places following the decimal point because both currencies have 100 cents for each 1.00 note.

#### Notes:

• Include comments for any parts of the code that is non-intuitive to let us know what that portion does.
• Use meaningful variable names of the appropriate types. i.e. `x` is not a good name, but `InputLetter` is. Use of variable names which are not meaningful will receive reduced credit.
• Include a descriptive header as a comment at the top of your source code as follows:
`// Course: CSC 226 Introduction to Programming with C++ // Name: Your Name// Assignment 3: <Put a brief sentence about your program here.>/* Purpose: 	<Put a more in-depth description of the program here.>*/`

When you are finished with your assignment, drop your source code, YourUserNameA3.cpp, into the A3 drop box in Moodle.