Make your own free website on Tripod.com

Tutorial 3

Completing the Problem-Solving Process and Getting Started with C++

Overview

This tutorial picks up in the problem-solving process at the point where the algorithm is converted into actual program code. In order to do this the programmer must understand the rules and syntax of the language. The beginning syntax of a simple C++ program is introduced, as well as C++ compiler implementation of the final program.

 

Objectives

After completing the tutorial, the student will be able to:

 Code an algorithm into a program

 Desk-check a program

 Evaluate and modify a program

 Understand the components of a C++ program

 Differentiate between source code, object code, and executable code

 Open a C++ source file

 Save, compile, build, and execute a C++ program

Lecture Notes

Reviewing and continuing the problem-solving process

In Tutorial 2 the problem-solving process was taken up to step 3, which is desk-checking the algorithm. At this point the reviewed algorithm is ready to be converted into actual program code. Once the algorithm has been converted, the problem-solving process will continue with the program code being desk-checked, and then the program will be evaluated and modified if necessary.

 

Understanding variables and writing code from the algorithm

In the next tutorial variables will be covered in great detail, however when coding the program from the IPO chart you will want to assign names, data types, and initial values the IPO items. While most C++ programmers use lower case for names, if names are more than one word then the beginning of the second word is capitalized to stand out. Remember that in most programming languages that variable names can consist of letters, numbers, and maybe an underscore, however no punctuation characters or spaces. The actual rules for naming variables in C++ will be covered in the next tutorial.

After naming the item, a data type must be chosen. The data type specifies the type of data that the item is permitted to store (for example, whether a number would have a decimal in it or be an integer). While the actual data types that C++ permits will be covered at a later time, in this tutorial we will learn that the float type will contain numbers with decimals. Therefore the only remaining step is to assign the variable an initial value, which is commonly called initializing the variable. As you will learn in the next tutorial, items declared using the float data type typically are initialized to zero using the value 0.0.

C++ syntax for declaring a variable

Remember that there are three parts to declaring a variable in C++. First determine the name of the variable, then the type, and finally assign an initial value to it. The first item coded is the data type, which is set using the C++ keyword that corresponds to the data type. In our example this will be float. Secondly we state the variable name as discussed previously. And finally we assign as initial value to the variable after the equal sign. Also remember that in C++ the variable declaration ends with a semicolon. The entire syntax would look like the following:

datatype variableName = initialValue;

An example could be:

float length = 0.0;

 

Basic input and output statements

In C++, streams are used to perform standard input and output operations. The standard output stream is called cout, which refers to the monitor. On the other hand, the standard input stream is called cin, which refers to the keyboard. When using cout, the insertion operator (<<) is used to separate the different data items in which you would like to display. For example, the following statement would display Hello to the screen:

cout << "Hello";

While the cout statement uses the insertion operator (<<), the cin statement uses the extraction operator (>>). For example, the following statement would use the cin stream to allow the user to enter a length:

cin >> length;

Note that by grouping together a cout and cin statement, the user can be prompted with a very specific message, and then enter the data into a variable specified by the programmer. For example, the following statements are used in conjunction to prompt the user for their age and place the value entered into the variable age:

cout << "Please enter your age in years (example: 21):";

cin >> age;

One additional item that could be used to better format your output would be a stream manipulator. A stream manipulator allows the program to manipulate, or manage, the input and output stream characters in some way. When outputting information to the computer screen, you could use the endl stream manipulator to advance the cursor to the next line on the screen (therefore creating a carriage return and line feed on the screen). An example where you would like two different lines of text printed on separate lines would be as follows:

cout << "Line One" << endl;

cout << "Line Two" << endl;

Desk-checking the program

Even though it appears that after the program has been coded from the algorithm you are ready to execute it and evaluate, however you can save yourself many hours of grief by taking the time to desk-check the program. Just like with the algorithm a sample set of data should be used (you could use the same one), and you should step through each program instruction similar to the way the computer will when the program is executed. Then once the program has been executed, you may compare the results to that of the desk-check for accuracy.

Evaluating and modifying the program

Once the program is ready to be executed, it must be thoroughly tested to make sure it produces correct results. If for any reason the program produces different results than the desk-check, the program should be debugged. Debugging refers to the process of locating and removing any errors, commonly called bugs, in a program. Program errors may be one of two types: syntax errors or logic errors. Syntax errors occur when you violate the rules of the language (the syntax of the language). For example, grammatical errors such as misspellings and incorrect punctuation are considered syntax errors and are relatively easy to fix compared to logic errors. Logic errors occur when the computer does what you told it to do vs. what you meant for it to do. For example, if you wished to add two items together you would use the plus sign (+), however if you accidentally hit the asterisk (*) then the two items would be multiplied together. While this would not be what you intended to occur, it would be syntactically correct and would produce inaccurate results. It would then be up to you as the programmer to locate and fix the problem (debug the program).

 Origins of C++

C++ evolved from the procedure-oriented C programming language, which was developed in 1972 at Bell Laboratories by Dennis Ritchie. In 1985, Bjarne Stroustrup added object-oriented features to the C language. This enhanced version of the C language was named C++. It is important to understand that C++ is a superset of C, which means that for the most part everything available in C is available in C++. Therefore you could use C++ as a procedural-oriented language, as well as an object-oriented language.

 IDE

To create and execute a C++ program, you need to access to a text editor and a C++ compiler. Both of these are combined in Microsoft Visual C++ 6.0 into what is called IDE or Integrated Development Environment. By having these two items integrated vs. separate, there is a great deal of time saved in the development, as well as the debugging part of the programming process.

 Source code vs. Object code

In Microsoft Visual C++ 6.0 the text editor is used to enter the C++ program itself, commonly called the source code. You will then save the source code on the computer using the filename extension of .cpp (which stands for C plus plus). This file containing the original program (source code) will be referred to as the source file.

In order for the computer to understand your program it must first be converted to machine language (remember from the previous tutorials that this is the only thing the computer understands). In order for the computer to convert the source code to machine language it needs a compiler. The compiler will perform this conversion. Once you compile your program (source code), the outcome of this step is a set of code called the object code. The object code will be saved in a file with the same filename as the source code, except the extension will be .obj instead of .cpp. The file containing the object code will be referred to as the object file.

After the compiler creates the object file, another program called a linker should be invoked. The linker combines the object file with other machine code necessary for the C++ program to run correctly. The linker will produce an executable file, which is the code necessary to execute your program without compiling it again. The executable file will have the same name as the source and object files, except the extension for it will be .exe.

 Starting to program in C++

Before creating a C++ program, you need to start C++. The instructions for starting C++ depend upon the system you are using. The textbook shows you how to start Microsoft Visual C++ 6.0 Introductory Edition. If you are using a different version of C++, you will need to talk with your instructor about the necessary steps to start your particular version. See page 92 for the beginning of how to start Microsoft Visual C++ 6.0 and how to open an existing partially completed program (note that this program is included in the student files that should be made available to you by your instructor).

Basic structure of a C++ program

The basic structure of a simple C++ program consists of the following:

 Documentation about the program

 #include directive(s)

 main function

Every program should have internal documentation at the beginning identifying important information about the program, such as the name of the program, author, date, filename where the program is saved, limitations of the program, etc. This information can save the programmer a great deal of time in the future when referencing the program.

The #include directive is a special instruction for the C++ compiler that tells the compiler to include the contents of another file. Files that are included in programs are called include files or header files. We will be creating our own header files in a later tutorial. The #include directive provides a convenient way to merge the source code from one file with the source code in another file, without having to retype the code. In C++, the iostream.h header file contains the instructions (source code) needed to handle input and output operations (such as cin and cout).

Functions will be covered in great detail in later tutorials, however each C++ program has a primary function called main. This is established with what is called a function header. A function header begins with the type of function (we will cover more on this later) followed by main (). After the function header the function code is enclosed in braces {}, marking the beginning and ending of the code. Within this function you will begin to code the program as developed through the problem-solving process.

Note: When keying in a C++ program please note that C++ is a case sensitive language. For example, by capitalizing the I in the #include directive you will cause a syntax error, because C++ is expecting the I to be lower case.

 Executing a C++ program

Beginning of page 98 of your textbook the author begins the process of compiling, building, debugging, executing, printing, etc. a C++ program. Please follow along with these examples on your computer.

 

Discussion Topics/Additional Activities (Optional unless assigned)

 Technical Notes

Note: If hard drive space is a consideration and you choose not to perform a complete installation, please test

the exercises in each tutorial thoroughly to ensure that the students will not encounter any difficulties in

performing their assignments. By doing this well in advance, you will be able make any necessary adjustments

to the installation and/or your lecture.

Note: Once you have downloaded and expanded the student files, instead of copying them to each

workstation you may consider making a set of disks that contain the information. This way each

student will have their own copy of the files and you will not have to worry about the files being

modified at each workstation (and you/someone having to constantly update/refresh them).

You will need to experiment to know how many student files for each tutorial will fit on each disk.

 

Solutions to Questions

1. b Code the algorithm into a program 9. a >>

2. d syntax 10. b cin >> currentPay;

3. c float hourlyPay = 0.0; 11. b <<

4. c semicolon 12. c endl

5. c streams 13. a evaluate and modify the program

6. b cout 14. c debugging

7. a cin 15. d a syntax error

8. c cout << "Hello"; 16. c a logic error

 

Solutions to Concept Lesson Exercises

  1. Added instructions are shaded in the IPO chart.

IPO Chart Information

C++ Instructions

Input

first number

second number

Processing

Output

sum

Algorithm

  1. enter the first number and the second number
  2.  

     

  3. calculate the sum by adding the first number to the second number
  4. display the sum

float num1 = 0.0;

float num2 = 0.0;

 

 

 

float sum = 0.0;

 

cout << "Enter first number: ";

cin >> num1;

cout << "Enter second number: ";

cin >> num2;

sum = num1 + num2;

 

 

cout << "The sum is " << sum << endl;

 

2.

num1

num2

sum

0.0

3

0.0

50.5

0.0

5

0.0

31.3

0.0

8

0.0

81.8

 

3. Added instructions are shaded in the IPO chart.

IPO Chart Information

C++ Instructions

Input

current weekly pay

raise rate

Processing

weekly raise

Output

new weekly pay

Algorithm

  1. enter the current weekly pay and raise rate
  2.  

     

  3. calculate the weekly raise amount by multiplying the current weekly pay by the raise rate
  4. calculate the new weekly pay by adding the weekly raise amount to the current weekly pay
  5. display the new weekly pay

float currentPay = 0.0;

float rate = 0.0;

 

float raise = 0.0;

 

float newPay = 0.0;

 

cout << "Enter current weekly pay: ";

cin >> currentPay;

cout << "Enter raise rate: ";

cin >> rate;

raise = currentPay * rate;

 

 

newPay = currentPay + raise;

 

 

cout << "New weekly pay is " << newPay << endl;

 

 

4.

currentPay

rate

raise

newPay

0.0

250

0.0

100

0.0

.03

0.0

.10

0.0

7.50

0.0

10

0.0

257.50

0.0

110

 

 

 

5. Added instructions are shaded in the IPO chart. (Answers may vary.)

a.

IPO Chart Information

C++ Instructions

Input

first number

second number

third number

Processing

Output

sum

Algorithm

  1. enter the first number, second number, and third number
  2.  

     

     

     

  3. calculate the sum by adding together the first number, second number, and third number
  4. display the sum

int num1 = 0;

int num2 = 0;

int num3 = 0;

 

 

 

int sum = 0;

 

cout << "First number: ";

cin >> num1;

cout << "Second number: ";

cin >> num2;

cout << "Third number: ";

cin >> num3;

sum = num1 + num2 + num3;

 

cout << "Sum: " << sum << endl;

b.

num1

num2

num3

sum

0

25

0

10

0

76

0

15

0

33

0

20

0

134

0

45

 

 

6.

a. Results of desk-checking the original program.

original

rate

discount

sale

0.0

100

0.0

.25

0.0

0.0

b. Changes made to the original program are shaded in the IPO chart.

IPO Chart Information

C++ Instructions

Input

original price

discount rate

Processing

discount

Output

sale price

Algorithm

  1. enter the original price and the discount rate
  2.  

     

  3. calculate the discount by multiplying the original price by the discount rate
  4. calculate the sale price by subtracting the discount from the original price
  5. display the sale price

float original = 0.0;

float rate = 0.0;

 

float discount = 0.0;

 

float sale = 0.0;

 

cout << "Original price: ";

cin >> original;

cout << "Discount rate: ";

cin >> rate

discount = original * rate;

 

 

sale = original - discount;

 

 

cout << "Sales price: " << sale << endl;

Results of desk-checking the corrected program.

original

rate

discount

sale

0.0

100

0.0

.25

0.0

25

0.0

75

 

Solutions to Application Lesson Exercises

1.

//T3AppE01.cpp - calculates and displays the sum of two numbers

#include <iostream>

using namespace std;

int main()

{

//declare variables

float num1 = 0.0;

float num2 = 0.0;

float sum = 0.0;

//enter input items

cout << "Enter first number: ";

cin >> num1;

cout << "Enter second number: ";

cin >> num2;

//calculate sum

sum = num1 + num2;

//display output item

cout << "The sum is " << sum << endl;

return 0;

} //end of main function

 

 2.

//T3AppE02.cpp - calculates and displays the new weekly pay

#include <iostream>

using namespace std;

int main()

{

//declare variables

float currentPay = 0.0;

float rate = 0.0;

float raise = 0.0;

float newPay = 0.0;

//enter input items

cout << "Enter current weekly pay: ";

cin >> currentPay;

cout << "Enter raise rate: ";

cin >> rate;

//calculate raise and new pay

raise = currentPay * rate;

newPay = currentPay + raise;

//display output item

cout << "New weekly pay is " << newPay << endl;

return 0;

} //end of main function

 

 

3.

//T3AppE03.cpp - calculates and displays a commission amount

#include <iostream>

using namespace std;

int main()

{

///declare variables

float sales = 0.0;

float rate = 0.0;

float commission = 0.0;

//enter input items

cout << "Enter the sales: ";

cin >> sales;

cout << "Enter the commission rate: ";

cin >> rate;

//calculate commission

commission = sales * rate;

//display commission

cout << "Your commission is $" << commission << endl;

return 0;

} //end of main function

sales

rate

commission

0.0

2000

0.0

5000

0.0

.10

0.0

.06

0.0

200

0.0

300

 

4.

//T3AppE04.cpp - calculates and displays the ending balance

#include <iostream>

using namespace std;

int main()

{

//declare variables

float begBal = 0.0;

float deposits = 0.0;

float withdrawals = 0.0;

float endBal = 0.0;

//enter input items

cout << "Beginning balance: ";

cin >> begBal;

cout << "Deposits: ";

cin >> deposits;

cout << "Withdrawals: ";

cin >> withdrawals;

//calculate ending balance

endBal = begBal + deposits - withdrawals;

//display ending balance

cout << "Ending balance: " << endBal << endl;

return 0;

} //end of main function

 

begBal

deposits

withdrawals

endBal

0.0

2000

0.0

500

0.0

775

0.0

100

0.0

1200

0.0

610

0.0

1575

0.0

-10

 

5.

//T3AppE05.cpp - calculates and displays the average

#include <iostream>

using namespace std;

int main()

{

//declare variables

float num1 = 0.0;

float num2 = 0.0;

float num3 = 0.0;

float avg = 0.0;

//enter input items

cout << "Number 1: ";

cin >> num1;

cout << "Number 2: ";

cin >> num2;

cout << "Number 3: ";

cin >> num3;

//calculate average

avg = (num1 + num2 + num3) / 3;

//display average

cout << "Average: " << avg << endl;

return 0;

} //end of main function

 

num1

num2

num3

avg

0.0

25

0.0

10

0.0

76

0.0

15

0.0

33

0.0

20

0.0

44.6667

0.0

15

 

6. Each of the three ways displays the identical message. The cout stream will essentially be used in

conjunction with the insertion operator (<<) and will concatenate what is to be printed until the endl stream

manipulator is encountered.

 

7.

//T3AppE07.cpp - calculates and displays the discount and new price

#include <iostream>

using namespace std;

int main()

{

//declare variables

float original = 0.0;

float rate = 0.0;

float discount = 0.0;

float sale = 0.0;

//enter input items

cout << "Original price: ";

cin >> original;

cout << "Discount rate: ";

cin >> rate;

//calculate discount and new price

discount = original * rate;

sale = original - discount;

//display discount and new price

cout << "The sales discount is: " << discount << endl;

cout << "The new sales price is: " << sale << endl;

return 0;

} //end of main function

 

Results of desk-checking the original program

original

Rate

discount

sale

0.0

100

0.0

.25

0.0

0.0

Results of desk-checking the corrected program

original

Rate

discount

sale

0.0

100

0.0

50

0.0

.25

0.0

.1

0.0

25

0.0

5

0.0

75

0.0

45