Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Ministerio de Educación Superior

Universidad de Guantánamo

Clase encuentro .1 Introducción al lenguaje c++


Profesor: Ing. Yenis Moro Durán. Instructor

Tema no.2 Elementos básicos de la programación en C++

CONTENIDOS

2.1. El lenguaje c++. Primer programa en c++ .Imprimir una línea de texto

2.2. Los datos. Sus tipos.

2.3. Identificadores, constantes y variables

2.4. Operadores y expresiones.

2.4.1 Expresiones

2.4.2. Operadores aritméticos

2.4.3 Operadores relacionales

2.4.4 Operadores de incremento y decremento

2.4.5 Operadores lógicos

2.5. Tipos de datos elementales

2.5.1 . Números enteros

C y c++ proporciona los siguientes tipos de datos elementales:

 números enteros,
 caracteres, y
 números de coma flotante (reales).

2.5.2. Modificadores

2.5.3 Caracteres

2.5.4 . Caracteres especiales


Introducción.

Conceptos:

Informática,Operadores lógicos,datos, programa de computadora, instrucciones,algortimo

2.1. El lenguaje c++

C++ es un lenguaje fuertemente tipado

Primer programa en c++. Imprimir una línea de texto

Consider a simple program that prints a line of text (Fig. 2.1). This program illustrates several
important features of the C++ language. The text in lines 1–10 is the program’s source code (or
code). The line numbers are not part of the source code.

Comments Lines 1 and 2

// Fig. 2.1: fig02_01.cpp

// Text-printing program.

each begin with //, indicating that the remainder of each line is a comment. You insert
comments to document your programs and to help other people read and understand them.
Comments do not cause the computer to perform any action when the program is run—
they’re ignored by the C++ compiler and do not cause any machine-language object code to be
generated. The comment Text-printing program describes the purpose of the program. A
comment beginning with // is called a single-line comment because it terminates at the end of
the current line. You also may use comments containing one or more lines enclosed in /* and
*/, as in
/* Fig. 2.1: fig02_01.cpp Text-printing program. */

#include Preprocessing Directive Line 3

#include <iostream> // enables program to output data to the screen

is a preprocessing directive, which is a message to the C++ preprocessor (introduced in Section


1.9). Lines that begin with # are processed by the preprocessor before the program is
compiled. This line notifies the preprocessor to include in the program the contents of the
input/output stream header <iostream>. This header is a file containing information the
compiler uses when compiling any program that outputs data to the screen or inputs data
from the keyboard using C++’s stream input/output.

La función principal de c++. Línea 5

// function main begins program execution

is a single-line comment indicating that program execution begins at the next line.

int main() {

is a part of every C++ program. The parentheses after main indicate that main is a program
building block called a function. C++ programs typically consist of one or more functions and
classes .Exactly one function in every program must be named main. Figure 2.1 contains only
one function. C++ programs begin executing at function main, even if main is not the first
function defined in the program. The keyword int to the left of main indicates that main
“returns” an integer (whole number) value. A keyword is a word in code that is reserved by C+
+ for a specific use. The complete list of C++ keywords can be found in Fig. 4.3. We’ll explain
what it means for a function to “return a value” when we demonstrate how to create your
own functions in Section 3.3. For now, simply include the keyword int to the left of main in
each of your programs. The left brace, {, (end of line 6) must begin the body of every function.
A corresponding right brace, }, (line 10) must end each function’s body.

An Output Statement

std::cout << "Welcome to C++!\n"; // display message

instructs the computer to perform an action—namely, to print the characters contained


between the double quotation marks. Together, the quotation marks and the characters
between them are called a string, a character string or a string literal. In this book, we refer to
characters between double quotation marks simply as strings. White-space characters in
strings are not ignored by the compiler. The entire line 7, including std::cout, the << operator,
the string "Welcome to C++!\n" and the semicolon (;), is called a statement. Most C++
statements end with a semicolon, also known as the statement terminator (we’ll see some
exceptions to this soon). Preprocessing directives (such as #include) do not end with a
semicolon. Typically, output and input in C++ are accomplished with streams of data. Thus,
when the preceding statement is executed, it sends the stream of characters Welcome to C+
+!\n to the standard output stream object—std::cout—which is normally “connected” to the
screen.

The std Namespace

The std:: before cout is required when we use names that we’ve brought into the program by
the preprocessing directive #include <iostream>. The notation std::cout specifies that we are
using a name, in this case cout, that belongs to namespace std. The names cin (the standard
input stream) and cerr (the standard error stream)—introduced in Chapter 1—also belong to
namespace std. Namespaces are an advanced C++ feature that we discuss in depth in Chapter
23, Other Topics. For now, you should simply remember to include std:: before each mention
of cout, cin and cerr in a program. This can be cumbersome—we’ll soon introduce using
declarations and the using directive, which will enable you to omit std:: before each use of a
name in the std namespace.

The Stream Insertion Operator and Escape Sequences


In the context of an output statement, the << operator is referred to as the stream insertion
operator. When this program executes, the value to the operator’s right, the right operand, is
inserted in the output stream. Notice that the << operator points toward where the data goes.
A string literal’s characters normally print exactly as they appear between the double quotes.
However, the characters \n are not printed on the screen (Fig. 2.1). The backslash (\) is called
an escape character. It indicates that a “special” character is to be output. When a backslash is
encountered in a string of characters, the next character is combined with the backslash to
form an escape sequence. The escape sequence \n means newline. It causes the cursor (i.e.,
the current screen-position indicator) to move to the beginning of the next line on the screen.
Some common escape sequences are listed in Fig. 2.2.

The return Statement


return 0; // indicate that program ended successfully

is one of several means we’ll use to exit a function. When the return statement is used at the
end of main, as shown here, the value 0 indicates that the program has terminated
successfully. The right brace, }, (line 10) indicates the end of function main. According to the C+
+ standard, if program execution reaches the end of main without encountering a return
statement, it’s assumed that the program terminated successfully—exactly as when the last
statement in main is a return statement with the value 0. For that reason, we omit the return
statement at the end of main in subsequent programs.

Modificando nuestro primer programa

Otro ejemplo de programa. Sumando dos enteros.

Our next program obtains two integers typed by a user at the keyboard, computes their sum
and outputs the result using std::cout. Figure 2.5 shows the program and sample inputs and
outputs. In the sample execution, we highlight the user’s input in bold. The program begins
execution with function main (line 6). The left brace (line 6) begins main’s body and the
corresponding right brace (line 21) ends it.
Variables. Declaración. Inicialización

The identifiers number1, number2 and sum are the names of variables. A variable is a location
in the computer’s memory where a value can be stored for use by a program. These
declarations specify that the variables number1, number2 and sum are data of type int,
meaning that these variables will hold integer (whole number) values, such as 7, –11, 0 and
31914. Lines 8–10 also initialize each variable to 0 by placing a value in braces ({ and })
immediately following the variable’s name—this is known as list initialization,1 which was
introduced in C++11. Previously, these declarations would have been written as:

int number1 = 0; // first integer to add (initialized to 0)

int number2 = 0; // second integer to add (initialized to 0)

int sum = 0; // sum of number1 and number2 (initialized to 0)

All variables must be declared with a name and a data type before they can be used in a
program. Several variables of the same type may be declared in one declaration—for example,
we could have declared and initialized all three variables in one declaration by using a comma-
separated list as follows:

int number1{0}, number2{0}, sum{0};


This makes the program less readable and prevents us from providing comments that describe
each variable’s purpose.

Tipos fundamentales de datos

We’ll soon discuss the type double for specifying real numbers and the type char for specifying
character data. Real numbers are numbers with decimal points, such as 3.4, 0.0 and –11.19. A
char variable may hold only a single lowercase letter, uppercase letter, digit or special
character (e.g., $ or *). Types such as int, double and char are called fundamental types.
Fundamental-type names consist of one or more keywords and therefore must appear in all
lowercase letters. Appendix C contains the complete list of fundamental types.

Identifiers

A variable name (such as number1) is any valid identifier that is not a keyword. An identifier is
a series of characters consisting of letters, digits and underscores ( _ ) that does not begin with
a digit. C++ is case sensitive—uppercase and lowercase letters are different, so a1 and A1 are
different identifiers.

Obtaining the First Value from the User Line 12

std::cout << "Enter first integer: "; // prompt user for data

displays Enter first integer: followed by a space. This message is called a prompt because it
directs the user to take a specific action. We like to pronounce the preceding statement as
“std::cout gets the string "Enter first integer: ".” Line 13

std::cin >> number1; // read first integer from user into number1

uses the standard input stream object cin (of namespace std) and the stream extraction
operator, >>, to obtain a value from the keyboard. Using the stream extraction operator with
std::cin takes character input from the standard input stream, which is usually the keyboard.
We like to pronounce the preceding statement as, “std::cin gives a value to number1” or
simply “std::cin gives number1.” When the computer executes the preceding statement, it
waits for the user to enter a value for variable number1. The user responds by typing an
integer (as characters), then pressing the Enter key (sometimes called the Return key) to send
the characters to the computer. The computer converts the character representation of the
number to an integer and assigns (i.e., copies) this number (or value) to the variable number1.
Any subsequent references to number1 in this program will use this same value. Pressing Enter
also causes the cursor to move to the beginning of the next line on the screen. Users can, of
course, enter invalid data from the keyboard. For example, when your program is expecting
the user to enter an integer, the user could enter alphabetic characters, special symbols (like #
or @) or a number with a decimal point (like 73.5), among others. In these early programs, we
assume that the user enters valid data. As you progress through the book, you’ll learn how to
deal with data-entry problems.
Calculating the Sum of the Values Input by the User

sum = number1 + number2; // add the numbers; store result in sum

adds the values of variables number1 and number2 and assigns the result to variable sum
using the assignment operator =. We like to read this statement as, “sum gets the value of
number1 + number2.” Most calculations are performed in assignment statements. The =
operator and the + operator are called binary operators because each has two operands. In the
case of the + operator, the two operands are number1 and number2. In the case of the
preceding = operator, the two operands are sum and the value of the expression number1 +
number2.

Displaying the Result

std::cout << "Sum is " << sum << std::endl; // display sum; end line

displays the character string Sum is followed by the numerical value of variable sum followed
by std::endl—a so-called stream manipulator. The name endl is an abbreviation for “end line”
and belongs to namespace std. The std::endl stream manipulator outputs a newline, then
“flushes the output buffer.” This simply means that, on some systems where outputs
accumulate in the machine until there are enough to “make it worthwhile” to display them on
the screen, std::endl forces any accumulated outputs to be displayed at that moment. This can
be important when the outputs are prompting the user for an action, such as entering data.

The preceding statement outputs multiple values of different types. The stream insertion
operator “knows” how to output each type of data. Using multiple stream insertion operators
(<<) in a single statement is referred to as concatenating, chaining or cascading stream
insertion operations.

Calculations can also be performed in output statements. We could have combined the
statements in lines 18 and 20 into the statement

std::cout << "Sum is " << number1 + number2 << std::endl;

thus eliminating the need for the variable sum. A powerful feature of C++ is that you can
create your own data types called classes (we discuss this capability in Chapter 3 and explore it
in depth in Chapter 9). You can then “teach” C++ how to input and output values of these new
data types using the >> and << operators (this is called operator overloading.

Conceptos de memoria

Variable names such as number1, number2 and sum actually correspond to locations in the
computer’s memory. Every variable has a name, a type, a size and a value. In the addition
program of Fig. 2.5, when the statement in line 13

std::cin >> number1; // read first integer from user into number1

is executed, the integer typed by the user is placed into a memory location to which the name
number1 has been assigned by the compiler. Suppose the user enters 45 for number1. The
computer will place 45 into the location number1, as shown in Fig. 2.6. When a value is placed
in a memory location, the value overwrites the previous value in that location; thus, placing a
new value into a memory location is said to be a destructive operation.
Returning to our addition program, suppose the user enters 72 when the statement

std::cin >> number2; // read second integer from user into number2

is executed. This value is placed into the location number2, and memory appears as in Fig. 2.7.
The variables’ locations are not necessarily adjacent in memory.

Once the program has obtained values for number1 and number2, it adds these values and
places the total into the variable sum. The statement

sum = number1 + number2; // add the numbers; store result in sum

replaces whatever value was stored in sum. The calculated sum of number1 and number2 is
placed into variable sum without regard to what value may already be in sum—that value is
lost. After sum is calculated, memory appears as in Fig. 2.8. The values of number1 and
number2 appear exactly as they did before the calculation. These values were used, but not
destroyed, as the computer performed the calculation. Thus, when a value is read out of a
memory location, the operation is nondestructive.

2.2 Los datos. Sus tipos

Los programas de ordenador realizan operaciones con distintos tipos de datos. Un tipo de
datos es el conjunto de valores que puede tomar una constante, variable o expresión. Una de
las características más importantes e interesantes del lenguaje Pascal es la capacidad que tiene
para admitir muchos tipos diferentes de datos. A continuación se presenta un resumen de los
distintos tipos de datos.

Los tipos de datos en C++ se clasifican en primitivos y derivados.

Los tipos de datos primitivos son los que están definidos dentro
del lenguaje.

Los tipos de datos derivados se forman a partir de los tipos


primitivos.
En este tema veremos los tipos primitivos y en temas siguientes
estudiaremos los tipos derivados.

Los tipos de datos primitivos en C++ son: numéricos enteros,


numéricos reales, tipo lógico y tipo carácter ampliado.
Tipos de datos C++ numéricos enteros

El tipo de dato numérico entero es un subconjunto finito de los


números enteros del mundo real. Pueden ser positivos o negativos.
En C++ los tipos de datos numéricos enteros son los siguientes:

Con los tipos enteros pueden utilizarse los calificadores signed y


unsigned. Estos calificadores indican si el número tiene signo o no.
Si se usan solos, sin indicar el tipo de dato se asume int.
Por ejemplo, las siguientes declaraciones son equivalentes:
unsigned int x; equivale a: unsigned x;

Usando estos calificadores podemos tener los siguientes tipos enteros:

Podemos ver que los datos enteros de tipo signed son equivalentes a
los enteros sin utilizar el calificador:
signed int a; es equivalente a escribir int a;
Tipos de datos numéricos reales

DATOS ESTATICOS

(1) Datos de tipo simple


(I) Tipos de datos predefinidos o estándar:
a) INTEGER (entero)
b) FLOAT (decimal)
c) CHAR (literal o carácter)
d) BOOLEAN (lógico o booleano)

(II) Tipos de dato definidos por el usuario:

(2) Datos de tipo estructurado


(I) ARRAY (Matrices)
(II) STRUCT (Registros)
(III) UNION (Conjuntos)

• DATOS DINAMICO

Se almacenan en estructuras dinámicas de datos (listas, pilas, colas, árboles, grafos,...)


realizadas con punteros. En estas estructuras, los elementos se van creando y eliminando en
tiempo de ejecución, por tanto, la memoria ocupada por datos dinámicos es gestionada en
tiempo de ejecución a diferencia de los datos estáticos cuya memoria se gestiona en tiempo de
compilación. Las estructuras dinámicas de datos serán estudiadas en profundidad el segundo
año de la carrera, en la asignatura Estructura de datos.

TIPOS ABSTRACTOS DE DATOS

Son un modelo matemático sobre el cual se pueden efectuar diversas operaciones definidas
por el programador. Es decir, operaciones definidas por una estructura de datos y procesos

que pueden utilizar esas operaciones de forma coordinada para que no interfieran entre sí.
Esto facilita la abstracción, la ocultación y el encapsulamiento de datos

Orientación del seminario No.1.

1. Tipos de datos en el lenguaje c++. Profundizar en los tipos de datos mencionados en la


conferencia: datos simples, datos predefinidos, datos definidos por el usuario, datos
estructurados, datos dinámicos. Cadena de caracteres y datos booleanos.
2.3. IDENTIFICADORES, CONSTANTES Y VARIABLES

Identificador:

Un identificador es un nombre dado a un elemento de un programa (nombre de una variable,


una constante, ...). Los identificadores están formados por letras o dígitos en cualquier orden,
pero el primer carácter debe ser una letra como se verá más adelante. Se permiten tanto letras
mayúsculas como minúsculas, que se consideran indistinguibles. Aprovechando esta
posibilidad, existen unas normas para la escritura de los diferentes identificadores que, aunque
no son obligatorias, son aceptadas por la mayoría de los programadores puesto que facilitan la
lectura de los programas, y serán aplicadas a lo largo de este texto.

Notación EBNF (Extended Backus Naur Form)

Metalenguaje

Son herramientas útiles para la descripción formal de la sintaxis de un lenguaje de


programación, facilitando así la comprensión del mismo. Se estudiarán dos tipos: los
diagramas sintácticos y lanotación EBNF (Extended Backus Naur Form).

Diagramas Sintácticos

Constan de una serie de cajas o símbolos geométricos conectados por flechas donde se
introducen los símbolos del lenguaje que se dividen en:

• Símbolos terminales : Son los que forman las sentencias del lenguaje y se introducen dentro
de círculos o cajas de bordes redondeados.

• Símbolos no terminales: Son introducidos como elementos auxiliares y no figuran en las


sentencias del lenguaje. Se representan por su nombre encerrado en un rectángulo o
cuadrado.

Utiliza los siguientes metasímbolos:

< > encierra conceptos definidos o por definir. Se utiliza para los símbolos no terminales.

::= sirve para definir o indicar equivalencia.

| separa las distintas alternativas.

{ } indica que lo que aparece entre llaves puede repetirse cero o más veces. En algunos casos
se indica con subíndices y superíndices el intervalo de repeticiones.

" " indica que el metasímbolo quea parece entrecomillas es un carácter que forma parte de la
sintaxis del lenguaje.

( ) se permite el uso de paréntesis para hacer agrupaciones.

Notación EBNF y el diagrama sintáctico de un IDENTIFICADOR.

<identificador> ::= <letra> { <alfanumérico> }


<alfanumérico> ::= <letra>|<dígito> <letra> ::= a|b|c|...|y|z|A|B|...|Y|Z

<dígito> ::= 0|1|2|...|8|9

Los datos se almacenan en la memoria del ordenador. La memoria del ordenador puede
representarse como un gran casillero donde se almacenan los datos. Evidentemente las casillas
no son iguales pues cada tipo de dato ocupa distinta memoria. Cada una delas casillas está
localizada por su posición. Los programadores en lenguaje máquina indican estas posiciones
con un código, por ejemplo, de la forma 1011100110 . Los lenguajes de alto nivel ofrecen la
posibilidad de usar identificadores para señalar la posición de memoria que ocupan los datos.

Los identificadores pueden ser nombres de variables o de constantes, es decir, pueden indicar
localizaciones de memoria cuyo valor puede cambiarse o debe de permanecer constante.

Variable es un identificador cuyo valor puede cambiar a lo largo de la ejecución de un


programa.

Constante es un identificador cuyo valor no puede variar a lo largo del programa.

Podemos decir que un programa está compuesto por distintos bloques, uno de los cuales será
el principal y que contendrá el procedimiento que será llamado al comenzar la ejecución del
programa. Serán bloques el interior de las funciones, el interior de las estructuras de control,
etc.

Diremos que el campo o ámbito de un identificador es el bloque en el que ha sido definido. Si


el bloque contiene otros bloques también en estos el identificador será válido. Cuando hablo
de identificador me refiero a su sentido más amplio: variables, constantes, funciones, tipos,
etc. Fuera del ámbito de su definición ningún identificador tiene validez.

Clasificaremos las variables en función de su ámbito de definición en globales y locales. Dentro


de un bloque una variable es local si ha sido definida en el interior del mismo, y es global si se
ha definido fuera del bloque pero podemos acceder a ella.

Como es lógico las variables ocupan memoria pero, como sólo son necesarias en el interior de
los bloques donde se definen, durante la ejecución del programa serán creadas al entrar en su
ámbito y eliminadas al salir de él. Así, habrá variables que existirán durante todo el programa
(si son globales para todos los bloques) y otras que sólo existan en momentos muy concretos.
Este mecanismo de creación y destrucción de variables permite que los programas aprovechen
al máximo la memoria que les ha sido asignada.

Todo lo dicho anteriormente es válido para las variables declaradas estáticamente, pero existe
otro tipo de variables cuya existencia es controlada por el programador, las denominadas
variables dinámicas. Ya hablamos anteriormente de los punteros y dijimos entonces que eran
las variables empleadas para apuntar a otras variables, pero ¿a qué nos referimos con
apuntar? Sabemos que las variables se almacenan en memoria, luego habrá alguna dirección
de memoria en la que encontremos su valor (que puede ocupar uno o varios bytes). Los
punteros no son más que variables cuyo contenido es una dirección de memoria, que puede
ser la de la posición del valor de otra variable.
Cuando deseamos crear variables de tipo dinámico el lenguaje de programación nos suele
proporcionar alguna función estándar para reclamarle al S.O. espacio de memoria para
almacenar datos, pero como no hemos definido variables que denoten a ese espacio,
tendremos que trabajar con punteros. Es importante señalar que el espacio reservado de esta
forma se considera ocupado durante todo el tiempo que se ejecuta el programa, a menos que
el programador lo libere explícitamente, pero los punteros que contienen la dirección de ese
espacio si son variables estáticas, luego dejan de existir al salir de un campo. Si salimos de un
campo y no hemos liberado la memoria dinámica, no podremos acceder a ella (a menos que
alguno de los punteros fuera global al ámbito abandonado), pero estaremos ocupando un
espacio que no será utilizable hasta que termine nuestro programa.

2.4.2. Operadores aritméticos

La TABLA 1 , comprende las cuatro operaciones básicas , suma , resta , multiplicación y división
, con un agregado , el operador módulo .

El operador módulo ( % ) se utiliza para calcular el resto del cociente entre dos ENTEROS , y NO
puede ser aplicado a variables del tipo float ó double . Si bien la precedencia (orden en el que
son ejecutados los operadores) se analizará más adelante, en esta temática, podemos
adelantar algo sobre el orden que se realizan las operaciones aritméticas. En la TABLA 1, última
columna, se da el orden de evaluación de un operador dado. Cuanto más bajo sea dicho
número mayor será su prioridad de ejecución.

Si en una operación existen varios operadores, primero se evaluarán los de multiplicación,


división y módulo y luego los de suma y resta. La precedencia de los tres primeros es la misma,
por lo que si hay varios de ellos, se comenzará a evaluar a aquel que quede más a la izquierda.
Lo mismo ocurre con la suma y la resta. Para evitar errores en los cálculos se pueden usar
paréntesis, sin limitación de anidamiento, los que fuerzan a realizar primero las operaciones
incluidas en ellos.

Los paréntesis no disminuyen la velocidad a la que se ejecuta el programa sino que tan sólo
obligan al compilador a realizar las operaciones en un orden dado, por lo que es una buena
costumbre utilizarlos ampliamente. Los paréntesis tienen un orden de precedencia 0, es decir
que antes que nada se evalúa lo que ellos encierran.
Se puede observar que no existen operadores de potenciación, radicación, logaritmación, etc,
ya que en el lenguaje C++ todas estas operaciones ( y muchas otras ) se realizan por medio de
llamadas a Funciones. El último de los operadores aritméticos es el de SIGNO. No debe
confundirse con el de resta, ya que este es un operador unitario que opera sobre una única
variable cambiando el signo de su contenido numérico. Obviamente no existe el operador +
unitario, ya que su operación sería DEJAR el signo de la variable, lo que se consigue
simplemente por omisión del signo.

2.4.3 Operadores relacionales

Los operadores relacionales se utilizan principalmente para elaborar condiciones en las


sentencias condicionales e iterativas.

Es interesante destacar que a diferencia de otros lenguajes de programación c y c++ no


disponen de un tipo de dato especial para los valores lógicos booleanos. En su lugar, c y c++
representa un “falso” como el valor numérico cero, y un resultado “Cierto” como cualquier
valor diferente de cero.

2.4.5 Operadores lógicos

En c++ una expresión es verdadera si devuelve un valor distinto de cero, y falso en caso
contrario.Por lo tanto, el resultado de una operación lógica (AND, OR, NOT) será un valor
verdadero (1) o falso (0).

Ejemplo de código de trabajo (operadores lógicos )


2.5.1 . Números enteros

You might also like