GEE 303 Computer Programming: (Lenguaje C)
GEE 303 Computer Programming: (Lenguaje C)
RICARDO TRIANA
(Lenguaje C)
INDICE INTRODUCCION (1) MARCO TEORICO (2) Historia (2.1) El C de Kernighan y Ritchie (2.2) Quien es Deniss Ritchie? (2.3) Quien es Ken Thompson? (2.4) Filosofia de Programacin (2.5) Estructura de un programa en C (2.6) Pros del lenguaje C (2.7) Contras del lenguaje C (2.8) PERFORMANCE REQUIREMENTS (3) (3.1) *Write getfloat, the floating-point analog of getint. What type does getfloat return as its function value? (3.2) *Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s . Use a switch . Write a function for the other direction as well, converting escape sequences into the real characters. (3.3) *Write a program that converts upper case to lower or lower case to upper, depending on the name it is invoked with, as found in argv[0]. (3.4) *A function called abs_val that returns int and takes an int argument. It returns the absolute value of its argument, by negating it if it is negative. A function called output that takes a single character argument and sends it to the program output with putchar. It will remember the current line number and column number reached on the output devicethe only values passed to the function are guaranteed to be alphanumeric, punctuation, space and newline characters. (3.5) *Construct a program to test output, where that function is in a separate file from the functions that are used to test it. In the same file as output will be two functions called current_line and current_column which return the values of the line and column counters. Ensure that those counters are made accessible only from the file that contains them. (3.6) *Write and test a recursive function that performs the admittedly dull task of printing a list of numbers from 100 down to 1. On entry to the function it increments a static variable. If the variable has a value below 100, it calls itself again.
(3.7) Then it prints the value of the variable, decrements it and returns. Check that it works. (3.8) *Write functions to calculate the sine and cosine of their input. Choose appropriate types for both argument and return value. The series (given below) can be used to approximate the answer. The function should return when the value of the final term is less than 0.000001 of the current value of the function. CONCLUSIONES (4) BIBLIOGRAFIA (5)
INTRODUCCION (1) A continuacin se presentar el desarrollo del trabajo acadmico para la asignatura CSE 303 de Newport University. Al inicio de este trabajo se presentar un muy "pequeno" marco teorico, donde se explicara de una manera breve que es el lenguaje de programacion C, su historia, se presentarn tambien unas pequenas notas sobre su desarrollo, la historia de sus creadores, estructura, filosofia, y sus pros y contras. Seguidamente se identifican los ejercicios para resolver y sus respectivas soluciones debidamente comentadas. Finalmente, en la bibliografa, se identificarn los diferentes recursos tanto digitales como fisicos utilizados para el desarrollo de este trabajo.
2.6 Estructura de un programa en C La sentencia ms sencilla que se puede escribir en C es la siguiente: main( ) { } Esta sentencia no tiene una funcionalidad especifica,pero contiene la parte ms importante de un programa C, adems es la sentencia ms pequea que se puede escribir y compilar correctamente. En esta sentencia se define la funcin main,que es la que ejecuta el sistema operativo al llamar a un programa C. (*Fuente: The Development of the C Language*. Dennis M. Ritchie. Bell Labs/Lucent Technologies. Murray Hill,NJ 07974 USA) El nombre de una funcin C siempre va seguida de parntesis,tanto si tiene argumentos como si no. La definicin de la funcin est formada por un bloque de sentencias,que esta encerrado entre llaves {}. Un ejemplo de una sentencia ms especfica: #include <stdio.h> main( ) { printf("Hello World!\n"); } Con esta sentencia se puede ver la frase Hello World!. En la primera lnea indica que se tengan en cuenta las funciones y ti pos definidos en la librera stdio (standard input/output). Estas definiciones se encuentran en el fichero header stdio.h. Ahora,en la funcin main se incluye una nica sentencia que llama a la funcin printf. Esta toma como argumento una cadena de caracteres,que se imprimen van encerradas entre dobles comillas " ". El smbolo \n indica un cambio de lnea. (*Fuente: The Development of the C Language*. Dennis M. Ritchie. Bell Labs/Lucent Technologies. Murray Hill,NJ 07974 USA)
2.8 Contras del lenguaje C Estas son algunas de las contras que puede tener este lenguaje de programacin,debido a la poca experiencia manejando C,se decidi poner las contras definidas en los diferentes foros de programadores expertos en el lenguaje,asi como en otras fuentes en internet. *Soporte para programacin orientada a objetos,aunque la implementacin original de C++ fue un preproc esador que traduca cdigo fuente de C++ a C. *Encapsulacin. *Funciones anidadas,aunque GCC tiene esta caracterstica como extensin. *Polimorfismo en tiempo de cdigo en forma de sobrecarga,sobrecarga de operadores y slo dispone de un soporte rudimentario para la programacin genrica. *Soporte nativo para programacin multihilo y redes de computadores. *Recoleccin de basura nativa,sin embargo se encuentran a tal efecto bibliotecas como la "libgc" desarrol lada por Sun Microsystems,o el Recolector de basura de Boehm.
#include <stdio.h> #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; /* buffer para ungetch */ /* siguiente posicion libre en el buffer*/
fputs("Introduzca un numero: ", stdout); fflush(stdout); ret = getfloat(&f); if (ret > 0) { printf("Ud introdujo: %f\n", f); } } while (ret > 0); if (ret == EOF) { puts("Stopped by EOF."); } else { puts("Stopped by bad input."); } return 0;
/* TRADUCCION LITERAL: Se copia el string tal string s, conviertiendo caracteres especiales a su secuencia de escape apropiada. La secuencia complete de escape caraters que se usa en el capitulo 2 se utiliza aca, a excepcion de: \? \' \ooo \xhh Se obvivaron porque se pueden escribir directamente en el codigo fuente. */ void escape(char * s, char * t) { int i, j; i = j = 0; while ( t[i] ) {
switch( t[i] ) { case '\n': s[j++] = '\\'; s[j] = 'n'; break; case '\t': s[j++] = '\\'; s[j] = 't'; break; case '\a': s[j++] = '\\'; s[j] = 'a'; break; case '\b': s[j++] = '\\'; s[j] = 'b'; break; case '\f': s[j++] = '\\'; s[j] = 'f'; break; case '\r': s[j++] = '\\'; s[j] = 'r'; break; case '\v': s[j++] = '\\'; s[j] = 'v'; break; case '\\': s[j++] = '\\'; s[j] = '\\'; break; case '\"': s[j++] = '\\'; s[j] = '\"'; break;
} s[j] = t[i];
/*
El caracter null
*/
-Ejercicio 3 Write a program that converts upper case to lower or lower case to upper,depending on the name it is invoked with,as found in argv[0]. #include <stdio.h>?*Estos son varios de los includes*/ #include <stdlib.h> #include <ctype.h> int main(int argc, char **argv) { int (*convcase[2])(int) = {toupper, tolower}; int func; int result = EXIT_SUCCESS; int ch; if(argc > 0) { if(toupper((unsigned char)argv[0][0]) == 'U') { func = 0; } else { func = 1; } while((ch = getchar()) != EOF) { ch = (*convcase[func])((unsigned char)ch); putchar(ch); }
return result;
Esta es otra posibilidad de solucion que vi en internet, mi version, manteniendo los creditos del autor, es esta. /* Write a program that converts upper case to lower case or lower case to upper, depending on the name it is invoked with, as found in argv[0]. Assumptions: The program should read from stdin, until EOF, converting the output to stdout appropriately. The correct outputs should be: Program Name lower upper Output stdin with all caps converted to lower case stdin with all lowercase characters converted to uppercase [anything else] helpful message explaining how to use this
Author : Bryan Williams */ #include <stdio.h>/* Estos son los incliudes*/ #include <stdlib.h> #include <ctype.h> #define SUCCESS #define NO_ARGV0 #define BAD_NAME 0 1 2
int main(int argc, char *argv[]) { int ErrorStatus = SUCCESS; int (*convert)(int c) = NULL; int c = 0; /*Chekear que hayan arguments*/ if(SUCCESS == ErrorStatus)
-Ejercicio 5 A function called output that takes a single character argument and sends it to the program output with putchar. It will remember the current line number and column number reached on the output devicethe only values passed to the function are guaranteed to be alphanumeric,punctuation,space and newline characters. #include <stdio.h>/*includes para stdio.h y stdlib*/ #include <stdlib.h> int curr_line(void), curr_col(void); void output(char); main(){ printf("line %d\n", curr_line()); printf("column %d\n", curr_col()); output('a'); printf("column %d\n", curr_col()); output('\n'); printf("line %d\n", curr_line()); printf("column %d\n", curr_col()); exit(EXIT_SUCCESS);
Ejercicio 6
Ejercicio 7 Write and test a recursive function that performs the admittedly dull task of printing a list of numbers from 100 down to 1. On entry to the function it increments a static variable. If the variable has a value below 100,it calls itself again. Then it prints the value of the variable,decrements it and returns. Check that it works. #include <stdio.h> #include <stdlib.h> void recur(void); main(){ recur();
void recur(void){ static ntimes; ntimes++; if(ntimes < 100) recur(); printf("%d\n", ntimes); ntimes--;
Ejercicio 8 Write functions to calculate the sine and cosine of their input. Choose appropriate types for both argument and return value. The series (given below) can be used to approximate the answer. The function should return when the value of the final term is less than 0.000001 of the current value of the function. sin x = x - pow(x,3)/fact(3) + pow(x,5)/fact(5)... cos x = 1 - pow(x,2)/fact(2) + pow(x,4)/fact(4)... #include <stdio.h>/*includes*/ #include <stdlib.h> #define PI 3.141592 #define INCREMENT (PI/20) #define DELTA .0001 double sine(double), cosine(double); static unsigned int fact(unsigned int n); static double pow(double x, unsigned int n); main(){ double arg = 0; for(arg = 0; arg <= PI; arg += INCREMENT){ printf("value %f\tsine %f\tcosine %f\n", arg, sine(arg), cosine(arg)); } exit(EXIT_SUCCESS);
static unsigned int fact(unsigned int n){ unsigned int answer; answer = 1;
static double pow(double x, unsigned int n){ double answer; answer = 1; while(n){ answer *= x; n--; } return(answer);
double sine(double x){ double difference, thisval, lastval; unsigned int term; int sign; sign = -1; term = 3; thisval = x; do{ lastval = thisval; thisval = lastval + pow(x, term)/fact(term) * sign; term += 2; sign = -sign; difference = thisval - lastval; if(difference < 0) difference = -difference; }while(difference > DELTA && term < 16); } return(thisval);
double cosine(double x){ double difference, thisval, lastval; unsigned int term; int sign; sign = -1; term = 2;
* sign;
CONCLUSIONES (4)
Estas son algunas de las conclusiones definitivas para este trabajo acadmico,cabe recalcar que debido a la poca experiencia manejando C,las conclusiones careceran de peso en cuanto a la parte puramente ejecucional del lenguaje. 1. Es un lenguaje flexible que permite al programador verstatilidad de estilos. Uno de los estilos ms empleados es el estructurado "no llevado al extremo". 2. Un conjunto reducido de palabras clave o keywords. Esto es muy importante ya que permite una mani pulacion efectiva del lenguaje de una manera mas rapida y depurada,a comparacin de otros lenguajes de programacin que requieren una biblioteca de palabras clave extensa. 3. Ti pos de datos agregados (struct) que permiten que los datos relacionados (como por ejemplo si un empleado,que tiene un id,un nombre y un salario) se combinen y se puedan mani pular como un todo (en una nica variable "empleado"). 4. Es un lenguaje ligeramente antiguo,a comparacion de otros lenguajes que utilizan integracion directa con ambientes web,utilizandio bibliotecas especificas para cumplir diferentes funciones. 5. Uns falencia de C es no tener un mtodo de encapsulacin.Existen mtodos de encapsulacin con C pero no son nativos del lenguaje. 6. C es un lenguaje utilizado con exito para desarrolo de sistemas operativos. 7. C es un lenguaje muy bsico pero que cumple con las expetativas. 8. Para sintetizar "C es un lenguaje de programacin de propsito general que ofrece una sintaxis muy breve,un control de flujo y estructuras sencillas y un buen conjunto de operadores. C es un lenguaje pequeo,sencillo y no est especializado en ningn ti po de aplicacin. C es un lenguaje relativamente potente,que tiene un campo de aplicacin ilimitado y que puede ser aprendido en un tiempo muy corto."
BIBLIOGRAFIA (5)
1. The C Book,second edition by Mike Banahan,Declan Brady and Mark Doran,originally published by Addison Wesley in 1991. 2. Curso de Lenguaje "C". Angel Sabas. Centro de Calculo universidad de Zaragoza. Ener0 1991. http://www.monografias.com/trabajos4/lenguajec/lenguajec.shtml 3. Introduccion a la Programacion en C. Marco A. Pena Basurto,Jose M Cela Espin. Primera edicion Septiembre de 2000. Edisions de la Universitat Politecnica de Catalunya,SL. 4. Estndar Internacional ISO/IEC 9899:TC3 http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf 5. Curso Onlinde de Lenguaje C. http://www.carlospes.com/curso_de_lenguaje_c/