CPP 1 Corrected)
-
Upload
blu-fageria -
Category
Documents
-
view
217 -
download
0
Transcript of CPP 1 Corrected)
-
8/3/2019 CPP 1 Corrected)
1/48
Computers are electronic information-processing machines. Data and programs in
these machines are saved, moved, and transformed in the form of electrical voltages.
These electrical voltages can be interpreted as a zeros and ones. The zeros andones can be aggregated and interpreted as words, numbers, images, sounds, and
so on.
Long ago, informationbe it data or programscould be entered into the computer by
manipulating switches on the front of the machine. Today, there are better methods.
Computer programming languages convert text into the requisite binary instructions.
If your computer could understand English, you would not have to learn a programming
language. But because it does not understand English, you must learn to write instructions
in a language your computer recognizes.
-
8/3/2019 CPP 1 Corrected)
2/48
Early computers were programmed in machine language. To see how instructions are written
in machine language, suppose you want to use the equation:
wages = rate * hours
to calculate weekly wages.
Further, suppose that the binary code 100100 stands for load, 100110 stands for
multiplication, and 100010 stands for store. In machine language, you might need the
following sequence of instructions to calculate weekly wages:
100100 010001
100110 010010
100010 010011
To represent the weekly wages equation in machine language, the programmer had to
remember the machine language codes for various operations. Also, to manipulate data, the
programmer had to remember the locations of the data in the main memory. This need to
remember specific codes made programming not only very difficult, but also error-prone.
-
8/3/2019 CPP 1 Corrected)
3/48
The 1960s gave birth to structured programming. This is the method of
programming supported by languages such as C. With structured languages, it
was, for the first time, possible to write moderately complex programs fairly easily.
Dividing a problem into smaller subproblems is called structured design. Each
subproblem is then analyzed, and a solution is obtained to solve the subproblem.
The solutions to all of the subproblems are then combined to solve the overall
problem. This process of implementing a structured design is called structured
programming. The structured-design approach is also known as top-down design,
bottom-up design, stepwise refinement, and modular programming.
However, even with structured programming methods, once a project reaches a
certain size, its complexity exceeds what a programmer can manage. By the late
1970s, many projects were near or at this point. To solve this problem, a new way
to program began to emerge.
This method is called object-oriented programming (OOP for short). Using OOP, a
programmer could handle larger programs. The trouble was that C did not support
object-oriented programming. The desire for an object-oriented version of C
ultimately led to the creation of C++.
-
8/3/2019 CPP 1 Corrected)
4/48
In response to the need to manage greater complexity, C++ was born. It was invented
by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially
called the new language C with Classes. However, in 1983 the name was changed
to C++.
C++ contains the entire C language. As stated earlier, C is the foundation upon which C++ is
built. C++ includes all of Cs features, attributes, and benefits. It also adheres to Cs
philosophy that the programmer, not the language, is in charge. At this point, it is critical to
understand that the invention of C++ was not an attempt to create a new programming
language. Instead, it was an enhancement to an already highly successful language.
-
8/3/2019 CPP 1 Corrected)
5/48
Most of the additions that Stroustrup made to C were designed to support object-oriented
programming. In essence, C++ is the object-oriented version of C. By building upon the
foundation of C, Stroustrup provided a smooth migration path to OOP. Instead of having to
learn an entirely new language, a C programmer needed to learn only a few new features toreap the benefits of the object-oriented methodology. But C is not the only language that
influenced C++.
Stroustrup states that some of its object-oriented features were inspired by another object-
oriented language called Simula67. Therefore, C++ represents the blending of two powerful
programming methods.
When creating C++, Stroustrup knew that it was important to maintain the original spirit of C,
including its efficiency, flexibility, and philosophy, while at the same time adding support for
object-oriented programming. Happily, his goal was accomplished.
C++ still provides the programmer with the freedom and control of C, coupled with the powerof objects.
-
8/3/2019 CPP 1 Corrected)
6/48
What Is Object-Oriented Programming?
Since object-oriented programming was fundamental to the development of C++, it
is important to define precisely what object-oriented programming is.
Object-oriented programming has taken the best ideas of structured programming and has
combined them with several powerful concepts that allow you to organize your programs
more effectively.
In general, when programming in an object-oriented fashion, you decompose a problem
into its constituent parts.
Each component becomes a self-contained object that contains its own instructions and
data related to that object. Through this process, complexity is reduced and you can
manage larger programs.
All object-oriented programming languages have three things in common: encapsulation,
polymorphism, and inheritance.
-
8/3/2019 CPP 1 Corrected)
7/48
Encapsulation
As you probably know, all programs are composed of two fundamental elements:
program statements (code) and data. Code is that part of a program that performs actions, and
data is the information affected by those actions.
Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse.
In an object-oriented language, code and data may be bound together in such a way that a self-
contained black box is created. Within the box are all necessary data andcode. When code and
data are linked together in this fashion, an object is created.
In other words, an object is the device that supports encapsulation. Within an object, the code,
data, or both may be private to that object or public.
Private code or data is known to, and accessible only by, another part of the object. That is,
private code or data may not be accessed by a piece of the program that exists outside theobject. When code or data ispublic, other parts of your program may access it, even though it is
defined within an object. Typically, the public parts of an object are used to provide a controlled
interface to the private elements of the object.
-
8/3/2019 CPP 1 Corrected)
8/48
Polymorphism
Polymorphism (from the Greek, meaning many forms) is the quality that allows one
interface to be used for a general class of actions.
The specific action is determined by the exact nature of the situation. A simple example of
polymorphism is found in the steering wheel of an automobile. The steering wheel (i.e., the
interface) is the same no matter what type of actual steering mechanism is used. That is, the
steering wheel works the same whether your car has manual steering, power steering, or rack-
and-pinion steering. Therefore, once you know how to operate the steering wheel, you can drive
any type of car.
The same principle can also apply to programming. For example, consider a stack (which is a
first-in, last-out list). You might have a program that requires three different types of stacks. One
stack is used for integer values, one for floating-point values, and one for characters.
In this case, the algorithm that implements each stack is the same, even though the data being
stored differs. In a non-object-oriented language, you would be required to create threedifferent sets of stack routines, calling each set by a different name, with each set having its own
interface. However, because of polymorphism, in C++ you can create one general set of stack
routines (one interface) that works for all three specific situations. This way, once you know how
to use one stack, you can use them all.
-
8/3/2019 CPP 1 Corrected)
9/48
Inheritance
Inheritance is the process by which new classes called derived classes are created from existing
classes called base classes. The derived classes have all the features of the base class and the
programmer can choose to add new features specific to the newly created derived class.
For example, a programmer can create a base class named fruit and define derived classes as
mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all
the features of the base class (fruit) with additional attributes or features specific to these newly
created derived classes. Mango would have its own defined features, orange would have its own
defined features, banana would have its own defined features, etc.
Inheritance helps the code to be reused in many situations. The base class is defined and once it
is compiled, it need not be reworked. Using the concept of inheritance, the programmer can
create as many derived classes from the base class as needed while adding specific features to
each derived class as needed.
The above concept of reusability achieved by inheritance saves the programmer time and effort.Since the main code written can be reused in various situations as needed.
Increases Program Structure which results in greater reliability.
-
8/3/2019 CPP 1 Corrected)
10/48
C++ is a compiled language.
This means that before the program is run, it is first translated into a form that the
machine can use directly.
The C++ files (and a typical project contains several) are called the source files. You create
the source files bytyping them using a program called a text editor.
The translation of the source files into a program proceeds in two phases.
First, the individual source files are translated by a program called the compiler into socalled object files. Next, a second program, called a linker (or loader) combines the
individual object files into an executable file, that is, a program you can execute
(run).
The precise manner in which is all this is done (source file creation/editing, compiling,
linking, and execution) varies among different computing platforms.
-
8/3/2019 CPP 1 Corrected)
11/48
The C++ language consists of two basic elements:
Semantics: This is a vocabulary of commands that humans can understand and
that can be converted into machine language, fairly easily.
and
Syntax: This is a language structure (or grammar) that allows humans to combine
these C++ commands into a program that actually does something
(well, maybe does something).
To write a program, you need two specialized computer programs. One (an editor) is what
you use to write your code as you build your .CPP source file.
The other (a compiler) converts your source file into a machine-executable .EXE file that
carries out your real-world commands (open spreadsheet, make rude noise, deflect
incoming asteroid, whatever).
Nowadays, tool developers generally combine compiler and editor into a single package
a development environment. After you finish entering the commands that make up
your program, you need only click a button to create the executable file.
-
8/3/2019 CPP 1 Corrected)
12/48
A computer program is simply a set of instructions to tell a computer how to perform a
particular task.
At the very simplest level it consists of issuing a sequence of commands to a computer to
achieve an objective.
A C++ program is a text file containing a sequence of C++ commands put together
according to the laws of C++ grammar. This text file is known as the source file (probablybecause its the source of all frustration). A C++ source file carries the extension .CPP just
as a Microsoft Word file ends in .DOC or an MS-DOS (remember that?) batch file ends in
.BAT. The concept extension .CPP is just a convention.
Whats a program?
It is not possible to execute this file directly. The source file is passed to a compiler
(a program which generates a new file containing a machine code translation of the source
text). This file is called an object file or executable file.
The executable file is said to have been compiled from the source text.
-
8/3/2019 CPP 1 Corrected)
13/48
-
8/3/2019 CPP 1 Corrected)
14/48
All C++ programs are based on what are known as C++ statements.
A statement is a single set of commands. All statements other than comments
end with a semicolon.
A declaration is a statementthat defines a variable. A variable is a holding tankfor a value of some type. A variable contains a value, such as a number or a
character.
For example
int age;
is a declaration statement.
C++ is a case-sensitive:
This means the word name is different from the word Name or any other variations
related to capitalization.
Unlike some other programming languages, such as COBOL, C++ is afree-form language,
meaning that programming statement can start in any column of any line. You can insert
blank lines in a program if you want.
-
8/3/2019 CPP 1 Corrected)
15/48
-
8/3/2019 CPP 1 Corrected)
16/48
-
8/3/2019 CPP 1 Corrected)
17/48
It may seem odd to have a command in C++ (or any other programming language)
thats specifically ignored by the computer. However, all computer languages have some
version of the comment. Its critical that the programmer explain what was going through
her mind when she wrote the code. A programmers thoughts may not be obvious to the
next colleague who picks up her program and tries to use it or modify it. In fact, theprogrammer herself may forget what her program meant if she looks at it months after
writing the original code and has left no clue.
Single-line comments begin with a double slash // and continue to the end of the line. They
are useful for short comments.
Multiple-line comments may span one or more lines. The comment begins with the pair of
characters /* and ends with */.
#include
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. The jobof the preprocessor is to read through your source code looking for lines that begin with #,
and when it finds one, to modify the code as requested by that command. These
manipulations usually include other text files to be compiled and perform various text
replacements. This all happens before the compiler sees your code.
-
8/3/2019 CPP 1 Corrected)
18/48
The #include tells the compiler to include the header file iostream.hthe
compiler is smart enough to know about the .h, so you dont have to put it in. This header
file describes what components the library provides so that the compiler can recognize
names such as cout. This header file is part of the C++ system, and so is called a system
header file.
Including the header file for iostream gives you the ability to use the iostream library.
You can open the iostream.h file if you can find it on your system (usually in the
include subdirectory of the directory where your compiler is installed). You will probably
find its source code hard to understand. Fortunately, the compiler doesnt.
The iostream file must be included for any program that outputs data to the screen or
inputs data from the keyboard using C++ style stream input/output. It also includes the
declaration of the stream inserter (
-
8/3/2019 CPP 1 Corrected)
19/48
The cout object: This is an object to which we send information that we want written on
the computer screen. The word cout is an abbreviation of console output.
The
-
8/3/2019 CPP 1 Corrected)
20/48
The object cout is not core part of C++, but standard addition to the language. It is possible
that a software developerlets call her Sophiemight want a different version ofcout that is
somehow different from the standard version.
Sophie also wants to call her console output object cout; this is possible in C++. Sophie creates
(dont worry about how, you are not a software developer) a separate namespace, which she
calls, say, sophie. Each namespace itself has a name that is added to any names in the code it
holds. Therefore, the full name of Sophies cout is sophie::cout. Similarly, the full name of the
standard cout is std::cout, where std stands for the standard namespace.
We can say that namespaces are a sort of container for names (or objects).
In the iostream file, cout is defined to have the full name std::cout. It is possible to
delete line using namespace std; from the program, but then it would be necessary to
replacecout with std::cout. However, for our purposes, it is much easier to declare: we are
going to be using the standard namespace, so we will use the short forms of the names. Thats
what the statement using namespace std; does.
-
8/3/2019 CPP 1 Corrected)
21/48
The statement using namespace std tells the compiler, If you see a name and you
dont know what namespace it is from, assume it is from the std namespace.
If you leave this command out, you will get the following message from the compiler:
error : cout was not declared in this scope
This is because the compiler does not know where to look for cout. Since we never
mention the namespace in which they can be found.
We could cure this without the using namespace statement by changing
line to std::cout
-
8/3/2019 CPP 1 Corrected)
22/48
The basic building block in a C++ program is thefunction.
The term function refers to a task or job.
Every C++ program is a collection of one or more functions, written in some arbitrary order.
One and only one of these functions in the program must have the name main().
C++ program always start its execution at the function named main.
It doesnt matter if main is physically located at the beginning or end of your source code.
Functions take various values as arguments, execute instructions, and return a value. In this
case, the function named main returns an integer value; this is signified by the word int
before the name of the function.
The value returned is zero, and this is accomplished at the end of the function with thestatement return 0; which returns the value 0.
-
8/3/2019 CPP 1 Corrected)
23/48
The main function does not take any arguments; this is signified by the empty pair of
parentheses following the word main.
The main function defined as : main() { }
int main() // function header, no semicolon
{ // start of function body
return 0; // C++ statement, requires semicolon
}//
end of function body
The function definition is the combination of the function header and the function body.
A function header is the first line in a function definition.
The function body contains the statements enclosed in curly braces.
-
8/3/2019 CPP 1 Corrected)
24/48
The function main() does not have to be at the top of a program so a C++ program does not
necessarily start at line 1. It always starts where main() is.
Also, the function main()cannot be called from any other function in the program.
Only the operating system can call the function main(): this is how a C++ program is started.
-
8/3/2019 CPP 1 Corrected)
25/48
Escape Sequence:
Non graphics characters (characters that can be
typed directly from keyboard e.g. backspace, tabs,
carriage return etc.) can be represented by using
escape sequences.
An escape sequence is represented by a backslash (\)followed by one or more characters.
An escape sequence is represents a single character.
-
8/3/2019 CPP 1 Corrected)
26/48
Escape Sequence: Non graphic character
\a Audible bell (alert)
\b Backspace
\n Newline or linefeed
\t Horizontal tab
\v Vertical tab
\\ Backslash
\ Single quote
\ Double quote
\0 Null character
A null character is a special character, used among other things to give a
character variable an initial value.
-
8/3/2019 CPP 1 Corrected)
27/48
What will be the output of the following C++ code:
#include
using namespace std;main()
{
cout
-
8/3/2019 CPP 1 Corrected)
28/48
The following comment in a C++ program would cause the compiler to issue
an error message.
/*
* In C++ comments are enclosed between /* and */
*/
Whats wrong?
For the following code, indicate if there are any errors. If there is an error,
specify how you fix it:
1. \\ This is my first program
2. /* this is the example of multi line Comment/*
3. /* Isnt this /* a fun */ comment */
4. int main();
5. int main( )
(
return 0 ;
)
-
8/3/2019 CPP 1 Corrected)
29/48
int main()
{
return 0
} end of main() function
Numbers are the building blocks of mathematics and, of course, computers are extremely
adept with numbers. There are several ways in which numbers are handled in C++.
Numbers in C++ are divided into two broad categories: integers and reals.
Each of these categories is refined further. Of course, to a mathematician every integer is a
real number, so these categories may seem spurious.
The reasons for having many different ways to represent numbers are efficiency and
accuracy; if the quantities with which we are computing are known to be integral, then using
an integer representation is not subject to roundoff error and the computations are faster.
-
8/3/2019 CPP 1 Corrected)
30/48
-
8/3/2019 CPP 1 Corrected)
31/48
Literals:
Literals (often referred to as constants) are data items thatnever change their value during a program run.
C++ allows several kinds of literals:
Literals
Integer
Decimal Octal Hexadecimal
Floating Character String
-
8/3/2019 CPP 1 Corrected)
32/48
Variables:
Avariable is a placeholder whose contents can change. A placeholder is given a name, which we use reference the
value stored in the variable.
Every variable name in C++ must start with a letter, the rest ofthe name can consist of letters, numbers and underscorecharacters.
It can not contain any blanks, commas or special symbols,such as ()!?.
C++ recognizes upper and lower case characters as being
different. you cannot use any of C++ keywords like main, while, switch
etc. as variable names.
-
8/3/2019 CPP 1 Corrected)
33/48
Examples of Variable Names:
Valid Variable Names:
Idnumber
sumofnumbers
I, j, k1transaction_number
phone_number
CASENO
Invalid Variable Names:
4myfriend
sum of two no
s.no
T1_
amount@1
while
write
-
8/3/2019 CPP 1 Corrected)
34/48
Every variable in a C++ program must be given a type.
The type of a variable is a specification of the kind of data the variable can store. The most
basic type is int.
An int represents an integer quantity.
In this program, two variables, x and y, are declared to be of type int.
C++ requires that we specify the type of every variable, and the declaration statement is the
manner by which this is accomplished.. Variables may be declared anywhere in the program so
long as they are declared before they are used.
Subsequently the variables are assigned values.
In this case x is assigned the value 3 and y the value 4.
The equal sign = is an operation (called assignment) that stores the value of the expression toits right into the variable on its left.
-
8/3/2019 CPP 1 Corrected)
35/48
It is possible to combine declarations on a single line; in place of lines 6 and 7, we could have
this:
int x,y;
It is possible to combine declaration with assignment. Lines 910 can be replaced by these two:
int x = 3;
int y = 4;
In line 12, the contents ofx and y are added, and the result is written on the computers screen.
Variables of type int can store a finite range of integer values. The size of that range depends
on your specific computer.
On many computers an int is held in 4 bytes of memory (one byte is 8 bits, so this is 32 bits).
With 32 bits one can store 232 different values.
-
8/3/2019 CPP 1 Corrected)
36/48
There is an easy way to learn the size of an int on your computer in C++ with the sizeof
operator. Evaluating sizeof(int) gives the number of bytes used to store variables of type
int.
There are a few variations of the fundamental int type.
A short is an integer type that is either the same as int, or else a smaller size than int.
That is, sizeof(short)cannot exceed sizeof(int).
There are a few variations of the fundamental int type.
A short is an integer type that is either the same as int, or else a smaller size than int.
That is, sizeof(short) cannot exceed sizeof(int).
A long is an integer type that is either the same size as int, or else a larger size than int. In
other words, sizeof(long) is at least sizeof(int).
Some compilers provide a long long type. This is an integer type that is at least the size of
a long. That is, sizeof(long long)cannot be less than sizeof(long).
In summary,
sizeof(short) sizeof(int) sizeof(long) sizeof(long long).
-
8/3/2019 CPP 1 Corrected)
37/48
-
8/3/2019 CPP 1 Corrected)
38/48
C++ provides header files with this information. The header file climits gives the minimum and
maximum value of various integer types. It defines symbols such as INT_MIN and INT_MAX that
are equal to the smallest and largest value an int may hold. Similarly, the header file cfloat gives
the minimum positive, maximum, and epsilon values for float, double, and long double (if
available) data types.
-
8/3/2019 CPP 1 Corrected)
39/48
The bool and char types
There are other basic data types available in C++. Two that we encounter frequently in C++ are
designed for handling Boolean and character data.
The data type bool is used to represent the logical values TRUE and FALSE. In C++, these arerepresented as integers: 1 for TRUE and 0 for FALSE. Indeed, bool is considered to be an
integer type.
Boolean values emerge as the result of comparison operations. In C++, to see if two variables
hold equal values we use the == operator.
The result of x == y is either 1 (TRUE) in the case where x and y hold equal values and 0
(FALSE) otherwise.
If your program contains the statement
cout
-
8/3/2019 CPP 1 Corrected)
40/48
Individual characters have the type char. One can create variables to hold single characters
by declaring them to be of type char as shown below:
char x;
x = A;
cout
-
8/3/2019 CPP 1 Corrected)
41/48
Exercises:What is wrong with each of the following declaration
statement:1. int a, int b;
2. int a = 0, b = 4.5;
3. char grade = A;
4. char title = this is first test program;
5. int base_salary (30000)
int id_num, staff_salary = base_salary;
6.float area, circumfrence;
-
8/3/2019 CPP 1 Corrected)
42/48
C++Constants:
ANSI C++ allows you to declare constants.
A constant is similar to a variable in the sense that it
represents a memory location.
It differs, in that it cannot be reassigned a new value after
initialization.
The const keyword is to declare a constant, as shown below: int const a = 1; or const int a =2;
const double PI = 3.1416;
Note: You can declare the const before or after the type.
It is usual to initialize a constant with a value as it cannot get a value any otherway.
-
8/3/2019 CPP 1 Corrected)
43/48
There are three techniques used to define
constants in C++:
Using #define
Using const variables
Using Enumerated Data Types
-
8/3/2019 CPP 1 Corrected)
44/48
Example:// defined constants: calculate circumference
#include using namespace std;
#define PI 3.14159
int main ()
{
double r = 5.0; // radius
double circle;
circle = 2 * PI * r;
cout
-
8/3/2019 CPP 1 Corrected)
45/48
Standard operations
C++ provides the familiar arithmetic operations. The expressions x+y, x-y, x*y, and
x/y are the usual sum, difference, product, and quotient ofx and y.
In these expressions, x and y may be any of the numeric types we discussed.
However, mixing types can sometimes cause problems and confusion. Ifx and y are of the
same type, then the result of the operation is also that type. For example, consider the
following code:
int numerator = 13;
int denominator = 5;
double quotient;
quotient = numerator/denominator;
cout
-
8/3/2019 CPP 1 Corrected)
46/48
We might expect this code to print the value 2.6 on the computers screen. The
surprise is that the computer prints 2. To understand why, we have to remember
that when two int values are divided, the result is an int.
In this case, C++ divides the integers 13 and 5 to give the result 2 (the fractionalpart is lost) and then assigns that value to quotient.
Because quotient is of type double there is a silent, behind-the-scenes conversion
of the int quantity into a double quantity.
We can coerce C++ to give us the answer 2.6 by converting 13 or 5 (or both) into
double variables. We replace quotient = numerator/denominator with this:
quotient = double(numerator) / double(denominator);
The expression double(numerator) converts the integer value in numerator into a
double quantity. This conversion process is known as casting. Note that the variables
numerator and denominator are unaffected by this; they remain type int and their typecannot be changed. What double(numerator) does is create a temporary double
number to be used in the division.
-
8/3/2019 CPP 1 Corrected)
47/48
-
8/3/2019 CPP 1 Corrected)
48/48