Date post: | 31-Dec-2015 |
Category: |
Documents |
Upload: | bethany-cervantes |
View: | 54 times |
Download: | 1 times |
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ANALISIS DE PROBLEMASANALISIS DE PROBLEMASSOLUCIONES LOGICASSOLUCIONES LOGICAS
PREPARAR CAFÉ UTILIZANDO PREPARAR CAFÉ UTILIZANDO COMO HERRAMIENTA UNA COMO HERRAMIENTA UNA
CAFETERA ELECTRICA.CAFETERA ELECTRICA.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OBJETIVO OBJETIVO
• ANALIZAR PROBLEMAS DE LA VIDA ANALIZAR PROBLEMAS DE LA VIDA RUTINARIA PARA ENCONTRAR LAS RUTINARIA PARA ENCONTRAR LAS DIFERENTES PARTES NECESARIAS PARA DIFERENTES PARTES NECESARIAS PARA SU SOLUCION, ASOCIADAS A LA SOLUCION SU SOLUCION, ASOCIADAS A LA SOLUCION DE PROBLEMAS POR MEDIO DE LA DE PROBLEMAS POR MEDIO DE LA PROGRAMACION.PROGRAMACION.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Preparar Café en Cafetera EléctricaPreparar Café en Cafetera Eléctrica
Ahh!!! necesito
Elementos
Procedimientos
Herramientas
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Elementos
Herramientas
Procedimientos
Materia Prima
Depósitos
Instrucciones(Procesos)
Café preparado
Resultados
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Materia Materia PrimaPrima
Depósitos
Instrucciones(procesos)
Resultados
Datos Entradas
Áreas de Almacenamiento
Espacio de Memoria
Procesos aritméticos /
lógicosDeclaraciones
Salidas
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
PASOS PARA RESOLVER UN PROBLEMAPASOS PARA RESOLVER UN PROBLEMA
•OBJETIVOS:OBJETIVOS:– DEFINIR CONCEPTOS BASICOS DE DEFINIR CONCEPTOS BASICOS DE
PROGRAMACION.PROGRAMACION.– DESCRIBIR LOS PASOS PARA RESOLVER DESCRIBIR LOS PASOS PARA RESOLVER
UN PROBLEMA UTILIZANDO AL UN PROBLEMA UTILIZANDO AL COMPUTADOR COMO HERRAMIENTA DE COMPUTADOR COMO HERRAMIENTA DE APOYO.APOYO.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La Ciclo de Vida de La ProgramaciónProgramación
Definición Análisis
¿Cuál es el problema?
E - P - S
2
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La ProgramaciónCiclo de Vida de La Programación
Programación
Algoritmo Prueba de Escritorio
Pseudocódigo
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La ProgramaciónCiclo de Vida de La Programación
Lenguaje C
CompilaciónProg. Fuente
Prog. Compilador
1
Lista fuente con errores de sintaxis
Errores sintaxis
no
si
Codificación TraducciónCompilación
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La Ciclo de Vida de La ProgramaciónProgramación
Listado fuente
Enlace EjecuciónProg. Objeto
1
Prog. Ejec. en leng. máquina
Datos Resultados
Errores ejecución
2
Ejecución
si
no
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La Ciclo de Vida de La ProgramaciónProgramación
Verificación Implementación
Datos Resultados Fuente
Procedimientos, entrenamiento
en uso
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Ciclo de Vida de La Ciclo de Vida de La ProgramaciónProgramación
Mantenimiento Documentación
Modificaciones, actualizaciones
• Interna (codificación)
• Externa
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ObjetivosObjetivos
• • Conocer el entorno del Lenguaje C.Conocer el entorno del Lenguaje C.• Conocer los elementos básicos del C.Conocer los elementos básicos del C.• Manejar los diferentes tipos de datos.Manejar los diferentes tipos de datos.• Definir constantes. Definir constantes. • Comprender los conceptos sobre Comprender los conceptos sobre constantes y constantes y variables.variables.• Conocer los diferentes operadores del C y Conocer los diferentes operadores del C y cómo cómo se construyen las expresiones.se construyen las expresiones.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
INTRODUCCIÓN AL LENGUAJE CINTRODUCCIÓN AL LENGUAJE C• FUE DESARROLLADO EN LOS AÑOS 70 POR DENNIS RITCHIE EN FUE DESARROLLADO EN LOS AÑOS 70 POR DENNIS RITCHIE EN
LOS LABORATORIOS BELL.LOS LABORATORIOS BELL.
• ES EL RESULTADO DE DOS LENGUAJES ANTERIORES, BCPL Y B.ES EL RESULTADO DE DOS LENGUAJES ANTERIORES, BCPL Y B.
• FUE DISEÑADO PARA EL DESARROLLO DE SISTEMAS FUE DISEÑADO PARA EL DESARROLLO DE SISTEMAS OPERATIVOS (UNIX), SIN EMBARGO POSEE CARACTERÍSTICAS OPERATIVOS (UNIX), SIN EMBARGO POSEE CARACTERÍSTICAS ESTRUCTURADAS DE ALTO NIVEL LO QUE PERMITE ESTRUCTURADAS DE ALTO NIVEL LO QUE PERMITE DESARROLLAR PROGRAMAS DE APLICACIÓN.DESARROLLAR PROGRAMAS DE APLICACIÓN.
• SE DIO A CONOCER EN 1978 POR LA PUBLICACIÓN DE BRAIN SE DIO A CONOCER EN 1978 POR LA PUBLICACIÓN DE BRAIN KERNIGHAN Y RITCHIE.KERNIGHAN Y RITCHIE.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
• C ES UN LENGUAJE DE PROGRAMACIÓN ESTRUCTURADO C ES UN LENGUAJE DE PROGRAMACIÓN ESTRUCTURADO DE PROPÓSITOS GENERALES.DE PROPÓSITOS GENERALES.
• SE PUEDEN DESARROLLAR PROGRAMAS FUENTES SE PUEDEN DESARROLLAR PROGRAMAS FUENTES CONCISOS, POR SU GRAN NÚMERO DE OPERADORES.CONCISOS, POR SU GRAN NÚMERO DE OPERADORES.
• TIENE UN CONJUNTO DE INSTRUCCIONES TIENE UN CONJUNTO DE INSTRUCCIONES RELATIVAMENTE PEQUEÑO, PERO INCLUYE NUMEROSAS RELATIVAMENTE PEQUEÑO, PERO INCLUYE NUMEROSAS FUNCIONES DE BIBLIOTECA QUE MEJORAN LAS FUNCIONES DE BIBLIOTECA QUE MEJORAN LAS INSTRUCCIONES BÁSICAS.INSTRUCCIONES BÁSICAS.
• LOS PROGRAMAS SON PORTABLES, SE PUEDEN LOS PROGRAMAS SON PORTABLES, SE PUEDEN COMPILAR Y EJECUTAR EN MUCHAS COMPUTADORAS COMPILAR Y EJECUTAR EN MUCHAS COMPUTADORAS DIFERENTES CON MUY POCA MODIFICACIÓN. DIFERENTES CON MUY POCA MODIFICACIÓN.
INTRODUCCIÓN AL LENGUAJE INTRODUCCIÓN AL LENGUAJE CC
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
El ENTORNO DE CEl ENTORNO DE C
• EDITOR: PERMITE INTRODUCIR Y MODIFICAR EL CODIGO EDITOR: PERMITE INTRODUCIR Y MODIFICAR EL CODIGO FUENTE C.FUENTE C.
• COMPILADOR: ES EL PROGRAMA QUE CONVIERTE EL FUENTE COMPILADOR: ES EL PROGRAMA QUE CONVIERTE EL FUENTE C EN UN CODIGO ENTENDIBLE POR EL COMPUTADOR.C EN UN CODIGO ENTENDIBLE POR EL COMPUTADOR.
• ARCHIVOS PARA INCLUIR: ARCHIVOS SEPARADOS (INCLUDE) ARCHIVOS PARA INCLUIR: ARCHIVOS SEPARADOS (INCLUDE) QUE FUEDEN SER UTILES EN CIERTAS SITUACIONES.QUE FUEDEN SER UTILES EN CIERTAS SITUACIONES.
• ARCHIVOS DE BIBLIOTECAS: PROGRAMAS PREVIAMENTE ARCHIVOS DE BIBLIOTECAS: PROGRAMAS PREVIAMENTE COMPILADOS QUE REALIZAN FUNCIONES ESPECIFICAS.COMPILADOS QUE REALIZAN FUNCIONES ESPECIFICAS.
• ENLAZADOR: COMBINA TODAS LAS PARTES NECESARIAS ENLAZADOR: COMBINA TODAS LAS PARTES NECESARIAS ( TALES COMO ARCHIVOS DE BIBLIOTECA) DE UN PROGRAMA ( TALES COMO ARCHIVOS DE BIBLIOTECA) DE UN PROGRAMA C PARA PRODUCIR EL CODIGO EJECUTABLE FINAL.C PARA PRODUCIR EL CODIGO EJECUTABLE FINAL.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ESTRUCTURA DE UN PROGRAMA ESTRUCTURA DE UN PROGRAMA EN CEN C
• CONSTA DE UNA O MÁS FUNCIONES, UNA DE CONSTA DE UNA O MÁS FUNCIONES, UNA DE LAS CUALES SE LLAMA main.LAS CUALES SE LLAMA main.
• CADA FUNCIÓN DEBE CONTENER:CADA FUNCIÓN DEBE CONTENER:
– CABECERA DE LA FUNCIÓN, QUE CONSTA DEL NOMBRE CABECERA DE LA FUNCIÓN, QUE CONSTA DEL NOMBRE DE LA FUNCIÓN SEGUIDO DE LA LISTA OPCIONAL DE DE LA FUNCIÓN SEGUIDO DE LA LISTA OPCIONAL DE ARGUMENTOS ENCERRADOS EN PARÉNTESIS.ARGUMENTOS ENCERRADOS EN PARÉNTESIS.
– LISTA DE DECLARACIONES DE ARGUMENTOS.LISTA DE DECLARACIONES DE ARGUMENTOS.– SENTENCIA COMPUESTA, ENCERRADA CON UN PAR DE SENTENCIA COMPUESTA, ENCERRADA CON UN PAR DE
LLAVES { }.LLAVES { }.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ESTRUCTURA DE UN PROGRAMA ESTRUCTURA DE UN PROGRAMA EN CEN C
• LAS SENTENCIAS DE EXPRESIÓN DEBEN TERMINAR LAS SENTENCIAS DE EXPRESIÓN DEBEN TERMINAR EN PUNTO Y COMA (;).EN PUNTO Y COMA (;).
• LOS COMENTARIOS PUEDEN APARECER EN LOS COMENTARIOS PUEDEN APARECER EN CUALQUIER PARTE DEL PROGRAMA DELIMITADOS CUALQUIER PARTE DEL PROGRAMA DELIMITADOS POR /* */. EJEMPLO:POR /* */. EJEMPLO:
/*MI PRIMER COMENTARIO EN C*//*MI PRIMER COMENTARIO EN C*/
• PUEDE USAR MAYÚSCULA O MINÚSCULA, AUNQUE PUEDE USAR MAYÚSCULA O MINÚSCULA, AUNQUE ES COSTUMBRE ESCRIBIR EN MINÚSCULA LAS ES COSTUMBRE ESCRIBIR EN MINÚSCULA LAS INSTRUCCIONES ORDINARIAS. MAYÚSCULA Y INSTRUCCIONES ORDINARIAS. MAYÚSCULA Y MINÚSCULA NO SON EQUIVALENTES EN C.MINÚSCULA NO SON EQUIVALENTES EN C.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
BibliotecaBiblioteca
stdio.hstdio.h time.htime.hconio.hconio.hmath.hmath.h
puts
gets
getch
scanf
printf
getchar
putchar
abs
ceil
cos
exp
sqrt
fmod
clrscr
gotoxy
textcolor
window
textbackground
getdate
gettime
setdate
settime
time
. . .
. . . . . . . . .
. . .
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
PROGRAMA SENCILLO EJEMPLOPROGRAMA SENCILLO EJEMPLO
• #include <stdio.h>#include <stdio.h>
/* Este programa solo visualiza un mensaje /* Este programa solo visualiza un mensaje en la pantalla del computador */en la pantalla del computador */
main ( )main ( )
{{
puts("Bienvenidos al mundo del puts("Bienvenidos al mundo del C");C");
printf (“ Este es mi primer programa en printf (“ Este es mi primer programa en C”);C”);
}}
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ELEMENTOS BASICOSELEMENTOS BASICOS
IDENTIFICADORES Nombres de constantes, variables, tipos, funciones y
etiquetas de un programa.
SINTAXIS: letra/_[letra/dígito/_].......
cualquier número de caracteres ( 31 significativos).
EJEMPLO: suma calculo_promedio _ordenar ab123
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ELEMENTOS BASICOSELEMENTOS BASICOS
PALABRAS CLAVESIdentificadores predefinidos con significado especial para el compilador C.
auto break case char const continue defaul do double else enum externfloat for goto if int longregister return short signed sizeof staticstruct switch typedef union unsigned voidvolatile while far fortran huge near pascal
Las palabras claves deben escribirse en minúscula
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ELEMENTOS BASICOSELEMENTOS BASICOS
CARACTERES DEL C.
Letras mayúsculas: A B C D E F G H I J K L M N O P Q R S T U V W X Y ZLetras minúsculas: a b c d e f g h i j k l m n o p q r s t u v w x y zDígitos decimales: 0 1 2 3 4 5 6 7 8 9Carácter de subrayado: _Carácter de espacio en blanco: espacio,tab,retorno de carro,avance de página,tab vertical y nueva línea.Carácteres especiales y signos de puntuación: , . ; ;: ?’”( ) [ ] { } < ! | / \ ~+ # % & ^ * - = >
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
TIPOS DE DATOS BASICOS:TIPOS DE DATOS BASICOS:
• TIPOS ENTEROS: char, int, short, long, signed, TIPOS ENTEROS: char, int, short, long, signed,
unsigned y enumunsigned y enum
• TIPOS REALES: float, double, long doubleTIPOS REALES: float, double, long double
• OTROS TIPOS: poiters, arrays, structOTROS TIPOS: poiters, arrays, struct
TIPOS ENTEROS
char: ( caracter --- 1byte ) enteros de -128 a 127 ASCII unsigned char: valor de 0 a 255 Ejemplo: char car;
char abreviación de signed char.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
int: int: ( entero) máquina de 16 bits -32768 a ( entero) máquina de 16 bits -32768 a 3276732767
unsigned int 0 a 65535unsigned int 0 a 65535 Ejemplo: Ejemplo: int n,x; int n,x;
int abreviación de signed int.int abreviación de signed int.
shortshort: : ( entero corto -- 2 bytes ) -32768 a 32767( entero corto -- 2 bytes ) -32768 a 32767 unsigned short 0 a 65535unsigned short 0 a 65535 Ejemplo: Ejemplo: short i, j;short i, j;
short abreviación de signed short intshort abreviación de signed short int
long: long: ( entero largo -- 4 bytes) -2E31 a 2E31-1 ( entero largo -- 4 bytes) -2E31 a 2E31-1 unsigned long 0 a 4294967295unsigned long 0 a 4294967295 Ejemplo: Ejemplo: long n ;long n ;
long abreviación de signed long intlong abreviación de signed long int
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
enum:enum: tipo enumerado. tipo enumerado. Ejemplo: Ejemplo: enum dia_semanaenum dia_semana { lunes, martes, miercoles,{ lunes, martes, miercoles, jueves, viernes, jueves, viernes,
sabado, sabado, domingodomingo } hoy;} hoy; enum dia_semana ayer;enum dia_semana ayer;
valor ordinal de lunes es 0. valor ordinal de lunes es 0.
Ejemplo2: Ejemplo2: enum dia_semanaenum dia_semana { lunes = 1, martes, { lunes = 1, martes,
miercoles,miercoles, jueves, viernes, jueves, viernes,
sabado, sabado, domingodomingo } hoy;} hoy;valor ordinal de martes es 2.valor ordinal de martes es 2.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
TIPO REALTIPO REALfloat:float: (simple precisión -- 4 bytes) hasta 7 dígitos (simple precisión -- 4 bytes) hasta 7 dígitos significativos.significativos. negativos: -3.402823E+38 a -1.40129E-negativos: -3.402823E+38 a -1.40129E-
4545 positivos: 1.40129E-45 a positivos: 1.40129E-45 a
3.402823E+383.402823E+38double:double: ( doble precisión -- 8 bytes) hasta 15 dígitos ( doble precisión -- 8 bytes) hasta 15 dígitos significativos.significativos. negativos : - negativos : -
1.79769313486231E+38 a 1.79769313486231E+38 a - 4.94065E-324- 4.94065E-324 positivos : 4.94065E-324 a positivos : 4.94065E-324 a
1.797693134862316E+3081.797693134862316E+308long double:long double: ( doble precisión largos -- 8 bytes) ( doble precisión largos -- 8 bytes) Precisión extendida -- depende del compilador. Precisión extendida -- depende del compilador.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
TIPOS ADICIONALES DE DATOSTIPOS ADICIONALES DE DATOSpointers:pointers: ( punteros) dirección de memoria que ( punteros) dirección de memoria que
apunta a apunta a un objeto.un objeto. Ejemplo : Ejemplo : int *p ;int *p ;
struct:struct: variables que representan registros. variables que representan registros. Ejemplo: Ejemplo: structstruct {{ float a, b;float a, b; } complejo;} complejo; struct personastruct persona {{ char nombre[20];char nombre[20]; long dni;long dni; };}; struct persona reg;struct persona reg;
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
union: union: representan registros variables ( alterna representan registros variables ( alterna varios tipos ).varios tipos ).
EjemplosEjemplos;; : : union tipo_unionunion tipo_union { { char var1;char var1; int var2;int var2; float var3;float var3; };}; union tipo_union union tipo_union
var_union;var_union;
arrays: arrays: conjunto de objetos del mismo tipo. conjunto de objetos del mismo tipo. Ejemplo: Ejemplo: intint lista[40]; lista[40]; /* /* lista[0] a lista[0] a
lista[39] */lista[39] */
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Declaración de variables o parámetros
main() {
int entero1, entero2; char caracter1, c, car2; float real1, r2; double d1, d2; short int s; long int entero_largo;unsigned char cc;
}
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CONSTANTES EN C
NÚMEROS, CARACTER, CADENA DE CARACTERES.
CONSTANTES ENTERAS: pueden ser de base 10,8,16
Decimal: uno o más dígito ( 0..9), el primero distinto de 0, signo +,-.
Ejemplo : 256
Octal: uno o más dígitos ( 0..7), precedidos por 0.
Ejemplo: 0400
Hexadecimal: uno o más caracteres ( 0..9; A..F), precedidos por 0x o 0X.
Ejemplo: 0x100
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CONSTANTES REALES:
Formato: [ dígitos][.dígitos][E/e[+/-]dígitos] dígitos: 0..9 E/e: símbolo de exponente
Ejemplos: 17.24 , .008E3, 27e-3, -0.025
CONSTANTES DE UN SOLO CARACTER:Encerradas entre ‘ ‘ ( comillas simples)
Ejemplos: ‘ ‘ , ‘x’, ‘\n’
CONSTANTES DE CARACTERES:Encerradas entre “ “ ( comillas dobles). Ejemplos: - “ Entre un numero” - “ Esta cadena de caracteres es dema\ siado larga” - printf (“Primera cadena,” “Segunda cadena”);
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
SECUENCIA DE ESCAPE DE CRepresentan caracteres no imprimibles CARACTER SECUENCIA VALOR ASCI
Sonido (bell) \a 007Backspace \b 008Tab horizontal \t 009Tab vertical \v 011Nueva línea \n 010Form feed \f 012
Retorno del carro \r 013Comillas (“) \” 034
Apóstrofo (‘) \’ 039Interrogación ( ?) \? 063 Backslash ( \ ) \\ 092Nulo \0 000
d=dígito octal \ddd h=dígito hexadecimal \xhh x ó X
Ejemplo: letra ‘A’ = 065 ASCII = \’101’ octal = \’x41’
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CONSTANTES SIMBOLICAS:CONSTANTES SIMBOLICAS:
• Nombre que sustituye una secuencia de caracteresNombre que sustituye una secuencia de caracteres ( constante numérica, carácter, cadena de caracteres).( constante numérica, carácter, cadena de caracteres).
• Cuando el programa se compila, las constantes simbólicas se Cuando el programa se compila, las constantes simbólicas se reemplazan por su correspondiente secuencia de caracteres.reemplazan por su correspondiente secuencia de caracteres.
• Se definen al comienzo del programa.Se definen al comienzo del programa.
Formato: #define Nombre TextoFormato: #define Nombre Texto
- Nombre representa un nombre simbólico.- Nombre representa un nombre simbólico.- Texto representa la secuencia de caracteres asociada al nombre.- Texto representa la secuencia de caracteres asociada al nombre.- No se coloca - No se coloca ; ; al final ya que no es una verdadera sentencia de C.al final ya que no es una verdadera sentencia de C.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CONSTANTES SIMBOLICAS:CONSTANTES SIMBOLICAS:
Ejemplo: Ejemplo: #define INTERES 0.23 #define INTERES 0.23
#define PI 3.141593 #define PI 3.141593 #define CIERTO 1 #define CIERTO 1
#define AMIGA “Marta” #define AMIGA “Marta”
{{………………..area = PI *radio*radioarea = PI *radio*radioarea = 3.141593*radio*radio area = 3.141593*radio*radio ………………..}}
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
COMO NOMBRAR CONSTANTES CON COMO NOMBRAR CONSTANTES CON EL MODIFICADOR CONSTEL MODIFICADOR CONST• Cuando inicializamos una variable dentro de una Cuando inicializamos una variable dentro de una
declaración, podemos marcar la variable de modo que declaración, podemos marcar la variable de modo que el programa no pueda alterar su valor. Por ello, el programa no pueda alterar su valor. Por ello, anteponemos la palabra anteponemos la palabra const const a la declaración. a la declaración.
• ConstConst es un modificador de las variables que se es un modificador de las variables que se declaran.A estás variables se les conoce como declaran.A estás variables se les conoce como constantes declaradas.constantes declaradas.
• SINTAXIS:SINTAXIS:ConstConst nombre_de_tipo nombre_variable = nombre_de_tipo nombre_variable = constante;constante;
• EjemploEjemplo const double PI = 3.14592;const double PI = 3.14592;const int N_PROV = 9;const int N_PROV = 9;
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
VARIABLES
Identificador para representar cierto tipo de información. Nombre de variable ----> Contenido o Valor ----> Tipo de
dato
Ejemplo: int a, b, c; char d;
. . . . a = 3; a = 4; b = 5; b = 2; c = a + b; c = a - b;
d = ‘a’; d = ‘w’
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EXPRESIONES
Representa una unidad de datos simples: constante,variable, elemento de un array, referencia de unafunción.
Combinación interconectada de datos simples poruno o más operadores.
Condiciones lógicas ciertas o falsas [1,0 (cantidadesnuméricas)].
Ejemplo: a +b x=y c=a+b x<=y x==y ++y
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
SENTENCIAS
Hace que la computadora lleve a cabo algunaacción.
Tipos: - Sentencia de expresión - Sentencias Compuestas - Sentencias de Control
Ejemplos: a=3; ++i; c=a+b;;
Sentencia Compuesta: { pi = 3.141593;
circunferenci = 2*pi*radio; area = pi*radio*radio; }
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
SENTENCIAS
Sentencias de Control: acciones especiales como comprobaciones lógicas, bucles y ramificaciones.
Ejemplo:
while (cont<=n) { printf ( “x=“);
scanf (“%f”,&x); suma += x; ++cont; }
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADORES ARITMETICOS
+ ADICION - RESTA * MULTIPLICACION
/ DIVISION % RESTO DE DIVISION ENTERA--- No hay operador de exponenciación.
Ejemplos: dado a=10 y b=3 v1=12.5 y v2=2.0Expresión valor Expresión valor
a+b 13 v1+v2 14.5 a-b 7 v1-v2 10.5 a*b 30 v1*v2 25.0 a/b 3 v1/v2 6.25 a%b 1 ---- ----Operaciones con caracteres Operaciones con operandos negativosSi c1= P y c2 = T Si a=11 y b= -3
Expresión Valor Expresión Valor c1 80 a+b 8 c1+c2 164 a-b 14 c1+C2+5 169 a*b -33 a/b -3 a%b 2 (-11) y (3)= -2 (-11) y (-3)= -2
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
REGLAS DE OPERANDOS QUE DIFIEREN DE TIPOS
1. Dos operandos de coma flotante con precisión distintas, el operando menorprecisión se transforma a la precisión del otro y el resultado se expresará conla precisión más alta.
Ejemplo: float y double dará como resultado double.2. Un operando de tipo coma flotante y otro char o int (short int, long int ), el
char/int se convierte a coma flotante. Ejemplo: int y double dará como resultdo double.3. Si no son coma flotante, y uno es long int el otro se transforma en long int. Ejemplo : long int e int dará como resultado long int.4. Si no son coma flotante ni long int, ambos operandos se convertirán en int Ejemplo: short int e int tendrá como resultado int.5. Si uno es unsigned long int , el otro es convertido y el resultado será
unsigned long int.6. Si uno es long int y el otro unsigned int entonces : a) Si unsigned int se puede convertir a long int el resultado será long int. b) Si no ambos serán convertidos a unsigned int e igual será el resultado7. Si uno de los operandos es unsigned int, el otro es convertido y el resultado
será unsigned int.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CONVERSION DEL VALOR RESULTANTE A UN TIPO DE DATO:
Formato: (tipo de dato) expresión
Ejemplo: i=7 (entero) f= 8.5 ( coma flotante)
(i+f) % 4 es inválida. ((int(i+f))% 4 es válida , ya que i+f se convierte a entero y
el resutado es 3.
PRECEDENCIA: ( ) , * / %, +-
Ejemplo: a= 5.2 b=10 c=5 d=2 a + b/c * d a + 10/5 * d a + 2* 2 5.2 + 4 = 9.2
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADORES LOGICOS
Operador Operación
&& and 1&&1=1, 1&&0=0, 0&&---- =0 | | or 0|| 0=0, 0||1=1, 1||--- =1 ! not !0=1 !1=0
Los operandos pueden ser enteros, reales o punteros.
Ejemplo: p=1 y q=0 p&&q = 0 p||q = 1 !p = 0
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADORES DE RELACION
Operador Operación < primer operando menor que el segundo > primer operando mayor que el segundo <= primer operando menor o igual que el segundo >= primer operando mayor o igual que el segundo = = primer operando igual que el segundo ! = primer operando distinto del segundo.
Los operandos pueden ser de tipo entero, real o puntero.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EXPRESIONES BOOLEANAS
Dan como resultado valores lógicos (1,0). Operadores: lógicos y de relación .
Ejemplo: x= 15, y= 18, z= 20
p= x= = y; /* resultado p=0 */
q= (x<y)&&(y<= z) /* resultado q=1 */
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADORES DE ASIGNACIÓN
OPERADORES DE INCREMENTO Y DECREMENTO:
++ Incremento - - Decremento
Ejemplo: x++; incrementa el valor de x en 1
++x; incrementa el valor de x en 1 x= --n; decrementa n en 1 y asigna el resultado a x x= n--; asigna el valor de n a x y luego decrementa en 1
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Operador Operación
= Asignación simple *= Multiplicación más asignación /= División más asignación %= Resto más asignación += Suma más asignación - = Resta más asignación
Ejemplo: i+=2; realiza la operación i=i+2 x *= n-3 realiza la operación x = x*(n-3)
OPERADORES DE ASIGNACIÓN Y OPERACION
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADOR SIZEOF
Devuelve el tamaño del operando en byte. Siempre precede a un operando. El operando puede ser una expresión o un cast ( conversión de tipo). Información útil cuando se transfiere el programa a una computadora diferente o a una
versión del C y asignación dinámica.
Formato: sizeof ( tipo)
Ejemplo: i entera, x de coma flotante, d de doble precisión, c caracter. Salida printf(“int: %d\n”,sizeof i); int: 2 printf(“float: %d\n”,sizeof x); float: 4 printf(“double: %d\n”,sizeof d); double: 8 printf(“char: %d\n”,sizeof c); char: 1
Ejemplo con cast:
Salida printf(“int: %d\n”,sizeof (int)); int: 2 printf(“float: %d\n”,sizeof (float)); float: 4 printf(“double: %d\n”,sizeof (double)); double: 8 printf(“char: %d\n”,sizeof (char)); char: 1
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
OPERADORES MONARIOS
Actúan sobre un solo operando para producir un nuevo valor.
operando función
! negación - números negativos o expresiones ++ incremento -- decremento sizeof devuelve el tamaño de un operando en byte.
Ejemplos: -745 -5E-8 -3*(x+y) ++j --j -0.2 -(x+y)
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Operador Operador ??int main()int main()
{{
int a,b=2,c=3;int a,b=2,c=3;
a= b>0 ? c : c+1a= b>0 ? c : c+1;;
/* Equivalente a/* Equivalente a
if(b>0)if(b>0)
a=c;a=c;
elseelse
a=c+1; */a=c+1; */
}}
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
PRECEDENCIA: categoría operadores asociatividad monarios - ++ -- ! sizeof D ---> I aritméticos * / % I ---> D aritméticos + - I ---> D relacionales < <= > >= I ---> D igualdad = = != I ---> D y lógico && I ---> D o lógico | | I ---> D condicional ?: D ---> I asignación = += -= *= /= %= D ---> I Ejemplo: i=7, f=5.5, c=‘w’ interpretación valor i + f <= 0 falso 0 i >= 6 && c= = ‘w’ cierto 1 c != ‘p’ | | i + f <= 10 cierto 1
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ENTRADA Y SALIDA DE DATOSENTRADA Y SALIDA DE DATOS
Funciones: getchar, putchar, scanf, printf, gets, y Funciones: getchar, putchar, scanf, printf, gets, y puts.puts.
ENTRADA DE UN CARÁCTER……… LA FUNCION: getchar.ENTRADA DE UN CARÁCTER……… LA FUNCION: getchar.• Entrada de carácter uno a uno.Entrada de carácter uno a uno.• Devuelve un carácter leído del dispositivo de entrada Devuelve un carácter leído del dispositivo de entrada
estándar.estándar.• Es parte de la biblioteca estándar. (stdio.h)Es parte de la biblioteca estándar. (stdio.h)
FORMATO:FORMATO:Variable de carácter = getchar();Variable de carácter = getchar();
Ejemplo: Ejemplo: char c;char c; …… …….. c= getchar();c= getchar();
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
SALIDA DE UN CARÁCTER SALIDA DE UN CARÁCTER ……….. LA FUNCION : ……….. LA FUNCION : putcharputchar
• Visualizar un carácter.Visualizar un carácter.• Transmitir un carácter al dispositivo de salida Transmitir un carácter al dispositivo de salida
estándar.estándar.• Es parte de la biblioteca estándar. (stdio.h)Es parte de la biblioteca estándar. (stdio.h)
FORMATO:FORMATO:putchar (variable de putchar (variable de
carácter)carácter)
EJEMPLO:EJEMPLO:char c;char c;
…… ……..putchar (c);putchar (c);
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ENTRADA DE DATOS …. ENTRADA DE DATOS …. LA FUNCIÓN LA FUNCIÓN scanfscanf
• Introducir datos procedentes del dispositivo de entrada Introducir datos procedentes del dispositivo de entrada estándar.estándar.
• Introducir cualquier combinación de valores numéricos, Introducir cualquier combinación de valores numéricos, caracteres sueltos y cadenas de caracteres.caracteres sueltos y cadenas de caracteres.
FORMATO:FORMATO: scanf (cadena de control, arg1, arg2, ……, arg scanf (cadena de control, arg1, arg2, ……, arg n)n)
• Cadena de control: cadena de caracteres que contienes Cadena de control: cadena de caracteres que contienes cierta información sobre el formato de los datos.cierta información sobre el formato de los datos.
• Arg1, arg2,….., arg n: representan los datos. (punteros que Arg1, arg2,….., arg n: representan los datos. (punteros que indican las direcciones de memoria en donde se encuentran indican las direcciones de memoria en donde se encuentran los datos).los datos).
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CARACTERES DE CONVERSIÓNCARACTERES DE CONVERSIÓN
Carácter de conversión Significado
c El dato es un carácter.
d El dato es un entero decimal.
e El dato es un valor en coma flotante.
f El dato es un valor en coma flotante.
g El dato es un valor en coma flotante.
h El dato es un entero corto.
i El dato es un entero decimal, octal o hexadecimal.
o El dato es un entero octal.
s El dato es una cadena de caracteres (carácter nulo al final)
u El dato es un entero decimal sin signo.
x El dato es un entero hexadecimal.
[… ] El dato es una cadena de caracteres que pueden incluir
caracteres de espaciado.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EJEMPLO:EJEMPLO:
#include<stdio.h>#include<stdio.h>main()main(){{char letras [20];char letras [20];int entero;int entero;float coste;float coste;…………scanf(“%s %d %f”, letras, &entero,&coste);scanf(“%s %d %f”, letras, &entero,&coste);}}
EJECUCIÓN:EJECUCIÓN:
velocidad 12345 0.05 ó velocidadvelocidad 12345 0.05 ó velocidad ó velocidad ó velocidad 12345 12345 12345 12345
0.050.05 0.050.05
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
NotaNota: :
• Cada nombre de variable debe ser precedido por un Cada nombre de variable debe ser precedido por un ampersand(&).ampersand(&).
• Los nombres de arrays no deben ser precedidos por &.Los nombres de arrays no deben ser precedidos por &.
• Conversión de caracteres tipo s: cadena que no Conversión de caracteres tipo s: cadena que no incluye espacio en blanco.incluye espacio en blanco.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ENTRADA DE DATOS …. ENTRADA DE DATOS …. LA FUNCIÓN scanfLA FUNCIÓN scanf
Introducir cadena de caracteresIntroducir cadena de caracteresEJEMPLOEJEMPLO::
#include<stdio.h>#include<stdio.h> {{
char linea[80];char linea[80]; … …....
scanf(“%[ ABCDEFGHIJKLOPQRSTUVXZ]”, linea);scanf(“%[ ABCDEFGHIJKLOPQRSTUVXZ]”, linea); }}
EJECUCIÓN:EJECUCIÓN:
FIN DE SEMANAFIN DE SEMANASe le asigna al array linea toda la cadena de caracteres. Observe que se acepta Se le asigna al array linea toda la cadena de caracteres. Observe que se acepta
espacios en blancos, primer carácter la cadena de control[].espacios en blancos, primer carácter la cadena de control[].
Fin de SemanaFin de SemanaSe le asigna al array linea solo la letra FSe le asigna al array linea solo la letra F
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EJEMPLO 2:EJEMPLO 2:
#include<stdio.h> #include<stdio.h> main()main() {{
char linea[80];char linea[80];……....scanf(“%[^\n]”, linea); scanf(“%[^\n]”, linea);
}}
Se leerá una cadena de caracteres de longitud no Se leerá una cadena de caracteres de longitud no determinada determinada
(no más de 79) y se asignará a línea.(no más de 79) y se asignará a línea.
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ESPECIFICACIOINES DE LONGITUD DE CAMPO:ESPECIFICACIOINES DE LONGITUD DE CAMPO:Limita el número de los caracteres especificando una longitud Limita el número de los caracteres especificando una longitud
dedecampo máxima para el dato.campo máxima para el dato.
EJEMPLO:EJEMPLO:
#include<stdio.h>#include<stdio.h>
main()main()
{{
char linea[80];char linea[80];
… …....
scanf(“%3d %3d %3d”, &a, &b, &c); scanf(“%3d %3d %3d”, &a, &b, &c);
}} EJECUCIÓN:
1 2 3 entonces a=1 , b=2, c =3123 456 789 entonces a=123, b=456, c =789123456789 entonces a=123, b=456, c =7891234 5678 9 entonces a=123, b=4, c =567
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ESCRITURA DE DATOS....... FUNCION PRINTF
ESCRIBIR CUALQUIER COMBINACION DE VALORES NUMERICOS,CARACTERES SUELTOS Y CADENAS DE CARACTERES.
FORMATO: PRINTF ( CADENA DE CONTROL, ARG1,ARG2, ... ARGN);
CADENA DE CONTROL: CADENA DE CARACTERES QUE CONTIENENINFORMACION SOBRE EL FORMATO DE SALIDA.
ARG1,ARG2,....ARGN: ARGUMENTOS QUE REPRESENTAN LOS DATOS DESALIDA ( CONSTANTES, VARIABLES SIMPLES, NOMBRES DE ARREGLOS,EXPRESIONES MAS COMPLICADAS).
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
CARACTERES DE CONVERSION
CARACTER SIGNIFICADOc EL DATO ES VISUALIZADO COMO CARACTERd ENTERO DECIMAL CON SIGNOe VALOR EN COMA FLOTANTE CON EXPONENTEf VALOR DE COMA FLOTANTE SIN EXPONENTEg VALOR EN COMA FLOTANTE UTILIZANDO LA CONVERSION TIPO e O TIPO f ,
SIN PUNTO NI CEROS FINALES CUANDO NO ES NECESARIO.i ENTERO CON SIGNO
o ENTERO OCTAL SIN EL CERO INICIALs CADENA DE CARACTERESu ENTERO DECIMAL SIN SIGNOx ENTERO HEXADECIMAL SIN EL PREFIJO X.
EJEMPLO 1: #include <stdio.h>
#include <math.h> main( )
{ float i=2.0, j= 3.0; printf (“%f %f %f %f”, i,j,i+j,sqrt(j));
}
RESULTADO: 2.000000 3.000000 5.000000 1.732051
ESCRITURA DE DATOS....... FUNCION PRINTF
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ESCRITURA DE DATOS....... FUNCION PRINTFEJEMPLO 2: ENTRADA printf (“%f %f\n”,x,y); x = 5000.0 printf (“%e %e”,x,y); y = 0.0025 RESULTADO: 5000.000000 0.002500 5.00000e+03 2.50000e-03
EJEMPLO 3: longitud de campo mínima. ENTRADA printf (“%3d %5d %8d\n\n”,i,i,i); i=12345 printf (“%3f %10f %13f\n\n”,x,x,x); x=345.678 RESULTADO: 12345 12345 12345 345.678000 345.678000 345.678000 EJEMPLO 4: indicadores de uso común. pág. 100 Gottfried. ENTRADA printf (“:%6d %7.0f %10.1e:\n\n ,i,x,y); i=123, x=12.0 printf (“:%-6d %-7.0f %-10.1e:\n\n,i,x,y); y=-3.3 RESULTADO: : 123 12 -3.3e+000: :123 12 -3.3e+000 :
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ENTRADA/SALIDALAS FUNCIONES GETS Y PUTS
FACILITAN LA TRANSFERENCIA DE CADENAS DE CARACTERES. ACEPTAN UN SOLO ARGUMENTO ( CADENA DE CARACTERES). EN CASO DE GETS ENTRA LA CADENA Y TERMINA CON RETURN.
FORMATO: GETS (ARG.); PUTS (ARG.);EJEMPLO: #include <stdio.h> main ( ) { char saludo [15]; gets (saludo); puts (saludo); }
RESULTADO: ENTRA: Buenos dias ENTER SALIDA: Buenos dias
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
Obtener el promedio de tres valores dados Obtener el promedio de tres valores dados por el usuariopor el usuario
ALGORITMOALGORITMO
INICIOINICIO/*DECLARACIONES*//*DECLARACIONES*/ENTEROS : V1,V2,V3ENTEROS : V1,V2,V3REAL: PROMREAL: PROM/*SOLICITA VALORES DE ENTRADA *//*SOLICITA VALORES DE ENTRADA */VISUALIZAR (“ENTRE LOS TRES VALORES “)VISUALIZAR (“ENTRE LOS TRES VALORES “)LEER (“%i%i%i”,V1,V2,V3)LEER (“%i%i%i”,V1,V2,V3)/* CALCULO DEL PROMEDIO *//* CALCULO DEL PROMEDIO */PROM (V1+ V2+ V3)/3PROM (V1+ V2+ V3)/3/*SALIDA DE LOS RESULTADOS *//*SALIDA DE LOS RESULTADOS */VISUALIZAR (“VALOR 1 VALOR 2VISUALIZAR (“VALOR 1 VALOR 2
VALOR 3 PROMEDIO”)VALOR 3 PROMEDIO”)VISUALIZAR (“%i%i%i%f”,V1,V2,V3,PROM)VISUALIZAR (“%i%i%i%f”,V1,V2,V3,PROM)FINFIN
PROGRAMA EN CPROGRAMA EN C#include <stdio.h>#include <stdio.h>main()main(){ { /*Declaraciones*//*Declaraciones*/
int v1,v2,v3;int v1,v2,v3;float prom;float prom;/* Solicita valores de entrada *//* Solicita valores de entrada */printf(“Entre los tres valores”);printf(“Entre los tres valores”);scanf (“%i %i %i”,&v1,&v2,&v3);scanf (“%i %i %i”,&v1,&v2,&v3);/* Calculo del promedio *//* Calculo del promedio */prom = (v1+v2+v3)/3;prom = (v1+v2+v3)/3;/* Salida de resultados *//* Salida de resultados */printf (“\n \t valor1 \t valor2 \t printf (“\n \t valor1 \t valor2 \t valor3 \t Promedio \n”);valor3 \t Promedio \n”);printf (“\t %i \t %i \t %i\t %.2f printf (“\t %i \t %i \t %i\t %.2f ”,v1,v2,v3,prom);”,v1,v2,v3,prom);
}}
EJEMPLOS DE PROGRAMAS EN C
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EJEMPLOS DE PROGRAMAS EN C
1. CALCULO DEL AREA DE UN CIRCULO. #include <stdio.h> /* programa que calculo el area de un circulo */ main ( ) { float radio,area; printf (“Radio es =?”); scanf (“%f”, &radio); area = 3.14159 * radio * radio; printf (“Area = %f”,area); }
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
EJEMPLOS DE PROGRAMAS EN C
#include <stdio.h> main ( ) { char nombre[20]; float nota1,notà2,nota3,media; printf (“Entre su nombre:”); gets (nombre); printf (“Entre las tres calificaciones:”); scanf (“%f %f %f”, ¬a1,¬a2,¬a3); media = (nota1+nota2+nota3)/3; puts (nombre); printf (“Notas: %-5.1f %-5.1f %-5.1f\n”,nota1,nota2,nota3); printf (“Media: %-5.1f\n\n”,media); }
OTRA FORMA DE SOLUCION DEL PROBLEMA ............ printf (“Entre su nombre:”); scanf (“%[^\n]”,nombre); ............ printf (“\n\nNombre: %-s\n\n”,nombre); .............
CALCULO DE PUNTUACION MEDIA DE EXAMENES:
Prof. Dra. ADDYS DE LAMProf. Dra. ADDYS DE LAM
ProgramaPrograma#include <stdio.h>main(){/*Declaracion de variables*//*Declaracion de variables*/int a,b,c;/*Entrada de los valores*//*Entrada de los valores*/printf (“Entre dos valores:”);scanf (“%i %i”, &a, &b);/*Calculo de la suma*//*Calculo de la suma*/c=a+b;/*Salida de resultados*//*Salida de resultados*/printf(“La suma de %i + %i es: %i”, a,b,c);}