






























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Introduction to Computers and C++ Programming
Typology: Lecture notes
1 / 38
This page cannot be seen from the preview
Don't miss anything!































Introduction to Computers and C++
(^1) Introduction to Computers
The whole of the development and operation of analysis are now capable of being executed by machinery ... As soon as an Analytical Engine exists, it will necessarily guide the future course of science. CHARLES BABBAGE (1792–1871)
Introduction In this chapter we describe the basic components of a computer, as well as the basic technique for designing and writing a program. We then show you a sample C++ program and describe how it works.
1.1 Computer Systems A set of instructions for a computer to follow is called a program. The collection of programs used by a computer is referred to as the software for that computer. The actual physical machines that make up a computer installation are referred to as hardware. As we will see, the hardware for a computer is conceptually very simple. However, computers now come with a large array of software to aid in the task of programming. This software includes editors, translators, and managers of various sorts. The resulting environment is a complicated and powerful system. In this book we are concerned almost exclusively with software, but a brief overview of how the hardware is organized will be useful.
Hardware There are three main classes of computers: PCs , workstations , and mainframes. A PC ( personal computer ) is a relatively small computer designed to be used by one person at a time. Most home computers are PCs, but PCs are also widely used in business, industry, and science. A workstation is essentially a larger and more powerful PC. You can think of it as an “industrial-strength” PC. A mainframe is an even larger computer that typically requires some support staff and generally is shared by more than one user. The distinctions between PCs, workstations, and mainframes are not precise, but the terms are commonly used and do convey some very general information about a computer.
software
hardware
PCs, workstations, and mainframes
4 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
Other components connect to the main memory and operate under the direction of the processor. The arrows in Display 1.1 indicate the direction of information flow. An input device is any device that allows a person to communicate information to the computer. Your primary input devices are likely to be a keyboard and a mouse. An output device is anything that allows the computer to communicate informa- tion to you. The most common output device is a display screen, referred to as a mon- itor. Quite often, there is more than one output device. For example, in addition to the monitor, your computer probably has a printer for producing output on paper. The keyboard and monitor are sometimes thought of as a single unit called a terminal. In order to store input and to have the equivalent of scratch paper for performing calculations, computers are provided with memory. The program that the computer executes is also stored in this memory. A computer has two forms of memory, called main memory and secondary memory. The program that is being executed is kept in main memory, and main memory is, as the name implies, the most important mem- ory. Main memory consists of a long list of numbered locations called memory locations ; the number of memory locations varies from one computer to another, ranging from a few thousand to many millions, and sometimes even into the billions. Each memory location contains a string of zeros and ones. The contents of these locations can change. Hence, you can think of each memory location as a tiny black- board on which the computer may write and erase. In most computers, all memory locations contain the same number of zero/one digits. A digit that can assume only the values zero or one is called a binary digit or a bit. The memory locations in most computers contain eight bits (or some multiple of eight bits). An eight-bit por- tion of memory is called a byte, so we may refer to these numbered memory loca- tions as bytes. To rephrase the situation, you can think of the computer’s main memory as a long list of numbered memory locations called bytes. The number that identifies a byte is called its address. A data item, such as a number or a letter, can be stored in one of these bytes, and the address of the byte is then used to find the data item when it is needed. If the computer needs to deal with a data item (such as a large number) that is too large to fit in a single byte, it will use several adjacent bytes to hold the data item. In this case the entire chunk of memory that holds the data item is still called a memory location. The address of the first of the bytes that make up this memory location is used as the address for this larger memory location. Thus, as a practical matter, you can think of the computer’s main memory as a long list of memory loca- tions of varying sizes. The size of each of these locations is expressed in bytes and the address of the first byte is used as the address (name) of that memory location. Display 1.2 shows a picture of a hypothetical computer’s main memory. The sizes of the memory locations are not fixed, but can change when a new program is run on the computer.
input devices
output devices
main memory
bit
byte
address
memory location
1.1 Computer Systems 5
The fact that the information in a computer's memory is represented as zeros and ones need not be of great concern to you when programming in C++ (or in most any other programming language). There is, however, one point about this use of zeros and ones that will concern us as soon as we start to write programs. The computer needs to interpret these strings of zeros and ones as numbers, letters, instructions, or other types of information. The computer performs these interpretations automat- ically according to certain coding schemes. A different code is used for each different type of item that is stored in the computer’s memory: one code for letters, another for whole numbers, another for fractions, another for instructions, and so on. For exam- ple, in one commonly used set of codes, 01000001 is the code for the letter A and also for the number 65. In order to know what the string 01000001 in a particular location
Display 1.2 Memory Locations and Bytes
Bytes and Addresses Main memory is divided into numbered locations called bytes. The number associated with a byte is called its address. A group of consecutive bytes is used as the location for a data item, such as a number or letter. The address of the first byte in the group is used as the address of this larger memory location.
byte 1 byte 2 byte 3 byte 4 byte 5 byte 6 byte 7 byte 8 byte 9
3 byte location with address 1
2 byte location with address 4 1 byte location with address 6
3 byte location with address 7
1.1 Computer Systems 7
Main memory is often referred to as RAM or random access memory. It is called random access because the computer can immediately access the data in any memory location. Secondary memory often requires sequential access, which means that the computer must look through all (or at least very many) memory loca- tions until it finds the item it needs. The processor (also know as the central processing unit, or CPU) is the “brain” of the computer. When a computer is advertised, the computer company will tell you what chip it contains. The chip is the processor. The processor follows the instructions in a program and performs the calculations specified by the program. The processor is, however, a very simple brain. All it can do is follow a set of simple instructions provided by the programmer. Typical processor instructions say things like “Interpret the zeros and ones as numbers, and then add the number in memory location 37 to the number in memory location 59, and put the answer in location 43,” or “Read a letter of input, convert it to its code as a string of zeros and ones, and place it in memory location 1298.” The processor can add, subtract, multiply, and divide and can move things from one memory location to another. It can interpret strings of zeros and ones as letters and send the letters to an output device. The processor also has some primitive ability to rearrange the order of instructions. processor instruc- tions vary somewhat from one computer to another. The processor of a modern com- puter can have as many as several hundred available instructions. However, these instructions are typically all about as simple as those we have just described.
Software You do not normally talk directly to the computer, but communicate with it through an operating system. The operating system allocates the computer’s resources to the different tasks that the computer must accomplish. The operating system is actually a program, but it is perhaps better to think of it as your chief servant. It is in charge of all your other servant programs, and it delivers your requests to them. If you want to run a program, you tell the operating system the name of the file that contains it, and the operating system runs the program. If you want to edit a file, you tell the operating system the name of the file and it starts up the editor to work on that file. To most users the operating system is the computer. Most users never see the computer without its operating system. The names of some common operating systems are UNIX , DOS , Linux , Windows , Macintosh , and VMS. A program is a set of instructions for a computer to follow. As shown in Dis- play 1.3, the input to a computer can be thought of as consisting of two parts, a pro- gram and some data. The computer follows the instructions in the program, and in that way, performs some process. The data is what we conceptualize as the input to the program. For example, if the program adds two numbers, then the two numbers
RAM
processor, chip
operating system
program
data
8 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
are the data. In other words, the data is the input to the program, and both the pro- gram and the data are input to the computer (usually via the operating system). Whenever we give a computer both a program to follow and some data for the pro- gram, we are said to be running the program on the data, and the computer is said to execute the program on the data. The word data also has a much more general meaning than the one we have just given it. In its most general sense it means any information available to the computer. The word is commonly used in both the nar- row sense and the more general sense.
High-Level Languages There are many languages for writing programs. In this text we will discuss the C++ programming language and use it to write our programs. C++ is a high-level language, as are most of the other programming languages you are likely to have heard of, such as C, Java, Pascal, Visual Basic, FORTRAN, COBOL, Lisp, Scheme, and Ada. High-level languages resemble human languages in many ways. They are designed to be easy for human beings to write programs in and to be easy for human beings to read. A high-level language, such as C++, contains instructions that are much more complicated than the simple instructions a computer's processor (CPU) is capable of following. The kind of language a computer can understand is called a low-level language. The exact details of low-level languages differ from one kind of computer to another. A typical low-level instruction might be the following:
ADD X Y Z
Display 1.3 Simple View of Running a Program
Program
Computer
Data
Output
running a program executing a program
high-level language
low-level language
10 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
Display 1.4. In reality, the entire process is accomplished by using one computer two times. The complete process of translating and running a C++ program is a bit more complicated than what we showed in Display 1.4. Any C++ program you write will
Display 1.4 Compiling and Running a C++ Program (Basic Outline)
Compiler A compiler is a program that translates a high-level language program, such as a C++ program, into a machine-language program that the computer can directly understand and execute.
C++ program (^) C++ programData for
Compiler
Computer
Machine-language program
Computer
Output of C++ program
1.1 Computer Systems 11
use some operations (such as input and output routines) that have already been pro- grammed for you. These items that are already programmed for you (like input and output routines) are already compiled and have their object code waiting to be com- bined with your program’s object code to produce a complete machine-language pro- gram that can be run on the computer. Another program, called a linker, combines the object code for these program pieces with the object code that the compiler produced from your C++ program. The interaction of the compiler and the linker are diagrammed in Display 1.5. In routine cases, many systems will do this linking for you automati- cally. Thus, you may not need to worry about linking in very simple cases.
SELF-TEST EXERCISES
1 What are the five main components of a computer? 2 What would be the data for a program to add two numbers?
3 What would be the data for a program that assigns letter grades to students in a class?
4 What is the difference between a machine-language program and a high- level language program?
5 What is the role of a compiler?
6 What is a source program? What is an object program?
7 What is an operating system?
8 What purpose does the operating system serve?
9 Name the operating system that runs on the computer you use to prepare pro- grams for this course.
10 What is linking?
11 Find out whether linking is done automatically by the compiler you use for this course.
Linking The object code for your C++ program must be combined with the object code for routines (such as input and output routines) that your program uses. This process of combining object code is called linking and is done by a program called a linker. For simple programs, linking may be done for you automatically.
linking
1.2 Programming and Problem-Solving 13
carried out by the computer, but the solutions are formulated by the programmer. Our discussion of computer programming begins with a discussion of how a programmer formulates these solutions.
1.2 Programming and Problem-Solving
The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. It can follow analysis; but it has no power of anticipating any analytical relations or truths. Its province is to assist us in making available what we are already acquainted with. ADA AUGUSTA, COUNTESS OF LOVELACE (1815–1852)
Ada Augusta, Countess of Lovelace and the first computer programmer, left
Charles Babbage, right
A model of Babbage’s computer
14 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
In this section we describe some general principles that you can use to design and write programs. These principles are not particular to C++. They apply no matter what programming language you are using.
Algorithms When learning your first programming language it is easy to get the impression that the hard part of solving a problem on a computer is translating your ideas into the specific language that will be fed into the computer. This definitely is not the case. The most difficult part of solving a problem on a computer is discovering the method of solution. After you come up with a method of solution, it is routine to translate your method into the required language, be it C++ or some other programming language. It is therefore helpful to temporarily ignore the programming language and to concentrate instead on formulating the steps of the solution and writing them down in plain English, as if the instructions were to be given to a human being rather than a computer. A sequence of instructions expressed in this way is frequently referred to as an algorithm. A sequence of precise instructions which leads to a solution is called an algorithm. Some approximately equivalent words are recipe , method , directions , procedure , and routine. The instructions may be expressed in a programming lan- guage or a human language. Our algorithms will be expressed in English and in the programming language C++. A computer program is simply an algorithm expressed in a language that a computer can understand. Thus, the term algorithm is more gen- eral than the term program. However, when we say that a sequence of instructions is an algorithm, we usually mean that the instructions are expressed in English, since if they were expressed in a programming language we would use the more specific term program. An example may help to clarify the concept. Display 1.6 contains an algorithm expressed in rather stylized English. The algorithm determines the number of times a specified name occurs on a list of names. If the list contains the winners of each of last season's football games and the name is that of your favorite team, then the algorithm determines how many games your team won. The algorithm is short and simple but is otherwise very typical of the algorithms with which we will be dealing. The instructions numbered 1 through 5 in our sample algorithm are meant to be carried out in the order they are listed. Unless otherwise specified, we will always assume that the instructions of an algorithm are carried out in the order in which they are given (written down). Most interesting algorithms do, however, specify some change of order, usually a repeating of some instruction again and again such as in instruction 4 of our sample algorithm. The word algorithm has a long history. It derives from the name of a ninth- century Persian mathematician and astronomer al-Khowarizmi. He wrote a famous
algorithm
sample algorithm
origin of the word algorithm
16 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
divided into two phases, the problem-solving phase and the implementation phase. The result of the problem-solving phase is an algorithm, expressed in English, for solving the problem. To produce a program in a programming language such as C++, the algorithm is translated into the programming language. Producing the final program from the algorithm is called the implementation phase. The first step is to be certain that the task—that which you want your program to do—is completely and precisely specified. Do not take this step lightly. If you do not know exactly what you want as the output of your program, you may be surprised at what your program produces. Be certain that you know what the input to the pro- gram will be and exactly what information is supposed to be in the output, as well as what form that information should be in. For example, if the program is a bank accounting program, you must know not only the interest rate, but also whether interest is to be compounded annually, monthly, daily, or whatever. If the program is supposed to write poetry, you need to determine whether the poems can be in free verse or must be in iambic pentameter or some other meter. Many novice programmers do not understand the need to design an algorithm before writing a program in a programming language, such as C++, and so they try to short-circuit the process by omitting the problem-solving phase entirely, or by reducing it to just the problem definition part. This seems reasonable. Why not “go for the mark” and save time? The answer is that it does not save time! Experience has shown that the two-phase process will produce a correctly working program faster. The two-phase process simplifies the algorithm design phase by isolating it from the detailed rules of a programming language such as C++. The result is that the algorithm design process becomes much less intricate and much less prone to error. For even a modest size program, it can represent the difference between a half day of careful work and several frustrating days of looking for mistakes in a poorly understood program. The implementation phase is not a trivial step. There are details to be concerned about, and occasionally some of these details can be subtle, but it is much simpler than you might at first think. Once you become familiar with C++ or any other pro- gramming language, the translation of an algorithm from English into the program- ming language becomes a routine task. As indicated in Display 1.7, testing takes place in both phases. Before the pro- gram is written, the algorithm is tested, and if the algorithm is found to be deficient, then the algorithm is redesigned. That desktop testing is performed by mentally going through the algorithm and executing the steps yourself. On large algorithms this will require a pencil and paper. The C++ program is tested by compiling it and running it on some sample input data. The compiler will give error messages for cer- tain kinds of errors. To find other types of errors, you must somehow check to see if the output is correct.
problem-solving phase
implementation phase
1.2 Programming and Problem-Solving 17
The process diagrammed in Display 1.7 is an idealized picture of the program design process. It is the basic picture you should have in mind, but reality is some- times more complicated. In reality, mistakes and deficiencies are discovered at unex- pected times, and you may have to back up and redo an earlier step. For example, testing the algorithm may reveal that the definition of the problem was incomplete. In such a case you must back up and reformulate the definition. Occasionally, defi- ciencies in the definition or algorithm may not be observed until a program is tested. In that case you must back up and modify the definition or algorithm and all that fol- lows them in the design process.
Object-Oriented Programming The program design process that we outlined in the previous section represents a program as an algorithm (set of instructions) for manipulating some data. That is a correct view, but not always the most productive view. Modern programs are usually designed using a method known as Object Oriented Programming or OOP. In OOP a
Display 1.7 Program Design Process
Translating to C++
Testing
Start
Working program
Desktop testing
Algorithm design
Problem definition
Problem-solving phase Implementation phase
OOP
1.3 Introduction to C++ 19
SELF-TEST EXERCISES
12 An algorithm is approximately the same thing as a recipe, but some kinds of steps that would be allowed in a recipe are not allowed in an algorithm. Which steps in the following recipe would be allowed?
Place 2 teaspoons of sugar in mixing bowl. Add 1 egg to mixing bowl. Add 1 cup of milk to mixing bowl. Add 1 ounce of rum, if you are not driving. Add vanilla extract to taste. Beat until smooth. Pour into a pretty glass. Sprinkle with nutmeg.
13 What is the first step you should take when creating a program?
14 The program design process can be divided into two main phases. What are they?
15 Explain why the problem-solving phase should not be slighted.
1.3 Introduction to C++
Language is the only instrument of science ... SAMUEL JOHNSON (1709–1784)
In this section we introduce you to the C++ programming language, which is the programming language used in this book.
Origins of the C++ Language
The first thing that people notice about the C++ language is its unusual name. Is there a C programming language, you might ask? Is there a C− or a C− − language? Are there programming languages named A and B? The answers to most of these questions is no. But the general thrust of the questions is on the mark. There is a B programming language; it was not derived from a language called A, but from a language called BCPL. The C language was derived from the B language, and C++ was derived from the C language. Why are there two pluses in the name C++? As you will see in the next chapter, ++ is an operation in the C and C++ languages, so using ++ produces a nice pun. The languages BCPL and B will not concern us. They
20 1 INTRODUCTION TO COMPUTERS AND C++ PROGRAMMING
are earlier versions of the C programming language. We will start our description of the C++ programming language with a description of the C language. The C programming language was developed by Dennis Ritchie of AT&T Bell Laboratories in the 1970s. It was first used for writing and maintaining the UNIX operating system. (Up until that time UNIX systems programs were written either in assembly language or in B, a language developed by Ken Thompson, who is the originator of UNIX.) C is a general-purpose language that can be used for writing any sort of program, but its success and popularity are closely tied to the UNIX oper- ating system. If you wanted to maintain your UNIX system, you needed to use C. C and UNIX fit together so well that soon not just systems programs, but almost all commercial programs that ran under UNIX were written in the C language. C became so popular that versions of the language were written for other popular oper- ating systems; its use is not limited to computers that use UNIX. However, despite its popularity, C is not without its shortcomings. The C language is peculiar because it is a high-level language with many of the features of a low-level language. C is somewhere in between the two extremes of a very high-level language and a low-level language, and therein lies both its strengths and its weaknesses. Like (low-level) assembly language, C language programs can directly manipulate the computer’s memory. On the other hand, C has many features of a high-level language, which makes it easier to read and write than assembly lan- guage. This makes C an excellent choice for writing systems programs, but for other programs (and in some sense even for systems programs), C is not as easy to under- stand as other languages; also, it does not have as many automatic checks as some other high-level languages. To overcome these and other shortcomings of C, Bjarne Stroustrup of AT&T Bell Laboratories developed C++ in the early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++, and so most C programs are also C++ pro- grams. (The reverse is not true; many C++ programs are definitely not C programs.) Unlike C, C++ has facilities to do object-oriented programming, which is a recently developed and very powerful programming technique.
A Sample C++ Program Display 1.8 contains a simple C++ program and the screen display that might be generated when a user runs and interacts with this program. The person who runs a program is called the user. The text typed in by the user is shown in boldface to distinguish it from the text written by the program. On the actual screen both texts would look alike. The person who writes the program is called the programmer. Do not confuse the roles of the user and the programmer. The user and the programmer may or may not be the same person. For example, if you write and then run a program, you are both the programmer and the user. With professionally produced
user
programmer