0% found this document useful (0 votes)
23 views

Chapter One C++

Uploaded by

amiitproduction
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Chapter One C++

Uploaded by

amiitproduction
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

CHAPTER ONE

What are computers?


Almost everyone has used a computer at one time or another. Perhaps you have played computer games or used a computer to write a
paper. Computers are used to predict the weather, design airplanes, make movies, run businesses, perform financial transactions,
control factories etc.
A modern computer might be defined as an electronic device that stores and manipulates information under the control of a
changeable program. There are two key elements to this definition. The first is that computers are devices for manipulating
information. This means that we can input data into a computer, and it can transform the information into new, useful forms, and then
output or display the information for our interpretation.
Computers are not the only machines that manipulate information. When you use a simple calculator to add up a column of numbers,
you are entering information (the numbers) and the calculator is processing the information to compute a running sum which is then
displayed. Another simple example is a gas pump. As you fill your tank, the pump uses certain inputs: the current price of gas per
gallon and signals from a sensor that reads the rate of gas flowing into your car. The pump transforms this input into information about
how much gas you took and how much money you owe.
We would not consider either the calculator or the gas pump as full-fledged computers, although modern versions of these devices
may actually contain embedded computers. They are different from computers in that they are built to perform a single, specific task.
This is where the second part of our definition comes into the picture: computers operate under the control of a changeable program.
What exactly does this mean?
If we change the program, then the computer performs a different sequence of actions, and hence, performs a different task. It is this
flexibility that allows a computer to be at one moment a word processor, at the next moment a financial planner, and later on, an
arcade game. The machine stays the same, but the program controlling the machine changes.

Computer Organization
A computer system can be divided in to hardware and software. Hardware is the physical/tangible part of a computer. A computer is
nothing more than a metal without software. Software is a series of instructions that instructs the computer hardware to do a certain
activity such as playing music, saving word files etc. It manages the computer hardware.
Regardless of differences in physical appearance, virtually computer hardware may be envisioned as divided into five logical units or
sections:
1. Input unit. This is the "receiving" section of the computer. It obtains information (data and computer programs) from
input devices and places this information at the disposal of the other units for processing. Most information is entered into
computers through keyboards and mouse devices. Information also can be entered in many other ways, including by speaking
to your computer, scanning images and having your computer receive information from a network, such as the Internet.
2. Output unit. This is the "shipping" section of the computer. It takes information that the computer has processed and
places it on various output devices to make the information available for use outside the computer. Most information output
from computers today is displayed on screens, printed on paper or used to control other devices. Computers also can output
their information to networks, such as the Internet.
3. Main memory unit. This is the rapid-access, relatively low-capacity "warehouse" section of the computer. It stores
computer programs while they are being executed. It retains information that has been entered through the input unit, so that it
will be immediately available for processing when needed. The memory unit also retains processed information until it can be
placed on output devices by the output unit. The memory unit is often called either memory or primary memory.
4. Central processing unit (CPU). This is the "administrative" and "manufacturing" section of the computer.
Arithmetic and logic unit (ALU), which is the manufacturing section of the CPU, is responsible for performing calculations,
such as addition, subtraction, multiplication and division. It contains the decision mechanisms that allow the computer, for
example, to compare two items from the memory unit to determine whether they are equal. The CPU also coordinates and
supervises the operation of the other sections. For instance the CPU tells the input unit when information should be read into
the memory unit, tells the ALU when information from the memory unit should be used in calculations and tells the output
unit when to send information from the memory unit to certain output devices. Many of today's computers have multiple CPUs
and, hence, can perform many operations simultaneously such computers are called multiprocessors.
5. Secondary memory unit. This is the long-term, high-capacity "warehousing" section of the computer. Programs or
data not actively being used by the other units normally are placed on secondary storage devices, such as your hard drive, until
they are again needed, possibly hours, days, months or even years later. Information in secondary storage takes much longer to
access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary
Computer Programming with C++ 2017Ec

memory. Other secondary storage devices include CDs and DVDs, which can hold hundreds of millions of characters and
billions of characters, respectively.

How do computers work?


You don’t have to know all the details of how a computer works to be a successful programmer, but understanding the underlying
principles will help you master the steps we go through to put our programs into action. It’s a bit like driving a car. Knowing a little
about internal combustion engines helps to explain why you have to do things like fill the gas tank, start the engine, step on the
accelerator, etc. You could learn to drive by just memorizing what to do, but a little more knowledge makes the whole process much
more understandable. Let’s take a moment to “look under the hood” of your computer.

So what happens when you fire up your favorite game or word processing program? First, the instructions that comprise the program
are copied from the (more) permanent secondary memory into the main memory of the computer. Once the instructions are loaded, the
CPU starts executing the program.
Technically the CPU follows a process called the fetch execute cycle. The first instruction is retrieved from memory, decoded to
figure out what it represents, and the appropriate action carried out. Then the next instruction is fetched, decoded and executed. The
cycle continues instruction after instruction. This is really all the computer does from the time that you turn it on until you turn it off
again: fetch, decode, execute. It doesn’t seem very exciting, does it? But the computer can execute this stream of simple instructions
with blazing speed, zipping through millions of instructions each second. Put enough simple instructions together in just the right way,
and the computer does amazing things.

What is a computer program?


A computer program is a detailed, step-by-step set of instructions telling a computer exactly what to do. The other name for a
computer program is software. The process of writing programs is called Computer Programming and the individual who writes
computer programs is called Computer Programmer.
There are different types of programming. The two basic ones are system and application programming. System programming deals
with the use of a computer system. This includes such things as the operating system, device drivers for input and output devices, and
systems utilities. Application programming deals with the programs that are directly used by most people. Application programming is
generally divided further into scientific and business programming.
Scientific programming is work in the scientific, engineering, and mathematical fields. Often the programmers are the researchers who
use the programs. Business programming is work in the data processing field, including large scale business systems, web-based
businesses, and office applications. It is exceedingly rare for these kinds of programs to be created by the person who uses them.
Another large category of programming is programming for personal or home use. This includes games. Historically, many advances
in computer science occurred in the development of computer and video games.
Embedded systems are programs that are built into specific hardware, such as the computer systems in an automobile or microwave
oven. These programs combine features of operating systems and application program into a single monolithic system.

PAGE 1 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

Scripting is a simplified version of programming originally intended for use primarily by non-programmers. In practice, most non-
programmers have trouble with scripting languages. Some professional programmers have built very useful, sometimes intricate
systems using scripting languages, especially those contained in office software (such as word processors or spreadsheets).

Programming languages
Remember that a program is just a sequence of instructions telling a computer what to do. Obviously, we need to provide those
instructions in a language that a computer can understand. It would be nice if we could just tell a computer what to do using our native
language, like they do in science fiction movies. (“Computer, how long will it take to reach planet Alphalpha at maximum warp?”)
Unfortunately, despite the continuing efforts of many top-flight computer scientists, designing a computer to understand human
language is still an unsolved problem.
Even if computers could understand us, human languages are not very well suited for describing complex algorithms. Natural
language is fraught with ambiguity and imprecision. For example, if I say: “I saw the man in the park with the telescope,” did I have
the telescope, or did the man? And who was in the park? We understand each other most of the time only because all humans share a
vast store of common knowledge and experience. Even then, miscommunication is commonplace.
Computer scientists have gotten around this problem by designing notations for expressing computations in an exact, and
unambiguous way. These special notations are called programming languages. Thus, Programming languages can be defined as
formal languages1 that have been designed to express computations. Every structure in a programming language has a precise form (its
syntax) and a precise meaning (its semantics). A programming language is something like a code for writing down the instructions that
a computer will follow.
In fact, programmers often refer to their programs as computer code, and the process of writing an algorithm in a programming
language is called coding.
C++ is one example of a programming language. It is the language that we will use throughout this course. You may have heard of
some other languages, such as C, Java, Perl, Scheme, or BASIC. Although these languages differ in many details, they all share the
property of having well-defined, unambiguous syntax and semantics.
All of the languages mentioned above are examples of high-level computer languages. Although they are precise, they are designed to
be used and understood by humans. Strictly speaking, computer hardware can only understand very low-level language known as
machine language.
Suppose we want the computer to add two numbers. The instructions that the CPU actually carries out might be something like this.
Load the number from memory location 2001 into the CPU
Load the number from memory location 2002 into the CPU
Add the two numbers in the CPU
Store the result into location 2003
This seems like a lot of work to add two numbers, doesn’t it? Actually, it’s even more complicated than this because the instructions
and numbers are represented in binary notation (as sequences of 0s and 1s).
In a high-level language like C++, the addition of two numbers can be expressed more naturally: c = a + b. That’s a lot easier for us to
understand, but we need some way to translate the high-level language into the machine language that the computer can execute.
There are two ways to do this: a high-level language can either be compiled or interpreted.

Formal languages are languages that are designed by people for specific applications. For example the notation that
mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.

PAGE 2 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

A compiler is a
complex computer program that takes another program written in a high-level language and translates it into an equivalent program in
the machine language of some computer all at once. The above figure shows a block diagram of the compiling process. The high-level
program is called source code, and the resulting machine code is a program that the computer can directly execute. The dashed line in
the diagram represents the execution of the machine code.

An interpreter is a program that simulates a computer that understands a high-level language. Rather than translating the source
program into a machine language equivalent, the interpreter analyzes and executes the source code instruction by instruction as
necessary. The above figure illustrates the process.
The difference between interpreting and compiling is that compiling is a one-shot translation; once a program is compiled, it may be
run over and over again without further need for the compiler or the source code. In the interpreted case, the interpreter and the source
are needed every time the program runs. Compiled programs tend to be faster, since the translation is done once and for all, but
interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run
interactively.

PAGE 3 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

Why should you learn Programming?


Computer programming is a challenging activity. Good programming requires an ability to see the big picture while paying attention
to minute detail. There are lots of good reasons to learn programming. Computers have become a commonplace tool in our society.
Understanding the strengths and limitations of this tool requires an understanding of programming. Non-programmers often feel they
are slaves of their computers. Programmers, however, are truly the masters. If you want to become a more intelligent user of
computers, then you absolutely should have an idea of programming.

Scientists also write programs to do routine, error prone and lengthy tasks using computers as they are very fast and don’t get tired in
the slightest.

Programming can also be loads of fun. It is an intellectually engaging activity that allows people to express themselves through useful
and sometimes remarkably beautiful creations. Believe it or not, many people actually write computer programs as a hobby.
Programming also develops valuable problem-solving skills, especially the ability to analyze complex systems by reducing them to
interactions of understandable subsystems.

Introduction to C++ Programming


What is C++?

C++ evolved from C, which evolved from two previous programming languages, BCPL and B. It was
developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories. It provides a number of features that
"spruce up" the C language; it provides features for procedural and object-oriented programming. However we
will not discuss any of the object oriented programming features of C++. C++ is a compiled higher level
programming language and many compilers have been written for it.

C++ programs consist of pieces called classes and functions. You can program each piece that you may need to
form a C++ program. However, most C++ programmers take advantage of the rich collections of existing
classes and functions in the C++ Standard Library. Thus, there are really two parts to learning the C++
"world." The first is learning the C++ language itself; the second is learning how to use the classes and
functions in the C++ Standard Library.

C++ Development Environment

C++ systems generally consist of three parts: a program development environment, the language and the C++
Standard Library. C++ programs typically go through six phases: edit, preprocess, compile, link, load and
execute.
Phase 1: Creating a Program

Phase 1 consists of editing a file with an editor program (normally known simply as an editor). You type a C++
program (typically referred to as source code) using the editor, make any necessary corrections and save the
program on a secondary storage device, such as a hard disk. C++ source code file names often end with
the .cpp, .cxx, .cc or .C extensions (note that C is in uppercase) which indicate that a file contains C++ source
code. We will use Quincy 2005 as an editor in this course. The file names can end with .cpp, .cxx or .cc
extension when Quincy 2005 is used as editor.

PAGE 4 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

Phases 2: Preprocessing

In phase 2, the programmer gives the command to compile the program. In a C++ system, a preprocessor
program executes automatically before the compiler's translation phase begins (so we call preprocessing phase 2
and compiling phase 3). The C++ preprocessor obeys commands called preprocessor directives, which
indicate that certain manipulations are to be performed on the program before compilation. These manipulations
usually include other text files to be compiled and perform various text replacements.

Phase 3: Compiling a C++ Program

In phase 3, the compiler translates the C++ program into machine-language code (also referred to as object
code).

Phase 4: Linking

Phase 4 is called linking. C++ programs typically contain references to functions and data defined elsewhere,
such as in the standard libraries or in the private libraries of groups of programmers working on a particular
project. The object code produced by the C++ compiler typically contains "holes" due to these missing parts. A
linker links the object code with the code for the missing functions to produce an executable image (with no
missing pieces). If the program compiles and links correctly, an executable image is produced.

Phase 5: Loading

Phase 5 is called loading. Before a program can be executed, it must first be placed in memory. This is done by
the loader, which takes the executable image from disk and transfers it to memory. Additional components
from shared libraries that support the program are also loaded.

Phase 6: Execution

Finally, the computer, under the control of its CPU, executes the program one instruction at a time.

PAGE 5 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

Figure 1. Typical C++ Environment

Problems That May Occur at Execution Time

Programs do not always work on the first try. Each of the preceding phases can fail because of various errors
that we discuss throughout the course. For example, an executing program might attempt to divide by zero (an
illegal operation for whole-number arithmetic in C++). This would cause the C++ program to display an error
message. If this occurs, you would have to return to the edit phase, make the necessary corrections and proceed
through the remaining phases again to determine that the corrections fix the problem(s).

PAGE 6 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

Elements of a C++ program:

Probably the best way to start learning a programming language is by writing a program. Therefore, here is our
first program:
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Output: Hello World!

The first part shows the source code for our first program. The second one shows the result of the program once
compiled and executed. The way to edit and compile a program depends on the compiler you are using.
The previous program is the typical program that programmer apprentices write for the first time, and its result
is the printing on screen of the "Hello World!" sentence. It is one of the simplest programs that can be written in
C++, but it already contains the fundamental components that every C++ program has. We are going to look
line by line at the code we have just written:
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have
any effect on the behavior of the program. The programmer can use them to include short explanations or
observations within the source code itself. In this case, the line is a brief description of what our program is.
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with
expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream> tells
the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of
the basic standard input-output library in C++, and it is included because its functionality is going to be used
later in the program.
main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point by
where all C++ programs start their execution, independently of its location within the source code. It does not
matter whether there are other functions with other names defined before or after it – the instructions contained
within this function's definition will always be the first ones to be executed in any C++ program. For that same
reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration:
In C++, what differentiates a function declaration from other types of expressions is these parentheses that
follow its name. Optionally, these parentheses may enclose a list of parameters within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is
contained within these braces is what the function does when it is executed.
cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually produce some
effect. In fact, this statement performs the only action that generates a visible effect in our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a
sequence of characters (in this case the Hello World sequence of characters) into the standard output stream
(which usually is the screen).

PAGE 7 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that
specific file and to declare that we were going to use this specific namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the
statement and in fact it must be included at the end of all expression statements in all C++ programs (one of the
most common syntax errors is indeed to forget to include some semicolon after a statement).
You may have noticed that not all the lines of this program perform actions when the code is executed. There
were lines containing only comments (those beginning by //). There were lines with directives for the compiler's
preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case,
the main function) and, finally lines with statements (like the insertion into cout), which were all included
within the block delimited by the braces ({}) of the main function.
The program has been structured in different lines in order to be more readable, but in C++, we do not have
strict rules on how to separate instructions in different lines. For example, instead of
int main ()
{
cout << " Hello World!";
return 0;
}
We could have written:
int main () { cout << "Hello World!"; return 0;}
All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (;) at the end of each one, so
the separation in different code lines does not matter at all for this purpose. We can write many statements per
line or write a single statement that takes many code lines. The division of code in different lines serves only to
make it more legible and schematic for the humans that may read it.
Let us add an additional instruction to our first program:
// my second program in C++
#include <iostream.h>
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
Output: Hello World! I'm a C++ program

In this case, we performed two insertions into cout in two different statements. Once again, the separation in
different lines of code has been done just to give greater readability to the program, since main could have been
perfectly valid defined this way:
int main () { cout << " Hello World! "; cout << " I'm a C++ program "; }

We were also free to divide the code into more lines if we considered it more convenient:
main ()
{
cout <<
"Hello World!";
cout

PAGE 8 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

<< "I'm a C++ program";


}
And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They
are lines read and processed by the preprocessor and do not produce any code by themselves. Preprocessor
directives must be specified in their own line and do not have to end with a semicolon (;).

Comments
Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is
only to allow the programmer to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found
up to the end of that same line. The second one, known as block comment, discards everything between the /*
characters and the first appearance of the */ characters, with the possibility of including more than one line.
We are going to add comments to our second program:

/* my second program in C++


with more comments */
#include <iostream>
int main ()
{
cout << "Hello World! "; // prints Hello World!
cout << "I'm a C++ program"; // prints I'm a C++ program
}
Output: Hello World! I'm a C++ program
If you include comments within the source code of your programs without using the comment characters
combinations //, /* or */, the compiler will take them as if they were C++ expressions, most likely causing one
or several error messages when you compile it.
Summary
 A computer is an electronic device that stores and manipulates information under the control of a
changeable program.
 We can put information into a computer, and it can transform the information into new, useful forms,
and then output or display the information for our interpretation.
 Machines that perform a single task like a simple calculator are not full-fledged computers as they don’t
operate under the control of a changeable program. In other words machines that are not programmable
are not computers.
 Software/Computer program is a detailed, step-by-step set of instructions telling a computer exactly
what to do.
 Hardware is the physical/tangible part of a computer.
 The six logical units of a computer are
o Input unit: This is the "receiving" section of the computer.
o Output unit: This is the "shipping" section of the computer.

PAGE 9 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

o Main memory unit: This is the rapid-access, relatively low-capacity "warehouse" section of the
computer.
o Central processing unit (CPU): This is the "administrative" and "manufacturing" section of the
computer.
o Secondary memory unit: This is the long-term, high-capacity "warehousing" section of the
computer.
 Multiprocessors are computers with more than one CPU.
 A computer works in simple fashion that is called the fetch execute cycle. When a computer program,
which is a sequence of many instructions, is loaded into memory, the first instruction in the program is
retrieved from memory, decoded to figure out what it represents, and the appropriate action carried out.
Then the next instruction is fetched, decoded and executed. The process continues like this until the
computer is turned off.
 Computer programming is the process of writing computer programs.
 There are different types of programming
o System programming deals with computer system.
o Application programming deals with programs that are used by people. There are two types of
application programs
 Scientific programming deals with programs that are used in the scientific, engineering and
mathematical fields.
 Business programming deals with programs that are used to facilitate the day to day
activities of data processing corporations, including large scale business systems, web-
based businesses, and office applications.
o Embedded systems programming deals with programs that are built into specific hardware such as
automobiles, micro waves, etc.
o Scripting language programming is intended for use by non-programmers. They are especially
included in office software. For instance the feature in Microsoft Excel that helps us to assign a
grade to a certain mark by using the if statement is a scripting language.
 Programmers can’t use natural languages to communicate with computers because of their imprecise
and ambiguous nature. As a result programming languages were invented.
 Programming languages are formal languages that have been designed to express computations.
 Higher level programming languages are English like formal languages. C++ is an example of a higher
level programming language.
 Computer hardware understands only machine language. Thus, translators are required to convert
programs that are written in higher level programming language into machine language.
 Compilers are translators that convert a program that is written in higher level programming language
into machine language all at once. Once the program is converted and execution of the machine
language starts the compiler is not required.
 Interpreters are translators that convert a program that is written in higher level programming language
into machine language instruction by instruction as necessary. The interpreter stays active while the
program is being executed, in fact when an instruction is converted into a machine language it will be
executed by the computer.

PAGE 10 Unit 01 – Introduction to Computer Programming


Computer Programming with C++ 2017Ec

 Learning computer programming helps you to


o Become an intelligent user of a computer
o Solve scientific problems that are lengthy, routine and error prone using computers
o Develop valuable problem solving skills

References
 H. M. Deitel & P. J. Deitel, “C++ How to Program”, Fifth Edition, Prentice Hall, 2005.
 John M. Zelle, Ph.D., “Python Programming: An Introduction to Computer Science”, Wartburg College
Printing Services, 2002.

PAGE 11 Unit 01 – Introduction to Computer Programming

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy