17.05.2013 Views

1 Estructura básica de un programa C++

1 Estructura básica de un programa C++

1 Estructura básica de un programa C++

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Elementos básicos <strong>de</strong> <strong>un</strong> lenguaje <strong>de</strong> alto nivel: <strong>C++</strong><br />

CONTENIDOS<br />

1. <strong>Estructura</strong> <strong>básica</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong>.<br />

2. Tipos <strong>de</strong> datos simples.<br />

3. Constantes y variables en <strong>C++</strong>. Declaración.<br />

4. Operadores y expresiones.<br />

5. Instrucciones <strong>de</strong> Entrada y Salida.<br />

Alg<strong>un</strong>as características <strong>de</strong> <strong>C++</strong>.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 1<br />

1<br />

<strong>Estructura</strong> <strong>básica</strong><br />

<strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 2


<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Componente<br />

estructural<br />

básico: la f<strong>un</strong>ción<br />

F<strong>un</strong>ciones<br />

Una <strong>de</strong> las<br />

f<strong>un</strong>ciones ha <strong>de</strong> ser<br />

main<br />

Directivas <strong>de</strong> preprocesador<br />

Declaraciones globales ( varaibles globales, f<strong>un</strong>ciones, …)<br />

f<strong>un</strong>ción main()<br />

{<br />

secuencia <strong>de</strong> <strong>de</strong>claraciones e instrucciones<br />

}<br />

f<strong>un</strong>ción1()<br />

{<br />

secuencia <strong>de</strong> <strong>de</strong>claraciones e instrucciones<br />

}<br />

...<br />

f<strong>un</strong>ciónN()<br />

{<br />

secuencia <strong>de</strong> <strong>de</strong>claraciones e instrucciones<br />

}<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 3<br />

<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Un ejemplo sencillo <strong>de</strong> <strong>un</strong> <strong>programa</strong> que intercambia el valor <strong>de</strong> 2 números:<br />

Directiva <strong>de</strong> preprocesamiento Biblioteca <strong>de</strong> E/S por consola<br />

Este <strong>programa</strong> usa la <strong>de</strong>finición <strong>de</strong><br />

cout para escribir por consola<br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

int x, y;<br />

int aux;<br />

cin >> x >> y;<br />

aux = x;<br />

x = y;<br />

y = aux;<br />

cout


<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Un ejemplo sencillo <strong>de</strong> <strong>un</strong> <strong>programa</strong> que intercambia el valor <strong>de</strong> 2 números:<br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

int x, y;<br />

int aux;<br />

}<br />

cin >> x >> y;<br />

aux = x;<br />

x = y;<br />

y = aux;<br />

cout


<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Directivas <strong>de</strong>l preprocesador<br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

cout


<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

La f<strong>un</strong>ción main()<br />

Una f<strong>un</strong>ción <strong>C++</strong> es <strong>un</strong> sub<strong>programa</strong> que <strong>de</strong>vuelve <strong>un</strong> valor, <strong>un</strong> conj<strong>un</strong>to<br />

<strong>de</strong> valores o realiza <strong>un</strong>a tarea específica.<br />

Todo <strong>programa</strong> <strong>C++</strong> tiene <strong>un</strong>a única f<strong>un</strong>ción main() que es el p<strong>un</strong>to<br />

inicial <strong>de</strong> entrada al <strong>programa</strong>.<br />

Las sentencias escritas entre las<br />

llaves se <strong>de</strong>nomina BLOQUE<br />

#inclu<strong>de</strong> <br />

main()<br />

{<br />

…<br />

...<br />

}<br />

Si se intenta <strong>de</strong>clarar dos f<strong>un</strong>ciones<br />

Llamadas a<br />

otras f<strong>un</strong>ciones<br />

main() <strong>de</strong>ntro <strong>de</strong>l <strong>programa</strong> se produce error.<br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

entrada_datos();<br />

proceso_datos();<br />

return 0;<br />

...<br />

}<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 9<br />

<strong>Estructura</strong> <strong>de</strong> <strong>un</strong> <strong>programa</strong> <strong>C++</strong><br />

Comentarios<br />

Un comentario es cualquier información que se escribe el en <strong>programa</strong><br />

para proporcionar información <strong>de</strong> cualquier tipo.<br />

#inclu<strong>de</strong> <br />

/* po<strong>de</strong>mos hacer<br />

comentarios que ocupen<br />

varias líneas */<br />

int main()<br />

{<br />

int x, y;<br />

int aux; // éste es <strong>un</strong> comentario <strong>de</strong> <strong>un</strong>a sola línea<br />

cin >> x >> y;<br />

...<br />

return 0;<br />

}<br />

Po<strong>de</strong>mos escribir los<br />

comentarios <strong>de</strong> dos<br />

formas diferentes<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 10


2<br />

Tipos <strong>de</strong> datos simples<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 11<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

El tipo <strong>de</strong> dato <strong>de</strong>termina la naturaleza <strong>de</strong>l valor que pue<strong>de</strong> tomar <strong>un</strong>a<br />

variable.Un tipo <strong>de</strong> dato <strong>de</strong>fine <strong>un</strong> dominio <strong>de</strong> valores y las operaciones<br />

que se pue<strong>de</strong>n realizar con éstos valores.<br />

<strong>C++</strong> dispone <strong>de</strong> <strong>un</strong>os cuantos tipos <strong>de</strong> datos pre<strong>de</strong>finidos (simples) y permite<br />

al <strong>programa</strong>dor crear otros tipos <strong>de</strong> datos<br />

Tipo <strong>de</strong> datos básicos<br />

• int ( Números enteros )<br />

• float ( Números reales )<br />

• double ( Números reales más gran<strong>de</strong>s que float )<br />

• bool ( Valores lógicos )<br />

• char ( Caracteres y cualquier cantidad <strong>de</strong> 8 bits )<br />

• void ( Nada. Sirve para indicar que <strong>un</strong>a fonción no <strong>de</strong>vuelve valores )<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 12


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tipo int<br />

Tamaño en bytes: 2 bytes (16 bits)<br />

Dominio: son todos los números enteros entre los valores<br />

-32.768 y 32.767<br />

Operaciones:<br />

+ Suma<br />

int × int → int<br />

- Resta<br />

* Producto<br />

/ División entera<br />

% Resto <strong>de</strong> la división entera<br />

(módulo)<br />

- , + Signo negativo, positivo<br />

++ Incrementación<br />

-- Decrementación int → int<br />

Números enteros<br />

Prioridad <strong>de</strong> los<br />

operadores:<br />

++, - - 10*5++<br />

- , + (<strong>un</strong>ario) -3<br />

* , /, % 3*5<br />

+, - 6+7<br />

10×6<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 13<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Operadores <strong>de</strong> incrementación y <strong>de</strong>crementación<br />

Son equivalentes<br />

m = m + 1;<br />

m++;<br />

++m;<br />

Se trata <strong>de</strong> los operadores: ++ - -<br />

x = 10;<br />

y = x++; // y vale 10<br />

Suma <strong>un</strong>a <strong>un</strong>idad<br />

a su argumento<br />

Resta <strong>un</strong>a <strong>un</strong>idad<br />

a su argumento<br />

Si prece<strong>de</strong> al operando, se realiza la operación ++<br />

o -- y luego se realiza la asignación.<br />

x = 10;<br />

y = ++x; // y vale 11<br />

Si sigue al operando, se realiza la asignación y<br />

posteriormente se realiza la operación ++ o --<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 14


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tipo float<br />

Tamaño en bytes: 4 bytes<br />

Dominio: son todos los números reales que contienen <strong>un</strong>a coma <strong>de</strong>cimal<br />

comprendidos entre los valores:<br />

Operaciones:<br />

3,4 × 10 -38 y 3,4 × 10 38<br />

+ Suma<br />

float × float → float<br />

- Resta<br />

* Producto<br />

/ División en coma flotante<br />

- , + Signo negativo, positivo<br />

++ Incrementación<br />

-- Decrementación float → float<br />

Números reales<br />

La prioridad <strong>de</strong> los<br />

operadores es la misma<br />

que para el tipo int<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 15<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tipo double<br />

Tamaño en bytes: 8 bytes<br />

Números reales<br />

Dominio: son todos los números reales que contienen <strong>un</strong>a coma <strong>de</strong>cimal<br />

comprendidos entre los valores:<br />

Operaciones:<br />

1,7 × 10 -308 y 1,7 × 10 308<br />

+ Suma<br />

double × double → double<br />

- Resta<br />

* Producto<br />

/ División en coma flotante<br />

- , + Signo negativo, positivo<br />

++ Incrementación<br />

-- Decrementación double → double<br />

Igual que float pero más gran<strong>de</strong>s<br />

La prioridad <strong>de</strong> los<br />

operadores es la misma<br />

que para el tipo int<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 16


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

A<strong>de</strong>más <strong>de</strong> éstas operaciones, <strong>C++</strong> dispone <strong>de</strong> <strong>un</strong> gran conj<strong>un</strong>to <strong>de</strong><br />

f<strong>un</strong>ciones matemáticas.<br />

F<strong>un</strong>ciones:<br />

abs: int → int Calcula el valor absoluto <strong>de</strong> <strong>un</strong> número<br />

ceil: double → double Calcula el número entero mayor o igual que el dado<br />

floor: double → double Redon<strong>de</strong>a por <strong>de</strong>fecto el valor <strong>de</strong> <strong>un</strong> número<br />

fmod: double × double → double Calcula el resto <strong>de</strong> la división real <strong>de</strong> dos números<br />

sqrt: double → double Calcula la raíz cuadrada <strong>de</strong> <strong>un</strong> número<br />

#inclu<strong>de</strong> <br />

{<br />

x = abs(-7) // x vale 7<br />

y = ceil (5.2) // y vale 6<br />

z = floor (5.2) // z vale 5<br />

resto = fmod(5.0, 2.0) // resto vale 1<br />

}<br />

Los archivos <strong>de</strong> cabecera que<br />

contienen éstas f<strong>un</strong>ciones son<br />

entre otras:<br />

math.h<br />

float.h<br />

complex.h<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 17<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tipo bool<br />

Tamaño en bytes: 1 byte<br />

Dominio: dos únicos valores: { true, false }<br />

No todos los compiladores <strong>de</strong> <strong>C++</strong> tienen éste tipo <strong>de</strong> dato. En su lugar se utiliza el tipo int<br />

para representar el tipo <strong>de</strong> datos bool, <strong>de</strong> forma que el valor entero 0 representa false y<br />

cualquier otro valor representa true.<br />

Operaciones:<br />

&& Y lógica (and)<br />

|| O lógica (or)<br />

Falso → Cero<br />

Verda<strong>de</strong>ro → Distinto <strong>de</strong> cero<br />

! Negación lógica (not)<br />

bool × bool → bool<br />

bool → bool<br />

Operadores lógicos<br />

Prioridad <strong>de</strong><br />

los operadores<br />

!<br />

&&, ||


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tabla <strong>de</strong> verdad:<br />

A B ! A A && B A || B<br />

T T F T T<br />

T F F F T<br />

F T T F T<br />

F F T F F<br />

Operadores relacionales:<br />

= = Igual a<br />

!= Distinto<br />

> Mayor que<br />

< Menor que<br />

>= Mayor o igual que<br />


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Tipo char<br />

Tamaño en bytes: 1 byte<br />

Dominio: dígitos, letras mayúsculas, letras minúsculas y signos <strong>de</strong><br />

p<strong>un</strong>tuación.<br />

Internamente, los caracteres se almacenan como números. El tipo char<br />

representa valores en el rango -128 y 127 y se asocian con el código<br />

ASCII. Así, el carácter ‘A’ se almacena como el número 65, etc ...<br />

0 < 1 < 2 …. < 9 < A < B < … < Z < a < b < …< z<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 21<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Operaciones:<br />

Dado que los caracteres se almacenan internamente como números<br />

enteros, se pue<strong>de</strong>n realizar operaciones aritméticas con los datos <strong>de</strong> tipo<br />

char. Se pue<strong>de</strong> sumar <strong>un</strong> entero a <strong>un</strong> carácter para obtener otro código<br />

ASCII diferente.<br />

Ejemplos:<br />

Más a<strong>de</strong>lante veremos que, en <strong>un</strong>ión<br />

con la estructura array, se pue<strong>de</strong>n almacenar<br />

ca<strong>de</strong>nas <strong>de</strong> caracteres.<br />

Para convertir <strong>un</strong>a letra minúscula en mayúscula basta con restar 32.<br />

‘a’ - 32 = ‘A’<br />

Para convertir <strong>un</strong>a letra mayúscula en minúscula basta con sumar 32.<br />

‘B’ + 32 = ‘b’<br />

Para convertir el carácter ‘4’ en el número 4 basta con restar 48.<br />

‘4’ - 48 = 4<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 22


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

F<strong>un</strong>ciones:<br />

isdigit: char → int Devuelve TRUE si el carácter es: ‘0’, … ,‘9’<br />

isalpha: char → int Devuelve TRUE si el carácter es: ‘A’, … ,‘Z’, ‘a’, … , ‘z’.<br />

islower: char → int Devuelve TRUE si el carácter es <strong>un</strong>a letra minúscula: ‘a’, … , ‘z’.<br />

isupper: char → int Devuelve TRUE si el carácter es <strong>un</strong>a letra mayúscula: ‘A’, … , ‘Z’.<br />

tolower: char → char Convierte <strong>un</strong> carácter mayúscula en minúscula.<br />

toupper: char → char Convierte <strong>un</strong> carácter minúscula en mayúscula.<br />

#inclu<strong>de</strong> <br />

char c = 65;<br />

{<br />

...<br />

char c = ‘A’;<br />

c = tolower (c); // c vale ‘a’<br />

t = isdigit(c) ; // t vale O (FALSE)<br />

...<br />

}<br />

El archivo <strong>de</strong> cabecera que<br />

contiene éstas f<strong>un</strong>ciones es:<br />

ctype.h<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 23<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Modificadores <strong>de</strong> tipos <strong>de</strong> datos<br />

Los tipos <strong>de</strong> datos int, double y char tienen variaciones o modificadores<br />

<strong>de</strong> tipos <strong>de</strong> datos.<br />

Permiten <strong>un</strong> uso más eficiente<br />

Son modificadores los siguientes:<br />

<strong>de</strong> los tipos <strong>de</strong> datos<br />

signed <strong>un</strong>signed<br />

short log<br />

Rango <strong>de</strong> valores<br />

<strong>un</strong>signed int 0 …65625<br />

long double -3,37 × 10 -4932 … 3,37 × 10 4932<br />

long int -2147483648 … 2147483647<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 24


Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

Las computadoras realizan numerosas operaciones para la resolución <strong>de</strong><br />

problemas,<br />

- Operaciones aritméticas y lógicas.<br />

- Operaciones condicionales.<br />

...<br />

A<strong>de</strong>más, pue<strong>de</strong> ocurrir que en <strong>un</strong>a misma expresión concurran varios tipos<br />

<strong>de</strong> datos. Ante ésta situación, <strong>de</strong>bemos saber cómo se comporta el<br />

compilador.<br />

Cuando los dos operandos son <strong>de</strong><br />

tipos distintos, el <strong>de</strong> tipo menor se<br />

promociona<br />

al <strong>de</strong> tipo mayor.<br />

long double<br />

double<br />

float<br />

int<br />

short int<br />

char<br />

Tipos <strong>de</strong> mayor<br />

a menor<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 25<br />

Tipos <strong>de</strong> datos básicos en <strong>C++</strong><br />

En cuanto a la memoria que<br />

ocupa cada tipo:<br />

Esto no siempre es cierto,<br />

<strong>de</strong>pen<strong>de</strong> <strong>de</strong>l or<strong>de</strong>nador y<br />

<strong>de</strong>l compilador.<br />

Tipo <strong>de</strong><br />

datos<br />

Datos<br />

almacenados<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 26<br />

+<br />

-<br />

#inclu<strong>de</strong> <br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

int i;<br />

i = sizeof( int )*8;<br />

}<br />

cout


3<br />

Constantes y variables <strong>C++</strong><br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 27<br />

Constantes y Variables<br />

• Son porciones <strong>de</strong> memoria que almacenan <strong>un</strong> valor.<br />

• Las variables son palabras que manipulan datos. Dicho valor pue<strong>de</strong> ser<br />

modificado en cualquier momento durante la ejecución <strong>de</strong>l <strong>programa</strong>.<br />

• Una constante es <strong>un</strong>a variable cuyo valor no pue<strong>de</strong> ser modificado.<br />

• Las variables pue<strong>de</strong>n almacenar todo tipo <strong>de</strong> datos: caracteres, números,<br />

estructuras, etc … Dependiendo <strong>de</strong>l valor <strong>de</strong> la variable, <strong>de</strong>cimos que dicha<br />

variable es <strong>de</strong> <strong>un</strong> tipo <strong>de</strong> dato.<br />

• Tanto las variables como las constantes están constituidas por <strong>un</strong> nombre y <strong>un</strong><br />

valor. El nombre lo llamaremos i<strong>de</strong>ntificador.<br />

Toda variable utilizada en <strong>un</strong> <strong>programa</strong> <strong>de</strong>be ser <strong>de</strong>clarada previamente. En<br />

<strong>C++</strong>, ésta <strong>de</strong>claración pue<strong>de</strong> situarse en cualquier parte <strong>de</strong>l <strong>programa</strong>.<br />

Dependiendo <strong>de</strong> dón<strong>de</strong> se <strong>de</strong>finan,<br />

tenemos varios tipos:<br />

Variables globales<br />

Variables locales<br />

Parámetros<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 28


Constantes y Variables<br />

Declaración <strong>de</strong> variables<br />

La <strong>de</strong>claración <strong>de</strong> <strong>un</strong>a variable consiste en escribir <strong>un</strong> sentencia que<br />

proporciona información al compilador <strong>de</strong> <strong>C++</strong>.<br />

• El compilador reserva <strong>un</strong> espacio <strong>de</strong> almacenamiento en memoria.<br />

• Los nombres <strong>de</strong> las variables se suelen<br />

escribir en minúsculas.<br />

En <strong>C++</strong> las variables no se<br />

actualizan automáticamente<br />

El procedimiento para <strong>de</strong>clarar <strong>un</strong>a variable:<br />

;<br />

;<br />

= valor;<br />

int x;<br />

char x, y, z;<br />

long int i =10, j, k=0;<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 29<br />

Constantes y Variables<br />

Una forma <strong>de</strong> expresar el procedimiento para <strong>de</strong>clarar <strong>un</strong>a variable es<br />

mediante los diagramas sintácticos:<br />

Declaración <strong>de</strong> variables<br />

Tipo <strong>de</strong> dato Nombre_<strong>de</strong>_variable<br />

=<br />

Valor_inicial<br />

Declaraciones locales<br />

Son variables locales aquellas que están <strong>de</strong>claradas <strong>de</strong>ntro <strong>de</strong> las<br />

f<strong>un</strong>ciones o <strong>de</strong> los bloques.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 30<br />

,<br />

;


Constantes y Variables<br />

Declaraciones globales ( variables globales, f<strong>un</strong>ciones, …)<br />

La zona <strong>de</strong> <strong>de</strong>claraciones globales <strong>de</strong> <strong>un</strong> <strong>programa</strong> pue<strong>de</strong> incluir<br />

<strong>de</strong>claraciones <strong>de</strong> variables y <strong>de</strong>claraciones <strong>de</strong> f<strong>un</strong>ciones (prototipos).<br />

Las f<strong>un</strong>ciones y variables<br />

aquí <strong>de</strong>claradas, se pue<strong>de</strong>n<br />

utilizar en cualquier p<strong>un</strong>to<br />

<strong>de</strong>l <strong>programa</strong>.<br />

Parámetros<br />

Definidos en la lista <strong>de</strong> parámetros<br />

formales <strong>de</strong> las f<strong>un</strong>ciones.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 31<br />

Constantes y Variables<br />

Ejemplos:<br />

…<br />

int f<strong>un</strong>cion1()<br />

{<br />

int i;<br />

if ( i= =1)<br />

{<br />

char m=‘s’;<br />

….<br />

}<br />

}<br />

...<br />

Variables locales<br />

/* aquí no se conoce a m */<br />

La variable m solo<br />

existe en éste bloque<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 32<br />

…<br />

int calcular(int i, float j)<br />

{<br />

...<br />

}<br />

...<br />

Parámetros


Constantes y Variables<br />

Declaración <strong>de</strong> Constantes<br />

Una constante es <strong>un</strong>a variable cuyo valor no pue<strong>de</strong> ser modificado.<br />

Los nombres <strong>de</strong> las constantes se suelen escribir en mayúsculas.<br />

1. Constantes <strong>de</strong>claradas const<br />

La palabra reservada const es <strong>un</strong> calificador <strong>de</strong> tipo variable e indica que el valor<br />

<strong>de</strong> variable no se pue<strong>de</strong> modificar.<br />

const = ;<br />

…<br />

const int DIAS = 7;<br />

const char VACIO = ‘ ‘;<br />

const char PORCENTAJE = ‘% ‘;<br />

...<br />

Ejemplos<br />

Si se intenta modificar <strong>un</strong>a variable<br />

<strong>de</strong>finida con const, se produce error.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 33<br />

Constantes y Variables<br />

2. Constantes <strong>de</strong>finidas<br />

Se <strong>de</strong>claran mediante la directiva #<strong>de</strong>fine<br />

#<strong>de</strong>fine <br />

Ejemplos<br />

…<br />

#<strong>de</strong>fine pi 3.14<br />

#<strong>de</strong>fine fin ‘F’<br />

...<br />

No se especifica<br />

el tipo <strong>de</strong> dato<br />

No aparece ;<br />

al final <strong>de</strong> la sentencia<br />

No aparece el<br />

símbolo =<br />

Es más recomendable utilizar const en lugar <strong>de</strong> #<strong>de</strong>fine ya que el compilador<br />

genera código más eficiente.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 34


Constantes y Variables<br />

3. Constantes enumeradas<br />

Las constantes enumeradas permiten crear listas <strong>de</strong> elementos afines.<br />

Ejemplo <strong>de</strong> constante enumerada<br />

<strong>de</strong> <strong>un</strong>a lista <strong>de</strong> colores<br />

…<br />

enum Colores {Rojo, Ver<strong>de</strong>, Azul, Amarillo};<br />

enum Botones {Salir, Jugar};<br />

…<br />

Colores favorito = Rojo;<br />

…<br />

enum { };<br />

Se comporta como<br />

cualquier otro tipo <strong>de</strong><br />

datos.<br />

Se pue<strong>de</strong>n <strong>de</strong>clarar<br />

variables <strong>de</strong> tipo<br />

enumerado.<br />

El compilador asigna <strong>un</strong> número a cada elemento <strong>de</strong>l conj<strong>un</strong>to (comenzando con 0).<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 35<br />

Constantes y Variables<br />

Ejemplo <strong>de</strong>l f<strong>un</strong>cionamiento <strong>de</strong> enumeraciones<br />

#inclu<strong>de</strong> <br />

int main()<br />

{<br />

enum Dias { L<strong>un</strong>es, Martes, Miercoles, Jueves, Viernes };<br />

Dias libre = Viernes; // Dias libre = 4;<br />

cout


4<br />

Operadores y expresiones<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 37<br />

Operadores y Expresiones<br />

1. Instrucciones <strong>de</strong> asignación.<br />

= ;<br />

Pue<strong>de</strong> ser otra variable, <strong>un</strong>a constante o <strong>un</strong>a operación<br />

entre variables y constantes.<br />

El operador asignación (=) asigna el valor <strong>de</strong> la expresión <strong>de</strong>recha a la<br />

variable situada en la izquierda <strong>de</strong> la instrucción.<br />

Po<strong>de</strong>mos tener en <strong>C++</strong> varios operadores <strong>de</strong> asignación:<br />

= += -= *= /= %=<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 38


Operadores y Expresiones<br />

Ejemplos:<br />

m += n;<br />

m -= n;<br />

m *= n;<br />

m /= n;<br />

m %= n;<br />

m = n; // asigna el valor <strong>de</strong> n a m<br />

m = m + n; //suma m y n y lo asigna a la variable m<br />

m = m- n; // resta m menos n y lo asigna a la variable m<br />

m = m * n; //multiplica m por n y lo asigna a la variable m<br />

m = m / n; //divi<strong>de</strong> m entre n y lo asigna a la variable m<br />

m = m % n; //calcula el resto <strong>de</strong> la div. entera y lo asigna a la variable m<br />

Instrucción abreviada.<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 39<br />

Operadores y Expresiones<br />

Más ejemplos:<br />

Po<strong>de</strong>mos dar valores a varias variables a la vez<br />

m = n = t = 10; // Damos a las variables m, n y t el valor 10<br />

m = n = t = a; // las variables m, n y t toman el valor <strong>de</strong> la variable a<br />

También po<strong>de</strong>mos asignar a varias variables el valor <strong>de</strong> otra <strong>de</strong> <strong>un</strong> sólo golpe<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 40


Operadores y Expresiones<br />

2. Operador <strong>de</strong> dirección: &<br />

999<br />

998<br />

997<br />

2<br />

1<br />

0<br />

Cuando se <strong>de</strong>clara <strong>un</strong>a variable, se le asocian tres características:<br />

1000001 x<br />

1001111<br />

0000001<br />

- nombre <strong>de</strong> la variable<br />

- tipo <strong>de</strong> la variable<br />

- dirección <strong>de</strong> memoria<br />

…<br />

char x = ‘A’;<br />

…<br />

El valor <strong>de</strong> la variable x es ‘A’.<br />

La dirección <strong>de</strong> memoria es 2.<br />

Para conocer la dirección <strong>de</strong> memoria don<strong>de</strong> se encuentra<br />

almacenada la variable, se pue<strong>de</strong> utilizar el operador &.<br />

…<br />

cout


5<br />

Instrucciones <strong>de</strong><br />

Entrada / Salida<br />

Metodología y Técnicas <strong>de</strong> Programación I 2004/2005 43<br />

Instrucciones <strong>de</strong> Entrada / Salida<br />

En <strong>C++</strong> la entrada y salida se lee y escribe en flujos. Cuando se incluye la<br />

biblioteca iostream.h en el <strong>programa</strong>, se <strong>de</strong>finen automáticamente dos flujos:<br />

Flujo cin (se utiliza para la entrada <strong>de</strong> datos)<br />

Flujo cout (se utiliza para la salida <strong>de</strong> datos)<br />

Permiten la com<strong>un</strong>icación <strong>de</strong>l<br />

or<strong>de</strong>nador con el exterior para<br />

tomar datos o <strong>de</strong>volver resultados<br />

Esta biblioteca también nos proporciona dos operadores, <strong>un</strong>o <strong>de</strong> inserción ( ) para<br />

extraer valores <strong>de</strong>l flujo cin y almacenarlos en variables.<br />

…<br />

cin >> a;<br />

cin >> a >> b >> c;<br />

…<br />

…<br />

cout


Instrucciones <strong>de</strong> Entrada / Salida<br />

<strong>C++</strong> utiliza secuencias <strong>de</strong> escape para visualizar caracteres que no están<br />

representados por los símbolos tradicionales.<br />

Las más utilizadas las mostramos en la siguiente tabla:<br />

\n Retorno <strong>de</strong> carro y avance <strong>de</strong> línea<br />

\t Tabulación<br />

\a Alarma<br />

\” Dobles comillas<br />

\\ Barra inclinada<br />

…<br />

cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!