Programación 1
Programación 1
Preliminaries
This chapter introduces the basic elements of a C++ program. We will use
simple examples to show the structure of C++ programs and the way they are
compiled. Elementary concepts such as constants, variables, and their storage
in memory will also be discussed.
The following is a cursory description of the concept of programming for
the benefit of those who are new to the subject.
Programming
A digital computer is a useful tool for solving a great variety of problems. A
solution to a problem is called an algorithm; it describes the sequence of steps
to be performed for the problem to be solved. A simple example of a problem
and an algorithm for it would be:
Problem:
Algorithm:
www.pragsoft.com
Chapter 1: Preliminaries
#include <iostream.h>
int main (void)
{
cout << "Hello World\n";
}
Annotation
This line defines a function called main. A function may have zero or
more parameters; these always appear after the function name, between a
pair of brackets. The word void appearing between the brackets indicates
that main has no parameters. A function may also have a return type; this
always appears before the function name. The return type for main is int
(i.e., an integer number). All C++ programs must have exactly one main
function. Program execution always begins from main.
C++ Programming
$ CC hello.cc
$ a.out
Hello World
$
Annotation
The return of the system prompt indicates that the program has completed
its execution.
$ CC hello.cc -o hello
$ hello
Hello World
$
www.pragsoft.com
Chapter 1: Preliminaries
First, the C++ preprocessor goes over the program text and carries out
the instructions specified by the preprocessor directives (e.g., #include).
The result is a modified program text which no longer contains any
directives. (Chapter 12 describes the preprocessor in detail.)
Then, the C++ compiler translates the program code. The compiler may
be a true C++ compiler which generates native (assembly or machine)
code, or just a translator which translates the code into C. In the latter
case, the resulting C code is then passed through a C compiler to produce
native object code. In either case, the outcome may be incomplete due to
the program referring to library routines which are not defined as a part of
the program. For example, Listing 1.1 refers to the << operator which is
actually defined in a separate IO library.
Finally, the linker completes the object code by linking it with the object
code of any library modules that the program may have referred to. The
final result is an executable file.
Figure 1.1 illustrates the above steps for both a C++ translator and a C++
native compiler. In practice all these steps are usually invoked by a single
command (e.g., CC) and the user will not even see the intermediate files
generated.
Figure 1.1 C++ Compilation
C++
Program
C++
Program
C++
TRANSLATOR
C
Code
C
COMPILER
C++
Object
NATIVE
Code
COMPILER
ExecutLINKER
able
C++ Programming
Variables
A variable is a symbolic name for a memory location in which data can be
stored and subsequently recalled. Variables are used for holding data values so
that they can be utilized in various computations in a program. All variables
have two important attributes:
#include <iostream.h>
int main (void)
{
int
workDays;
float
workHours, payRate, weeklyPay;
workDays = 5;
workHours = 7.5;
payRate = 38.55;
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
}
Annotation
This line defines an int (integer) variable called workDays, which will
represent the number of working days in a week. As a general rule, a
variable is defined by specifying its type first, followed by the variable
name, followed by a semicolon.
This line defines three float (real) variables which, respectively, represent
the work hours per day, the hourly pay rate, and the weekly pay. As
illustrated by this line, multiple variables of the same type can be defined
at once by separating them with commas.
www.pragsoft.com
Chapter 1: Preliminaries
10-12 These lines output three items in sequence: the string "Weekly Pay =
", the value of the variable weeklyPay, and a newline character.
When run, the program will produce the following output:
Weekly Pay = 1445.625
#include <iostream.h>
int main (void)
{
int
workDays = 5;
float
workHours = 7.5;
float
payRate = 38.55;
float
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
}
C++ Programming
Simple Input/Output
The most common way in which a program communicates with the outside
world is through simple, character-oriented Input/Output (IO) operations.
C++ provides two useful operators for this purpose: >> for input and << for
output. We have already seen examples of output using <<. Listing 1.4 also
illustrates the use of >> for input.
Listing 1.4
1
2
3
4
5
6
#include <iostream.h>
int main (void)
{
int
workDays = 5;
float
workHours = 7.5;
float
payRate, weeklyPay;
7
8
9
10
11
12
13
Annotation
This line outputs the prompt What is the hourly pay rate? to seek
user input.
This line reads the input value typed by the user and copies it to payRate.
The input operator >> takes an input stream as its left operand (cin is
the standard C++ input stream which corresponds to data entered via the
keyboard) and a variable (to which the input data is copied) as its right
operand.
9-13
When run, the program will produce the following output (user input appears
in bold):
What is the hourly pay rate? 33.55
Weekly Pay = 1258.125
Both << and >> return their left operand as their result, enabling multiple
input or multiple output operations to be combined into one statement. This is
illustrated by Listing 1.5 which now allows the input of both the daily work
hours and the hourly pay rate.
Listing 1.5
www.pragsoft.com
Chapter 1: Preliminaries
#include <iostream.h>
2
3
4
5
6
7
8
9
10
cout << "What are the work hours and the hourly pay rate? ";
cin >> workHours >> payRate;
weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = " << weeklyPay << '\n';
}
Annotation
This line reads two input values typed by the user and copies them to
workHours and payRate, respectively. The two values should be
separated by white space (i.e., one or more space or tab characters). This
statement is equivalent to:
(cin >> workHours) >> payRate;
Because the result of >> is its left operand, (cin >> workHours)
evaluates to cin which is then used as the left operand of the next >>
operator.
9
This line is the result of combining lines 10-12 from Listing 1.4. It outputs
"Weekly Pay = ", followed by the value of weeklyPay, followed by a
newline character. This statement is equivalent to:
((cout << "Weekly Pay = ") << weeklyPay) << '\n';
Because the result of << is its left operand, (cout << "Weekly Pay = ")
evaluates to cout which is then used as the left operand of the next <<
operator, etc.
When run, the program will produce the following output:
What are the work hours and the hourly pay rate? 7.5 33.55
Weekly Pay = 1258.125
C++ Programming
Comments
A comment is a piece of descriptive text which explains some aspect of a
program. Program comments are totally ignored by the compiler and are only
intended for human readers. C++ provides two types of comment delimiters:
#include <iostream.h>
/* This program calculates the weekly gross pay for a worker,
based on the total number of hours worked and the hourly pay
rate. */
int main (void)
{
int
workDays = 5;
float
workHours = 7.5;
float
payRate = 33.50;
float
weeklyPay;
//
//
//
//
A comment should be easier to read and understand than the code which
it tries to explain. A confusing or unnecessarily-complex comment is
worse than no comment at all.
Use of descriptive names for variables and other entities in a program, and
proper indentation of the code can reduce the need for using comments.
The best guideline for how to use comments is to simply apply common sense.
www.pragsoft.com
Chapter 1: Preliminaries
Memory
A computer provides a Random Access Memory (RAM) for storing
executable program code as well as the data the program manipulates. This
memory can be thought of as a contiguous sequence of bits, each of which is
capable of storing a binary digit (0 or 1). Typically, the memory is also
divided into groups of 8 consecutive bits (called bytes). The bytes are
sequentially addressed. Therefore each byte can be uniquely identified by its
address (see Figure 1.2).
Figure 1.2 Bits and bytes in memory.
Byte Address
...
1211
1212
1213
1214
1215
1216
Byte
Byte
Byte
Byte
Byte
Byte
1217
Byte
... Memory
1 1 0 1 0 0 0 1
Bit
The C++ compiler generates executable code which maps data entities to
memory locations. For example, the variable definition
int salary = 65000;
causes the compiler to allocate a few bytes to represent salary. The exact
number of bytes allocated and the method used for the binary representation of
the integer depends on the specific C++ implementation, but let us say two
bytes encoded as a 2s complement integer. The compiler uses the address of
the first byte at which salary is allocated to refer to it. The above assignment
causes the value 65000 to be stored as a 2s complement integer in the two
bytes allocated (see Figure 1.3).
Figure 1.3 Representation of an integer in memory.
...
1211
1212
1213
1214
1215
1216
Byte
Byte
Byte
10110011
10110011
Byte
1217
Byte
... Memory
salary
(a two-byte integer whose address is 1214)
10
C++ Programming
Integer Numbers
An integer variable may be defined to be of type short, int, or long. The
only difference is that an int uses more or at least the same number of bytes
as a short, and a long uses more or at least the same number of bytes as an
int. For example, on the authors PC, a short uses 2 bytes, an int also 2
bytes, and a long 4 bytes.
short
int
long
age = 20;
salary = 65000;
price = 4500000;
age = 20;
salary = 65000;
price = 4500000;
1984l
1984U
1984u
1984LU 1984ul
// decimal
// equivalent octal
// equivalent hexadecimal
Octal numbers use the base 8, and can therefore only use the digits 0-7.
Hexadecimal numbers use the base 16, and therefore use the letter A-F (or af) to represent, respectively, 10-15. Octal and hexadecimal numbers are
calculated as follows:
0134 = 1 82 + 3 81 + 4 80 = 64 + 24 + 4 = 92
0x5C = 5 161 + 12 160 = 80 + 12 = 92
www.pragsoft.com
Chapter 1: Preliminaries
11
Real Numbers
A real variable may be defined to be of type float or double. The latter uses
more bytes and therefore offers a greater range and accuracy for representing
real numbers. For example, on the authors PC, a float uses 4 and a double
uses 8 bytes.
float
double
interestRate = 0.06;
pi = 3.141592654;
0.06f
3.141592654L
3.141592654l
In addition to the decimal notation used so far, literal reals may also be
expressed in scientific notation. For example, 0.002164 may be written in the
scientific notation as:
2.164E-3
or
2.164e-3
The letter E (or e) stands for exponent. The scientific notation is interpreted
as follows:
2.164E-3 = 2.164 10-3
12
C++ Programming
Characters
A character variable is defined to be of type char. A character variable
occupies a single byte which contains the code for the character. This code is a
numeric value and depends on the character coding system being used (i.e., is
machine-dependent). The most common system is ASCII (American Standard
Code for Information Interchange). For example, the character A has the
ASCII code 65, and the character a has the ASCII code 97.
char
ch = 'A';
offset = -88;
row = 2, column = 26;
//
//
//
//
//
//
new line
carriage return
horizontal tab
vertical tab
backspace
formfeed
Single and double quotes and the backslash character can also use the escape
notation:
'\''
'\"'
'\\'
Literal characters may also be specified using their numeric code value.
The general escape sequence \ooo (i.e., a backslash followed by up to three
octal digits) is used for this purpose. For example (assuming ASCII):
'\12'
'\11'
'\101'
'\0'
//
//
//
//
www.pragsoft.com
Chapter 1: Preliminaries
13
Strings
A string is a consecutive sequence (i.e., array) of characters which are
terminated by a null character. A string variable is defined to be of type
char* (i.e., a pointer to character). A pointer is simply the address of a
memory location. (Pointers will be discussed in Chapter 5). A string variable,
therefore, simply contains the address of where the first character of a string
appears. For example, consider the definition:
char
*str = "HELLO";
Figure 1.4 illustrates how the string variable str and the string "HELLO" might
appear in memory.
Figure 1.4 A string and a string variable in memory.
1207
1208
1209
1212
...
1210
1211
1212
1213
1214
1215
1216
1217
'H'
'E'
'L'
'L'
'O'
'\0'
1218
...
str
// tab-separated words
// 'A' specified as '101'
A long string may extend beyond a single line, in which case each of the
preceding lines should be terminated by a backslash. For example:
"Example to show \
the use of backslash for \
writing a long string"
The backslash in this context means that the rest of the string is continued on
the next line. The above string is equivalent to the single line string:
"Example to show the use of backslash for writing a long string"
14
C++ Programming
Names
Programming languages use names to refer to the various entities that make
up a program. We have already seen examples of an important category of
such names (i.e., variable names). Other categories include: function names,
type names, and macro names, which will be described later in this book.
Names are a programming convenience, which allow the programmer to
organize what would otherwise be quantities of plain data into a meaningful
and human-readable collection. As a result, no trace of a name is left in the
final executable code generated by a compiler. For example, a temperature
variable eventually becomes a few bytes of memory which is referred to by the
executable code by its address, not its name.
C++ imposes the following rules for creating valid names (also called
identifiers). A name should consist of one or more characters, each of which
may be a letter (i.e., 'A'-'Z' and 'a'-'z'), a digit (i.e., '0'-'9'), or an underscore
character ('_'), except that the first character may not be a digit. Upper and
lower case letters are distinct. For example:
salary
salary2
2salary
_salary
Salary
//
//
//
//
//
valid identifier
valid identifier
invalid identifier (begins with a digit)
valid identifier
valid but distinct from salary
C++ keywords.
asm
continue
float
new
signed
try
auto
default
for
operator
sizeof
typedef
break
delete
friend
private
static
union
case
do
goto
protected
struct
unsigned
catch
double
if
public
switch
virtual
char
else
inline
register
template
void
class
enum
int
return
this
volatile
const
extern
long
short
throw
while
www.pragsoft.com
Chapter 1: Preliminaries
15
Exercises
1.1
1.2
1.3
1.4
16
Age of a person.
Income of an employee.
A greeting message.
C++ Programming