Chapter 1
Introduction

Chapter 2
Functions

Chapter 3
Branching

Chapter 4
Iteration

Chapter 5
OOP

Chapter 6
Arrays


CHAPTER 1

( Introduction ) 

1 ) Introduction to C++

2 ) Sending output to a Print File

3 ) Programming Tip

Introduction

Required terminology and general information for this chapter:

Program . a series of instructions for a computer to execute.

Programming languages: Machine, Assembly, and High Level

How the first computers were programmed? By manually connecting wires.

Machine language: programs and data were entered into the computer using zeros and ones. All operation codes (opcodes) and operands were entered in binary numbers. Machine language is the machine "understandable" language. It does not matter what other languages are used to program, eventually all programs and data will have to be translated into a "machine executable" format.

Assembly Language: An easier programming language than machine language, where programs are written using familiar symbols (for example A for add). The operands could be in binary, hexadecimal or decimal format. For every machine language code, there needs to be one assembly language code. The program was not shorter, just easier to write. Once the program was written in assembly language, it had to be compiled to produce the machine executable code in order to run the program. The compiler used is called an ASSEMBLER.

High Level Language: Included are languages such as Fortran (Formula Translator), COBOL (Common Business Oriented Language), BASIC (Beginner. s All purpose Symbolic Instruction Code), Pascal, C, Ada, and many more. Programs are much shorter than lower level languages. Each instruction is converted to several machine executable codes. This conversion is done in three steps: preprocessing, compiling and linking. An original program written using an EDITOR in a high level language is known as the Source Code. A compiled program is called the Object Code and the linked program is called the Executable Code. Examples of files created in each stage are: Carpet.CPP, Carpet.OBJ, and Carpet.EXE

Syntax: Rules for constructing a legal sentence in a programming language. If a program has syntax errors, it will not compile. Therefore, it produces compile time errors.

Semantics: Rules that determine the meaning of instructions written in a programming language.

Runtime and Logical errors: A runtime error occurs when the program cannot execute what is being asked to do. For example, open a file when it does not exist. Logical errors are most difficult to fix; it is caused by faulty logic by the programmer. For example, suppose you wanted write a program to give discount if purchase is greater than $100.00, instead you programmed to give discount if purchase is less than $100.00.

C++: The C (Dennis Ritchie) language is a modification of another language called BCPL (Ken Thompson). C language was written for programming under the Unix operating system environment which continues to be a very popular operating system for universities and businesses. C++ (Bjarne Stroustrup) is an object oriented version of C.

Constant : a data item that does not change during the execution of the program. A constant could be a named constant or a literal constant. Example of a literal constant is given in the following program. Example of a named constant is:

const float TAX_RATE = 8.025; //TAX_RATE is a named constant // 8.025 is a literal constant

First C++ program: Call up the C++ programming environment from your windows desktop and type the following program in. Compile, and run it.

Program 1-1 

/********************************

Say Hello program

By Dr. John Abraham

Created for 1380 students

Teaching objective: program structure

********************************/

#include <iostream.h> //this is preprocessor directive

int main () //this is the main function

{

cout << "See mom! I wrote my first C++ program\n";

return 0;

}

Program run 1

See mom! I wrote my first C++ program

IMPORTANT: Did this program run so fast that you could not see the output? Go to the end of this chapter where I describe how to stop the screen while running. See Program 1-1A

A program in C++
is a collection of one or more functions. This program has only one function named main. The function main is a required function in all programs. If there are several functions in a program, each function carries out a different task. The main function will call other functions into action.

Description of the program:
Lines beginning with /* and ending with */ are comments, C++ ignores these lines. These comments are used for internal documentation. // may be used for commenting one line.

Preprocessor library:
C language is a small language and does not have inherent input/output support. Input/output support is provided by modules (library). This program outputs one line of text to the monitor. The monitor is the standard output device and the keyboard is the standard input device. A pound sign # indicates that the remainder of that line is an instruction (directive) to the compiler. #include <iostream.h> tells the compiler to add the code found in that file to the beginning of this program. This code handles all character stream inputs and outputs. Without this you cannot read from the keyboard or display anything to the monitor.

A function:
int main () is a function. A function receives one or more parameters (arguments) from the calling module and returns none or one result to the calling module. The word int before the function name (main) indicates that the function will return an integer to the calling module. The calling module of the main is the operating system. This program returns a zero to the operating system, indicating normal execution. The () after the function name indicates that this function does not receive any parameters from the calling module. Later we will see variations to this.

Begin and End of a block:
The beginning of a body or compound statement is indicated by { and the ending is indicated by }.

Statement separator: A statement is separated from another statement by placing a semicolon between them. End of the line does not indicate end of a statement.

cout and cin:
cout displays (prints) to an output device such as a monitor, and cin receives input from an input device such as a keyboard. The << or >> indicates the direction of flow of the data. In this program, "See mom! I wrote my first C++ program\n, is the data (in this case the data is a literal) that flows into the output device. Notice that the string literal is enclosed in double quotes. The last two characters in the literal \n makes the cursor to go to a new line. The backslash is used as a symbol for escape. An escape sequence is used to control output devices. We will see additional escape sequences later.

The return statement:
return 0, returns zero to the calling module through the main. In this case, the operating system is given the value 0, indicating that the program had a normal execution. Perhaps, another procedure would have returned a result of a calculation to the calling module.

Modification of the program:
Adding one line to the program stops the screen for you press an enter key.

Program 1-1A

/********************************

Say Hello program

By Dr. John Abraham

Created for 1380 students

********************************/

#include <iostream.h> //this is preprocessor directive

int main () //this is the main function

{

cout << "See mom! I wrote my first C++ program\n";

getchar(); //wait for the enter key to be pressed

return 0;

}

Arithmetic in C++
When we write code in C++ to do calculations, it is important to remember that results of integer and integer calculations may be different than real and real calculations. We also need to know how mixed number calculations will be carried out. C++ will allow you to assign a number with decimal to an integer, however, the fractional part will be discarded.

INTEGER OPERATIONS

6 + 3 = 9

l = 6.5, m = 3.5 --------->l + m = 9

10 / 3 = 3

10 % 3 = 1 < /FONT >

REAL AND MIXED OPERATIONS

10 / 3 = 3

10.0 / 3.0 = 3.33333

10.0 / 3 = 3.33333<>

If l=6.5 and m= 3.5 then l+m should be 10, why is it 9? We assigned these numbers to integer variables, which discards the fractional part leaving 6 and 3, which give a total of 9.
How about 10/9 yielding 3? This is called integer division.

The next problem 10 % 3 gives a result of 1, which is the remainder of the integer division (also known as the modulus).

In the next problem even though we assigned the result of 10/3 to a real variable (a), the variable only received the result of an integer division. The result of 10.0/3.0 is 3.333333; here both numbers are real numbers (float).

However the last problem 10.0/3 also gives 3.33333, why? In a mixed operation like this the integer is converted to float first, then the operation is carried out.

Home work

The terminology given at the beginning of this chapter is very important. You must learn it thoroughly. Make q-cards and memorize the terms.
Write this program over and over again until you do not have to look at the notes. You should not continue to the next chapter until you mastered this chapter thoroughly.
This homework may appear surprisingly easy to you. Don't be fooled. Many students do not finish the course because they do not spend much time with the first two chapters.
Write a program to determine the number of thousands, hundreds, tens, and ones in a given number. Hint: use integer division and modulus. Example of a program run:

In 8532 there are
8 thousands
5 hundreds
3 tens
2 ones.


Sending the output to a printfile

You are required to submit hard copies of all programs and program runs for every assignment given to you. You are required to submit structure charts and pseudocodes aswell. This addendum Chapter 1 describes how to send the output to a text file which can be printed from any program or directly from DOS.

Suppose you created a text file called carpet.txt from a program, this file then can be printed by opening it under Word, WordPerfect, or any other program you like and then printing from it. You can also print it by going to DOS prompt and typing the following: type carpet.txt > prn

 

Program OneA_1.

/********************************************************

Printing to a file

By Dr. John Abraham

Created for 1380 students

Instructional objective: create print file One_2.txt

********************************************************/

#include <iostream.h>

#include <fstream.h> //to handle files

int main ()

{

    int i,j,k,l, m,n;

    float a,b,c;

    ofstream outfile; //output file stream handle is outfile

    outfile.open("a:One_2.txt"); //assign a DOS name to the handle

    //creates a file called One_2.txt in floppy drive A:

    //integer operations

    cout << "INTEGER OPERATIONS\n \n";

    i = 6 + 3;

    l = 6.5;

    m = 3.5;

    j = l + m;

    k = 10 /3;

    n = 10 % 3;

    cout << "6 + 3 = " << i << "\n";

    cout << "l = 6.5, m = 3.5 --------->l + m = " << j << "\n";

    cout << "10 / 3 = " << k << "\n";

    cout << "10 % 3 = " << n << "\n";

    outfile << "6 + 3 = " << i << "\n";

    outfile << "l = 6.5, m = 3.5 --------->l + m = " << j << "\n";

    outfile << "10 / 3 = " << k << "\n";

    outfile << "10 % 3 = " << n << "\n";

    //real and mixed operations

    cout << "\nREAL AND MIXED OPERATIONS \n \n";

    outfile << "\nREAL AND MIXED OPERATIONS \n \n";

    a = 10 / 3;

    b = 10.0 / 3.0;

    c = 10.0 /3;

    cout << "10 / 3 = " << a << "\n";

    cout << "10.0 / 3.0 = " << b << "\n";

    cout << "10.0 / 3 = " << c << "\n";

    outfile << "10 / 3 = " << a << "\n";

    outfile << "10.0 / 3.0 = " << b << "\n";

    outfile << "10.0 / 3 = " << c << "\n";

    outfile.close();

    getchar();

    return 0;

}

In order to create a textfile follow these steps:

  • Required preprocessor directive: #include <fstream.h>
  • Give a file handle such as outfile, printfile, textfile, or anything you like.
    Now on the file will be referred to using this name in the program.
  • Assign this handle to an actual DOS file name. DOS file names are 8 character long, a dot, and 3 character extension. You may include the drive letter and path in front of the file name. For example: C:\mydocuments\cprograms\printfiles\carpet.txt
  • Place any character stream you want in this file by using the << flow director. The easiest way to do this is to make copies of every cout lines in the program and change the cout to the file handle name. See example Program OneA_1.
  • Close the file.

To print the textfile created by this program, follow these steps:

  • Open Notepad from Startą Programsą Accessories
  • Open the file you created
  • From file option, choose print

You will be required to follow these steps for all program assignments now on.

PROGRAMMING TIP

After the first laboratory assignment several students came to my office and asked questions that were very similar. Thus, this addendum to Chapter 1 was written. When a program is assigned to you the first thing you should do is to understand the problem. Even though you may think that the assignment is very easy and you can do it at the last minute, most of the time this is not the case. Therefore, I require you to solve the problem assigned to you with "paper and pencil" first. If you approach me or the graduate assistant for help with a programming problem, you will be asked show this handwritten work first. If you do not have it, we will not help you with the coding. We will still help you to understand the problem. Once you understood the problem, figure out all the functions and variables needed to write the program. Make a structure chart and show the data flow. Next, write the psuedocode for each of the modules. A structure chart tells you what to do, a psuedocode tells you how to do it. I will cover this in class at great detail. Here is an example of a programming assignment. Write a program to determine how many quarter rolls, dime rolls, nickel rolls and penny rolls in a given amount of dollars.

Let us understand this problem.
What are the known information about this programming assignemnt?
    There are ten dollars in a quarter roll.
    There are five dollars in a dime roll.
    There are two dollars in a nickel roll.
    And there are two penny rolls in a dollar.

    The amount may vary each time you run the program. For this example let us assume the amount is 38 dollars.

    Quarter rolls may be obtained by doing integer division 38/10. Integer division gives you only the integer portion of the result. ------>
    3 quarter rolls Remainder is 38-30, which is 8.
    You can get the remainder by doing the modulus operation. Dime rolls may be obtained by doing integer division 8/5 ----------> 1 dime roll. The remainder is 8-5, whch is 3. Nickel rolls may be obtained by doing integer division 3/2.----------> 1 nickel roll. The remainder may be obtained by doing the modulus operation, which will give a remainder of 1. There are two rolls of pennies in a dollar.-------------> 2 penny rolls.


Refining this will give you the following:

  • get dollars
  • read dollars from the keyboard
  • calculate quarter rolls and remainder
  • quarter_rolls = dollars / 10
  • remainder = dollars % 10
  • calculate dime rolls and remainder
  • dime_rolls = remainder / 5
  • remainder = remainder % 5
  • calculate nickel rolls and remainder
  • nickel_rolls = remainder / 2
  • remainder = remainder % 2
  • calculate penny rolls
  • penny_rolls = remainder * 2



After doing all the above, go to the computer lab, launch the Visual C++ or whatever compiler you like. Many of you write the entire program in then spend hours trying to debug it. A better practice is to write smaller portions first.

Write a shell of the program as follows, save it to the appropriate subdirectory. If you are using the campus computer, save to c:\temp\yourfilename.cpp. Replace yourfilename with whatever name you want to call it. Compile the program and make sure that there no errors. Remember to copy the yourfilename.cpp to your floppy disk before logging out of the computer. Once you logout all your work will be erased. You can copy the file by either dragging the file from the C: drive to A: drive or copying from C: and pasting to A:.

Sample program shell.

/******************************************/
Put all your comments here
******************************************/
#include <iostream.h>
int main()
{
return (0);
}

If no errors occurred in the above program, begin to write the source code. If you are not an experienced typist or a programmer, I suggest that you compile the program after every few lines. Make sure there are no errors. You are allowed to have warnings, but no errors. Correct the errors before continuing.

Program OneB_1

/********************************************************

Calculate how many Quarter Rolls, Dime Rolls

Nickel Rolls and Penny rolls in given dollar amount.

By Dr. John Abraham

Created for 1380 students

**********************************************************/

#include <iostream.h>

 

int main()

{

int dollar, quarterR, dimeR, nickelR, pennyR, remainder;

//prompt and read dollar

cout << "Enter amount of dollars to change---> ";

cin >> dollar;

//find quarter rolls

quarterR = dollar / 10;

remainder = dollar % 10;

//find dime rolls

dimeR = remainder / 5;

remainder = remainder % 5;

//find nickel rolls

nickelR = remainder / 2;

remainder = remainder %2;

//find penny rolls

pennyR = remainder *2;

//display results

cout << "amount entered ----> " << dollar << "\n";

cout << "quarter rolls -----> " << quarterR << "\n";

cout << "dime rolls --------> " << dimeR << "\n";

cout << "nickel rolls ------> " << nickelR << "\n";

cout << "penny rolls -------> " << pennyR << "\n";

return(0);

}

Program Run OneB_1

Enter amount of dollars to change---> 38

amount entered ----> 38

quarter rolls -----> 3

dime rolls --------> 1

nickel rolls ------> 1

penny rolls -------> 2

Press any key to continue

 

Here is a description of the program line by line.

int main()

Every program must have a main function. A program begins executing with the main function. Main returns an integer value to DOS.

{

The left bracket indicates the beginning of the main.

int dollar, quarterR, dimeR, nickelR, pennyR, remainder;

Variables that are used in the main are declared. There are six variables of type integer. These variable names (identifiers) stand for memory locations. In each of these memory locations, only whole numbers within the range of -32768 to 32767 can be stored.

//prompt and read dollar

cout << "Enter amount of dollars to change---> ";

Displays the prompt to the user.

cin >> dollar;

Waits for the user to type in a value at the keyboard. When a value is entered, that value is stored in the memory location referred to by dollar.

//find quarter rolls

quarterR = dollar / 10;

Result of this integer division is stored in the variable called quarterB.

remainder = dollar % 10;

Result of this modulus operation is stored in the memory location referred to by remainder.

//find dime rolls

dimeR = remainder / 5;

remainder = remainder % 5;

//find nickel rolls

nickelR = remainder / 2;

remainder = remainder %2;

//find penny rolls

pennyR = remainder *2;

//display results

cout << "amount entered ----> " << dollar << "\n";

cout << "quarter rolls -----> " << quarterR << "\n";

cout << "dime rolls --------> " << dimeR << "\n";

cout << "nickel rolls ------> " << nickelR << "\n";

cout << "penny rolls -------> " << pennyR << "\n";

return(0);

}

This program only prints to the monitor. We want the program run to be saved in a file. The following program shows the necessary lines required to do it.

Program OneB_2.

/********************************************************

Calculate how many Quarter Rolls, Dime Rolls

Nickel Rolls and Penny rolls in given dollar amount.

By Dr. John Abraham

Created for 1380 students

**********************************************************/

#include <iostream.h>

#include <fstream.h>

int main()

{

//file routines

ofstream outfile;

outfile.open("a:OneB_1.txt");

int dollar, quarterR, dimeR, nickelR, pennyR, remainder;

//prompt and read dollar

cout << "Enter amount of dollars to change---> ";

cin >> dollar;

outfile << "Enter amount of dollars to change---> " << dollar << "\n";

//find quarter rolls

quarterR = dollar / 10;

remainder = dollar % 10;

//find dime rolls

dimeR = remainder / 5;

remainder = remainder % 5;

//find nickel rolls

nickelR = remainder / 2;

remainder = remainder %2;

//find penny rolls

pennyR = remainder *2;

//display results

cout << "amount entered ----> " << dollar << "\n";

cout << "quarter rolls -----> " << quarterR << "\n";

cout << "dime rolls --------> " << dimeR << "\n";

cout << "nickel rolls ------> " << nickelR << "\n";

cout << "penny rolls -------> " << pennyR << "\n";

outfile << "amount entered ----> " << dollar << "\n";

outfile << "quarter rolls -----> " << quarterR << "\n";

outfile << "dime rolls --------> " << dimeR << "\n";

outfile << "nickel rolls ------> " << nickelR << "\n";

outfile << "penny rolls -------> " << pennyR << "\n";

outfile.close();

 return(0);

}

Once this program is run a file is created in the floppy disk drive. I opened the file that was created (OneB_2.txt) using MS Word. Here is the output:

Enter amount of dollars to change---> 44

amount entered ----> 44

quarter rolls -----> 4

dime rolls --------> 0

nickel rolls ------> 2

penny rolls -------> 0


Go to the top of this Chapter

Site design/development provided by the UTPA NewMedia Center
@1999 The University of Texas-Pan American