15
8/19/2019 Introduccion al Lenguaje C++ (PARTE 1) http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 1/15 REPÚBLICA BOLIVARIANA DE VENEZUELA MINISTERIO DEL PODER POPULAR PARA LA EDUCACIÓN UNIVERSITARIA UNIVERSIDAD BOLIVARIANA DE VENEZUELA PROGRAMA DE FORMACIÓN DE GRADO EN  INFORMÁTICA PARA LA GESTIÓN SOCIAL MANUAL DE APOYO EN LA ELECTIVA INTEGRAL ESTRUCTURAS DINÁMICAS INTRODUCCION AL LENGUAJE C++ (PARTE 1) FUNDAMENTOS BÁSICOS CON RELACIÓN A SU SINTAXIS Y SEMÁNTICA VERSION 1. E!"#$%"&$ '$% P%$. J*" C"%!$, -%%%"

Introduccion al Lenguaje C++ (PARTE 1)

Embed Size (px)

Citation preview

Page 1: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 1/15

REPÚBLICA BOLIVARIANA DE VENEZUELAMINISTERIO DEL PODER POPULAR PARA LA EDUCACIÓN UNIVERSITARIA

UNIVERSIDAD BOLIVARIANA DE VENEZUELAPROGRAMA DE FORMACIÓN DE GRADO EN INFORMÁTICA PARA LA GESTIÓN SOCIAL

MANUAL DE APOYO EN LA ELECTIVA INTEGRAL ESTRUCTURAS DINÁMICASINTRODUCCION AL LENGUAJE C++ (PARTE 1)

FUNDAMENTOS BÁSICOS CON RELACIÓN A SU SINTAXIS Y SEMÁNTICA

VERSION 1.

E!"#$%"&$ '$% P%$. J*" C"%!$, -%%%"

Page 2: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 2/15

C"%"/",0 F#%%$ & 12

C++ For Artists: The Art, Philosophy, and Science of Object-Oriented Programming

by ic! "iller #$%%&'

 Another C++ Program

Example 5.2 gives the source code for another short C++ program. Although short, it has a little

more meat to it than the minimal program discussed above.

Listing 5.2: Another C++ Program

1 /************************************************ 2 Simple C++ Program 3 ************************************************/ 4

 5 #include <iostream> 6 

 7 using namespace std;8

 9 int main(){10 const int const_val !"";11 int i;12 i !";13

14 cout<<$%is is a simple C++ program&<<endl;15 cout<<$%e value o' i is <<i<<endl;16 cout<<$%e value o' const_val is <<const_val<<endl;17 

18 return ";19

Parts of the Program

Let us discuss example 5.2 line by line. he numbers ! through !" in italics to the left of the

listing are line numbers and are not part of the source code.

Comments

Line ! begins #ith the $% characters and is the start of a C&style comment. he comment proceeds

to the end of line ' #hich ends #ith the %$ characters. Everything appearing bet#een the $% and %$characters is ignored by the compiler. (f you #ere to disassemble this code the comments #ould

 be omitted.

Preprocessor Directive

Line 5 begins #ith the preprocessor directive )include and names a library header file called

iostream. he library header file named iostream is enclosed in the * character pair telling the preprocessor ho# it should conduct its search for the iostream file. (f you are using an older

2

Page 3: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 3/15

development environment you may have to use the filename iostream.h to access the iostream

library.

Libraries

Libraries, lie iostream, are code modules that implement some type of functionality and can beincorporated into your programs. o gain access to a library the compiler must no# #here to

find it and its header file must be included in the source code via an )include preprocessor

directive.

Using Directive

Line - contains a using directive indicating that the namespace std the standard namespace/ is being used. his is re0uired to gain access to various iostream ob1ects. ne iostream ob1ect, cout,

is being used on lines !3, !5, and !4 to send stream output to the standard output device. he

standard output device in this case is the computer screen.

main() function

Line " contains the start of the main/ function. he body of the main/ is comprised of

everything appearing bet#een the opening left brace at the end of line ", and closing right brace

6 on line !".

Constants

Line !7 declares an integer constant named const8val and defines its value as !77. A constant is

an ob1ect #hose value is to remain unchanged during its lifetime. he ey#ord const is also usedto prevent dumb programming mistaes or to enforce good program design.

Variables

Line !! declares an integer variable named i. n line !2 i is assigned the value !7. 9nlie a

constant, a variable is an ob1ect #hose value is allo#ed to change during its lifetime.

Statements and Expressions 

Lines !7 through !2, lines !3 through !4, and line !: each contain a statement. Line !2 is anexample of a statement that is also an expression.

Keywords

C++ programs, lie example 5&2, are constructed using certain identifiers that are reserved for use

 by the C++ compiler. hese reserved #ords are no#n as ey#ords. ;ou can name your

3

Page 4: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 4/15

variables and constants anything you lie so long as you avoid using ey#ord names. he

ey#ords are listed in the first four columns of the C++ ey#ord list belo#.

Fundamental Types

C++ comes #ith several built&in data types ready for immediate use. Each of the character,integer, and floating point types has a corresponding range of values they should represent. ( use

the #ord <should= because each compiler implementation can choose to increase the value range

of a particular type so long as they meet certain American >ational ?tandards (nstitute A>?(/re0uirements as specified in the C++ standard.

;our compiler defines its fundamental data type value ranges in the follo#ing header files@

climits.h, limits.h, and cfloat.h. he value ranges of each type is largely hard#are dependent. or

example, a '2&bit processor #ill have a smaller maximum long integer value than a 43&bit processor, assuming the compiler is eeping pace #ith the hard#are it is running on.

able 5&! gives the type value ranges for the Betro#ers Codearrior C++ compiler version 5.7.

 Table 5-1: Fundamental Tyes and their !alue "anges

Type "inim(m )al(e "a*im(m )al(e

 bool false 7/ true !/

signed char &!2: !2-

char &!2: !2-

unsigned char 7 255

#char8t 7 45,5'5

signed short int &'2,-4: '2,-4-

short int &'2,-4: '2,-4-

unsigned short int 7 45,5'5

signed int &2,!3-,3:',43: 2,!3-,3:',43-

int &2,!3-,3:',43: 2,!3-,3:',43-

#

Page 5: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 5/15

 Table 5-1: Fundamental Tyes and their !alue "anges

Type "inim(m )al(e "a*im(m )al(e

unsigned int 7 3,2"3,"4-,2"5

signed long int &2,!3-,3:',43: 2,!3-,3:',43-

long int &2,!3-,3:',43: 2,!3-,3:',43-

unsigned long int 7 3,2"3,"4-,2"5

signed long long int &",22','-2,7'4,:53,--5,:7: ",22','-2,7'4,:53,--5,:7-

long long int &",22','-2,7'4,:53,--5,:7: ",22','-2,7'4,:53,--5,:7-

unsigned long long int 7 !:,334,-33,7-',-7",55!,4!5

float !.!-53"e&':  '.372:2e+': 

double 272257-e&'7:  !.7-"-4"e+'7: 

long double 272257-e&'7:  !.7-"-4"e+'7: 

ote: hese ranges are valid for Betro#ers Codearrior C++ version 5.7 for Bacintosh. ;ourranges may loo similar or some#hat different for some of the larger types depending on your

compiler implementation.

Literals

;ou often need to represent data <literally= in your program. he follo#ing statement gives anexample@

int i ;

he integer value 25 is being assigned to the ne#ly declared integer variable named i. hen

numbers, characters, and strings of characters appear directly in source code, lie the 25 does in

this example, they are called literals. Dere, the value 25 is no#n as a decimal integer literal .

5

Page 6: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 6/15

Expressions

Expressions are built using operators and operands. he operators and operands in the expression

specify a computation from #hich a value may result. he follo#ing statement offers severalexamples@

(n this example, the t#o integer literals ' and 4 are the operands to the multiplication operator.

he resulting value from the multiplicative expression becomes one of the operands to the

assignment operator. he other operand is the integer variable named i #hich is declared in thesame statement.

Operators

Bost of the expressions listed in table 5&' involve the use of multiplicative, additive, relational,

conditional, and assignment operators. ;ou may already have a fundamental understanding ofho# these operators #or, especially the multiplicative, additive, and assignment. ( #ill discuss

these and a fe# others in this section. Any operator ( fail to discuss here #ill be introduced to you

later in the boo #hen you are ready to learn its use.

efore ( tal about each operator ( #ant to tal briefly about operator precedence.

perator Precedence

perators in C++ have a precedence associated #ith their use. able 5&3 lists C++ operators in

order of their precedence, from highest to lo#est, along #ith their associativity. he use of parentheses is covered in the next section. 9se them and you #ill have fe#er bugs in your code

and fe#er headaches.

 Table 5-#: C++ $erators% Pre&eden&e% and Asso&iati'ity

perator Fescription Associates

++ Gost&increment Left to right

&& Gost&decrement Left to right

/ unction call Left to right

(

Page 7: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 7/15

H I Array element Left to right

& Gointer to structure member Left to right

. ?tructure or union member Left to right

++ Gre&increment Jight to left

&& Gre&decrement Jight to left

K Logical > Jight to left

it#ise > Jight to left

& 9nary minus Jight to left

+ 9nary plus Jight to left

M Address Jight to left

% (ndirection Jight to left

siNeof ?iNe in bytes Jight to left

ne# Allocate program memory Left to right

delete Feallocate program memory Left to right

type/ ype cast includes all C++ castoperators/

Left to right

.% Gointer to member ob1ects/ Left to right

&% Gointer to member pointers/ Left to right

% Bultiply Left to right

$ Fivide Left to right

)

Page 8: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 8/15

O Bodulo or Jemainder Left to right

+ Add Left to right

& ?ubtract Left to right

** Left shift Left to right

Jight shift Left to right

* Less than Left to right

*P Less than or e0ual to Left to right

Qreater than Left to right

P Qreater than or e0ual to Left to right

PP E0ual to Left to right

KP >ot e0ual to Left to right

M it#ise A>F Left to right

R it#ise exclusive J Left to right

S it#ise J Left to right

MM Logical A>F Left to right

SS Logical J Left to right

T @ Conditional Jight to left

P Assignment Jight to left

%P, $P, OP, +P, &P

**P, P, MP, RP, SPCompound assignment Jight to Left

*

Page 9: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 9/15

, Comma Left to right

Identifers

(dentifiers are names given to various ob1ects in a program. ;ou have already seen several

identifiers declared and used in this chapterU they #ere given short names lie i, a, b, andrepresented simple data types. (dentifiers are also used to name functions, labels, and other user

defined data types. he C++ reserved ey#ords, listed in the Vey#ords section of this chapter,

are examples of identifiers you cannot use to name your ob1ects because they are reserved by thecompiler.

(dentifiers are formed using letters and digits, ho#ever, an identifier must start #ith a letter or

underscore <8= character. he follo#ing are valid identifiers@

count_count,_count_to_!"_-togetCount()printScreen().ael!

Constants

A constant is an ob1ect in your program that you intend to remain unchanged during its lifetime.

he use of constants can vastly improve the readability and maintainability of your code.

;ou can declare constants in C++ using the ey#ord const . Constants have to be defined at the

 point of declaration. he follo#ing statement gives an example of a constant declaration anddefinition@

const int 012_C345$ ;

here is an exception to the define&at&the&point&of&declaration rule, and that is #hen you aredeclaring constants for use in classes or structures. (n chapter !! ( #ill sho# you ho# to use

constructors to define class constant members.

nce you have defined the constant, any attempt to change its value #ill be met #ith disapproval

from the compiler.

Page 10: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 10/15

aria!les

A variable is an ob1ect #hose value #ill liely change during the execution of a program.

Wariables have a storage class, and a visibility or scope

Declaring

;ou have seen several variables declared and used in this chapter. ;ou precede the identifier #ith

the variableXs type as in the follo#ing example@

c%ar* '_name;

(n this case the type of the variable named f8name is pointer to char. DereXs another example@

'loat account_alance;

Wariables can be defined or initialiNed at the point of declaration or later if necessary. As a rule,though, it is a good idea to initialiNe the variable to some no#n value so you donXt try to use avariable that contains a garbage value. DereXs an example@

long de'unct_dot_coms ";666de'unct_dot_coms 778;

Dere the variable named defunct8dot8coms is declared and initialiNed to 7. ;ou can also initialiNea variable using <constructor= notation. Chec this out@

int cool_variale(8");

The main"# Fun$tion 

Every C++ program contains a main/ function. ;ou may #rite library routines that do not

contain a main function but the program that ultimately uses them #ill have a main/ function.

his section #ill briefly discuss the purpose of the main/ function and the t#o forms it can tae.

!he Purpose of the main() "unction

he main/ function mars the start of program execution. A program may be small and containonly a main/ function that itself only contains a fe# simple statements, or it may be huge and becomprised of many different ob1ects and stand&alone functions that are defined across thousands

of files and millions of lines of source code. hat ever form it taes, it all starts #ith main/.

1,

Page 11: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 11/15

Page 12: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 12/15

%imple Input and Output 

C++ provides character stream input and output in the form of the cin and cout ob1ects. ;ou have

already seen the stream insertion operator in use to send variable values and strings to the coutob1ect. By ob1ective in this boo is to limit the use of cin and cout to the absolute minimum

re0uired to facilitate program interaction. ( do this because there exist several good iostream boos on the maret that go into much greater detail than ( #ish to do so in this boo.

By second reason for limiting my coverage is that should you decide to specialiNe in a particularoperating system you #ill need to learn ho# to use the graphical user interface components lie

#indo#s, text boxes, text fields, etc., supported by that operating system.

cin

he iostream header file declares the cin ob1ect for your console stream input use. he cin ob1ect

taes input from the standard input device, #hich is usually the eyboard, and directs it to

designated variables. Example 5." sho#s the cin ob1ect being used to read in several integervalues and direct the input to the integer variables a, b, and c@

Listing 5.: sing &in $be&t to "ead/nteger !alues 0rom eyboard

1 #include <iostream> 2

 3 using namespace std; //introduces namespace std 4

 5 int main(){ 6 int a "9 "9 c "; 7 

 8 cout<<?nter values 'or a9 9 and c ; 9 cin>>a>>>>c;10 cout<<a<< <<<< <<c<<endl;11

12 return ";13

 >otice the #ay the Xs point #hen using the cin ob1ect vs. the cout ob1ect. he is called the

stream extraction operator and the ** is called the stream insertion operator.

!rapping $ad %nput

A problem arises #hen using the cin ob1ect to read input from the eyboard. (f you are expectinga certain type, say, an integer, but the user enters a character or string of characters, it causes the

extraction operation to fail and cinXs internal fail bit #ill be set. hat the user sees #hen this

happens is a screen scrolling #ildly out of controlU the program 1ust crashed.

A simple solution, until you learn more robust error trapping techni0ues, is to test for the successof the cin stream extraction. Example 5.!7 offers an example.

12

Page 13: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 13/15

amle 5.1,: Testing 0or !alid /nut

Example 5.!7 sho#s the cin ob1ect being tested for success or failure in the expression section of

a #hile loop. (f the extraction operation #as successful, #hich in most cases means the correcttype #as extracted from the input stream and stored in the designated variable, then the #hile

loop is sipped. (f the extraction operation failed then the body of the #hile loop is entered and

#ill loop until the extraction operation is a success.

cout

he cout ob1ect sends stream output to the standard output device, usually the screen. ;ou have

seen the cout ob1ect in action throughout this chapter. As noted above <**< is called the streaminsertion operator. (t is overloaded to properly handle all the native C++ types.

he most common mistae made #hen using the cout ob1ect is forgetting to put 0uotation mars

around strings, but practice maes perfect.

%ummary 

All C++ programs re0uire a main/ function and a minimum, #ell&formed C++ program may

have nothing but a main/ function, although it #ouldnXt be very useful. ;ou can learn a lot about

the language and the host computer by disassembling programs. he Betro#ers Codearrior

disassembler can be configured to display output in several different formats.

odos los programas en C + + re0uieren una funciZn main / y un m[nimo, bien formado

 programa en C ++ puede tener m\s 0ue una funciZn main /, aun0ue no ser[a muy ]til. ?e puede

aprender mucho sobre el lengua1e y la computadora host desensamblando programas. Eldesensamblador Betro#ers Codearrior se puede configurar para mostrar la salida en varios

formatos diferentes.

13

Page 14: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 14/15

Vey#ords are identifiers reserved for use by the compiler. ;ou build C++ programs from

declarations, statements, and expressions constructed from ey#ords, identifiers, fundamentaldata types, and operators.

Las palabras clave son identificadores reservados para su uso por el compilador. ?e pueden

construir programas en C + + mediante declaraciones, instrucciones y expresiones construidas a partir de palabras clave, identificadores, tipos de datos fundamentales, y operadores.

C++ contains several fundamental data types such as char, int, float, and double, etc.undamental data types can represent a certain range of values depending on their siNe. Learn the

siNe, in bytes, of data types by using the siNeof operator. Fetermine the range of data types by

using the numeric8limits template class.

C + + contiene varios tipos de datos fundamentales tales como char, int, float y double, etc. Lostipos de datos fundamentales pueden representar un cierto rango de valores en funciZn de su

tama^o. ConoNca el tama^o, en bytes, de los tipos de datos mediante el operador siNeof.

Fetermine el rango de los tipos de datos mediante el uso de la clase numeric8limits.

 >umbers, characters, and strings of characters that appear directly in programs are no#n as

literals. (nteger literals can be expressed in decimal, octal, or hexadecimal format. Bultiple

character literals have a value e0ual to the integer value of their bit representation. ?pecial

characters can be represented by escape se0uences. loating point literals have type double unlessspecified as float #ith the f or suffix. ?tring literals are terminated #ith the null character _`7X.

oolean literals true and false represent the values ! and 7.

Los n]meros, caracteres y cadenas de caracteres 0ue aparecen directamente en los programas se

conocen como literales. Los literales enteros pueden ser expresados en decimal, octal ohexadecimal. B]ltiples caracteres literales tienen un valor igual al valor entero de su

representaciZn de bits. Los caracteres especiales pueden ser representados por secuencias de

escape. Literales de punto flotante tienen tipo double al menos 0ue se especifi0ue como float conel sufi1o f o . Los literales de cadena se terminan con el car\cter nulo ` 7. Literales booleanos

true y false representan los valores ! y 7.

Expressions, constructed from operators, specify a computation from #hich a value may result.

perators have precedenceU use parenthesis to explicitly define operator precedence in anexpression and mae code easier to read and understand.

Las expresiones, construidas a partir de los operadores, especifican un cZmputo calculo/ de la

0ue puede dar lugar a un valor. Los operadores tienen prioridadU utilice parntesis para definir 

expl[citamente la precedencia de los operadores en una expresiZn y hacer 0ue el cZdigo m\s f\cilde leer y entender.

(dentifiers are names given to ob1ects in a programU adopt a naming convention and stic #ith it.

A constant is an ob1ect #hose value #ill remain unchanged during its lifetime. A constant must bedefined at the point of declaration except in class member constants #hich re0uire initialiNation

in the class constructor.  see chapter 11/

1#

Page 15: Introduccion al Lenguaje C++ (PARTE 1)

8/19/2019 Introduccion al Lenguaje C++ (PARTE 1)

http://slidepdf.com/reader/full/introduccion-al-lenguaje-c-parte-1 15/15

Los identificadores son los nombres dados a los ob1etos en un programa, adopte una convenciZn

de nomenclatura y aferrase a l. 9na constante es un ob1eto cuyo valor se mantendr\ sin cambiosdurante su vida ]til. 9na constante se debe definir en el punto de la declaraciZn, salvo en las

constantes de miembro de clase 0ue re0uieren inicialiNaciZn en el constructor de la clase. vase

el cap[tulo !!/.

A variableXs value #ill change during its lifetime. Wariables have an area of authoriNed usage#ithin a program no#n as scope. Jedeclaring a variable in an enclosed scope can mas or hide

a variable of the same name in outer or enclosing scopes. ile scope variables have external

linage by default. 9se the static ey#ord to limit file scope variable visibility to the file in

#hich it is declared.

El valor de una variable cambia durante su vida ]til. Las variables tienen un \rea de uso

autoriNada dentro de un programa conocido como \mbito de aplicaciZn. Jedeclarando una

variable en un \mbito cerrado puede enmascarar u ocultar una variable con el mismo nombre en\mbitos exteriores o envolventes. Wariables de \mbito de archivo tienen vinculaciZn externa por 

defecto. 9se la palabra clave static para limitar el \mbito de visibilidad de la variable al archivoen el 0ue se declara.

he main/ function taes t#o forms. he cstdlib header defines the constants EY(8?9CCE??and EY(8A(L9JE for use in the return statement or exit/ function. 9se atexit/ function to

call a function of your choosing upon exiting a program.

La funciZn main / toma dos formas. El encabeNado cstdlib define las constantes

EY(8?9CCE?? y EY(8A(L9JE para su uso en la instrucciZn return o funciZn exit /.9tilice la funciZn atexit / para llamar a una funciZn de su elecciZn al salir de un programa.

?tream input and output is provided by the cin and cout ob1ects.

Entrada y salida de flu1o de datos es proporcionada por los ob1etos cin y cout.

15