Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Laboratorio del jueves 19 de junio del 2014 1. Ejemplo de punteros a enteros
#include
#include int main() int main() { int int *p, *p, a=10; p=&a; printf("\n printf("\n valores p=%d a%d ",p,a); " ,p,a); printf("\n printf("\n direcciones p=%d a%d ",&p,&a); " ,&p,&a); printf("\n printf("\n lo apuntado de *p%d ",*p); " ,*p); getch(); } 2. Punteros a números númer os reales
#include #include int main() int main() { float float *p, *p, a=10; p=&a; printf("\n printf("\n valores p=%d a%f ",p,a); " ,p,a); printf("\n printf("\n direcciones p=%d a%d ",&p,&a); " ,&p,&a); printf("\n printf("\n lo apuntado de *p%f ",*p); " ,*p); getch(); } 3. Punteros a letras
#include #include int main() { char char *p, a='A'; p=&a; printf("\n valores p=%d a%c ",p,a); printf("\n direcciones p=%d a%d ",&p,&a); printf("\n lo apuntado de *p%c ",*p); getch(); } 4. Punteros y arreglos
// punteros y arreglos #include #include
-1-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
const int int n=5; n=5; int main() int main() { int int *p,fila; *p,fila; int A[5]={10,20,30,40,50}; A[5]={10,20,30,40,50}; p=&A[0]; printf("\n printf("\n valores p=%d a%d ",p,A); " ,p,A); printf("\n printf("\n direcciones p=%d a%d ",&p,&A); " ,&p,&A); printf("\n printf("\n lo apuntado de *p%d ",*p); " ,*p); // imprimiendo usando arreglos for (fila=0;fila
Punteros de arreglo de números reales
// punteros y arreglos #include #include const int int n=5; n=5; int main() int main() {float float *p; *p; int int fila; fila; float A[5]={10,20,30,40,50}; A[5]={10,20,30,40,50}; p=&A[0]; printf("\n printf("\n valores p=%d a%d ",p,A); " ,p,A); printf("\n printf("\n direcciones p=%d a%d ",&p,&A); " ,&p,&A); printf("\n printf("\n lo apuntado de *p%f ",*p); " ,*p); // imprimiendo usando arreglos for (fila=0;fila
// punteros y arreglos #include #include const int int n=5; n=5; int main() int main() {double double *p; *p; int fila; int fila; double A[5]={10,20,30,40,50}; A[5]={10,20,30,40,50}; p=&A[0]; printf("\n printf("\n valores p=%d a%d ",p,A); " ,p,A); printf("\n printf("\n direcciones p=%d a%d ",&p,&A); " ,&p,&A); printf("\n printf("\n lo apuntado de *p%f ",*p); " ,*p); // imprimiendo usando arreglos for (fila=0;fila
-2-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
printf("\n printf("\n usando punteros *****" ); for (fila=0;fila
// punteros y arreglos #include #include const int int n=5; n=5; int main() int main() {char *p; *p; int fila; int fila; char A[5]={'H' A[5]={'H',,'O' 'O',,'L' 'L',,'A' 'A',,'\0' '\0'}; }; p=&A[0]; printf("\n printf("\n valores p=%d a%d ",p,A); " ,p,A); printf("\n printf("\n direcciones p=%d a%d ",&p,&A); " ,&p,&A); printf("\n printf("\n lo apuntado de *p%c ",*p); " ,*p); // imprimiendo usando arreglos for (fila=0;fila
// punteros y arreglos #include #include int largoCadena( int largoCadena( char *S) *S) {int int col=0; col=0; for ( ( col=0;*(S+col)!= col=0;*(S+col)!='\0' '\0';col++) ;col++) printf(" printf(" %c ", ", *(S+col)); return col; return col; } int main() int main() {char *p; *p; int fila,nletras; int fila,nletras; //char A[5]={'H','O','L','A','\0'}; p=new p=new char [5]; [5]; printf("\n printf("\n ingrese cadena "); " ); scanf("%s" scanf("%s",p); ,p); printf("\n printf("\n la cadena ingresada es %s", %s" , p); nletras=largoCadena(p); printf("\n printf("\n cantidad de letras %d",nletras); %d" ,nletras); //printf("\n usando punteros *****"); for (fila=0;fila
-3-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
getch(); } 9. Ingrese su nombre con arreglos
#include #include int main() {char nombre[20]; printf("\n Ingrese nombre "); scanf("%s",&nombre); printf("\n hola %s ",nombre); getch(); } 10. . Ingrese su nombre con punteros
#include #include int main() {char *nombre; nombre= new char [2000]; printf("\n Ingrese nombre "); scanf("%s",nombre); printf("\n hola %s ",nombre); getch(); }
ARCHIVOS 11. Ingrese su nombre y grabe en un archivo usando punteros
#include #include int main() { FILE *p; char *nombre; p=fopen("E:\\datos\\archivo1.txt","w"); nombre= new char [2000]; printf("\n Ingrese nombre "); scanf("%s",nombre); fprintf(p,"\n hola %s ",nombre); fclose(p); getch(); }
-4-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
11. grabe el contenido de un vector
#include #include int main() { FILE *p; int fila,n=10; char *nombrearchivo="E:\\datos\\numeros.txt"; int A[10]={1,2,3,4,5,6,7,8,9,10}; p=fopen(nombrearchivo, "w"); for (fila=0;fila
#include #include n const int maxfilas=10,maxcol=10; void Ingresar( int A[][maxcol],int nf, int nc) {int fila,col; for (fila=0;fila
-5-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include n const int maxfilas=10,maxcol=10; void Ingresar( int A[][maxcol],int nf, int nc) {int fila,col; for (fila=0;fila
-6-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
14 Grabar con delimitadores
#include #include n const int maxfilas=10,maxcol=10; void Ingresar( int A[][maxcol],int nf, int nc) {int fila,col; for (fila=0;fila
-7-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include #include float f( float x, float y) { return sin(x*x+y*y)/(x*x+y*y);} int main() { FILE *p; char *Nombre="E:\\jueves19\\funcion.txt"; p=fopen(Nombre, "w"); float x ,y,z,dy=0.5,dx=0.5; for (y=-4 ;y<=4;y =y+dy) {fprintf(p,"\n"); for (x=-4 ;x<=4;x =x+dx) { z= f(x,y); fprintf(p," %8.2f \t",z); } } fclose(p); printf("archivo %s grabado",Nombre); getch(); } 16.Grabar añadir y un archivo de texto
//ARCHIVOS #include #include int main() {char nombre[20]; FILE *p; char NombreArchivo[40]= "E:\\JUEVES19\\texto1.txt"; p=fopen(NombreArchivo, "w"); fprintf(p,"\n Este es un ejemplo de archivo del texto" ); fprintf(p,"\n agregamos nueva linea y cerramos"); fclose(p); printf("\n el archivo %s ha sido grabado ",NombreArchivo); //// añadimos al archivo p=fopen(NombreArchivo, "a"); fprintf (p,"\n el archivo a sido abierto para añadir" ); fprintf (p,"\n Añadimos otra linea y FIN"); fclose(p);
-8-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
printf("\n el archivo %s ha añadido " ,NombreArchivo); getch(); } 17 Leer cualquier archivo de texto usando arreglos
#include #include const int limite =500; int ne,i ; char cadena[limite]; void MostrarCadena(char cadena[], int ne) { for (i=0;i< ne;i++) printf("%c",cadena[i]); } void recuperar( char cadena[], int &ne) { FILE *p; int i; if (( p= fopen("E:\\datos\\programa.txt","r")) ==0) printf("\n No existe ese archivo \n"); else { i=0; while(!feof(p)) { fscanf(p,"%c",&cadena[i]); i++; } } fclose(p); printf("\n el archivo ha sido recuperado y es\n "); ne=i; } int main() { recuperar(cadena,ne); MostrarCadena(cadena ,ne); getch(); } 17 Leer cualquier archivo de texto usando punteros
#include #include #include char *cadena;
-9-
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 10 -
void MostrarCadena( int ne) { for (int i=0;i< ne;i++) printf("%c",*(cadena+i)); } void recuperar( int &ne) { FILE *p; int i; //char *s=cadena; char car; if (( p= fopen("E:\\DATOS\\PROGRAMA.txt","r")) ==0) printf("\n No existe ese archivo \n"); else { i=0; while(!feof(p)) { cadena= (char *) realloc (cadena,i+1); fscanf(p,"%c",&car); *(cadena+i)=car; i++; }} fclose(p); printf("\n el archivo ha sido recuperado y es\n "); ne=i; } int main() { int ne; cadena= (char *)malloc (sizeof (char ) ); recuperar(ne); MostrarCadena(ne); free(cadena); getch(); } 18. recuperar un archivo de texto Convertirlo a mayúsculas y volverlo a grabar
#include #include #include char *cadena; void MostrarCadena( int ne) { for (int i=0;i< ne;i++) printf("%c",*(cadena+i)); } void GrabarMayuscula( int ne) { FILE *p1; int i; char *destino="E:\\DATOS\\Destino.txt",letra; p1=fopen(destino,"w"); for (int i=0;i< ne;i++) { letra=*(cadena+i); if ( letra >=97 && letra<=122) letra=letra-32; fprintf(p1,"%c",letra); } fclose(p1); printf("\n archivo %s grabado satisfactoriamente" ,destino); } void recuperar( int &ne) { FILE *p; int i;
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 11 -
char *Nombre="E:\\DATOS\\PROGRAMA.txt",car; if (( p= fopen(Nombre,"r")) ==0) printf("\n No existe ese archivo \n"); else { i=0; while(!feof(p)) { cadena= (char *) realloc (cadena,i+1); fscanf(p,"%c",&car); *(cadena+i)=car; i++; } } fclose(p); printf("\n el archivo %s ha sido recuperado y es\n ",Nombre); ne=i; } int main() { int ne; cadena= (char *)malloc (sizeof (char ) ); recuperar(ne); MostrarCadena(ne); GrabarMayuscula(ne); free(cadena); getch(); }
LABORATORIO DE LENGUAJE DE PROGRAMACION JUEVES 26 DE JUNIO DEL 2014 1Hallar los valores de la función f(x,y) = sin(x*x+y*y)/(x*x+y*y);
X= -4,-4.5,-4,…. 3.5,4 Y= -4,-4.5,-4,…. 3.5,4
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 12 -
#include #include #include float f( float x, float y) { return sin(x*x+y*y)/(x*x+y*y); } int main() {float x, y,lix=-2,lsx=2,liy=-4,lsy=4,dx=0.5,dy=0.5,z; for (y=liy;y<=lsy;y=y+dy) {printf("\n"); for (x=lix;x<=lsx;x=x+dx) {z=f(x,y); printf("%8.2f",z); } } getch(); } 2. Realizar lo mismo pero que grabe en un archivo de texto con delimitadores para Excel
// ******* programa principal #include #include #include float f( float x, float y) { return sin(x*x+y*y)/(x*x+y*y); } int main() {FILE *p; char Nombrearchivo[50]="E:\\datos1\\funcion3d.txt"; p=fopen(Nombrearchivo, "w"); float x, y,lix=-2,lsx=2,liy=-4,lsy=4,dx=0.5,dy=0.5,z; for (y=liy;y<=lsy;y=y+dy) {fprintf(p,"\n"); for (x=lix;x<=lsx;x=x+dx) {z=f(x,y); fprintf(p,"%8.2f\t",z); } } fclose(p); printf("\n el archivo %s a sido grabado",Nombrearchivo); getch(); }
3. .Recuperar una matriz Generar números aleatorios en Excel
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include const int maxcol=10,maxfilas=10; void MostrarMatriz(int A[][maxcol],int nf, int nc) { int fila,col; for (fila=0;fila
- 13 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include const int maxcol=10,maxfilas=10; void recuperarMatriz(float A[][maxcol], int nf,int nc) { FILE *p; int fila,col; char Nombrearchivo[50]="E:\\datos1\\reales5x5.txt"; p=fopen(Nombrearchivo, "r"); for (fila=0;fila
a) Recuperar los puntos b) Mostrar los puntos recuperado c) Unir esos puntos de acuerdo a una matriz de relaciones
- 14 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
const int maxcol=10,maxfilas=10; void recuperarMatriz(char NombreArchivo[], float A[][maxcol],int nf,int nc) { FILE *p; int fila,col; p=fopen(NombreArchivo, "r"); for (fila=0;fila
- 15 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
} } } void linea(float x1,float y1,float x2,float y2) { int i,vel=10; float mayor,ancho,alto,partex,partey,px,py,dx,dy; ancho=fabs(x2-x1); alto=fabs(y2-y1); if (x1<=x2)dx=1;else dx=-1; if (y1<=y2)dy=1;else dy=-1; if (ancho>alto)mayor=ancho;else mayor=alto; partex=ancho/mayor; partey=alto/mayor; for (i=0;i<=mayor;i++) { px=i*partex*dx; py=i*partey*dy; gotoxy(x1+px,y1+py); printf("*"); // Sleep(vel); } } void MostrarPuntos( float A[][maxcol],int nf) { int fila; for (fila=0;fila
#include #include #include #include #include "E:\Datos1\milib.h" #include "calculos.h" int main() { float A[maxfilas][maxcol]; int Relaciones[maxfilas][maxcol]; int nf=5,nc=5; recuperarMatriz( "E:\\datos1\\pueblos5.txt",A,nf,nc); recuperarMatrizEntera("E:\\datos1\\relaciones5x5.txt",Relaciones,nf,nc); textcolor(0,12);
- 16 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
UnirRelaciones( A,Relaciones,nf,nc); textcolor(0,14); MostrarPuntos(A,nf); getch(); } 6 Recuperar cualquier archivo de texto
//*** calculos.h const int limite =1000; int ne,i ; char cadena[limite]; void MostrarCadena(char cadena[], int ne) { for (i=0;i< ne;i++) printf("%c",cadena[i]); } void recuperar( char cadena[], int &ne) { FILE *p; int i; if (( p= fopen("E:\\datos1\\archivo3.txt","r")) ==0) printf("\n No existe ese archivo \n"); else { i=0; while(!feof(p)) { fscanf(p,"%c",&cadena[i]); i++; } } fclose(p); printf("\n el archivo ha sido recuperado y es\n "); ne=i; } Programa principal
#include #include #include "calculos.h" int main() { recuperar(cadena,ne); MostrarCadena(cadena ,ne); getch(); }
- 17 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
7. Tarea. Ingresar un cadena de texto Grabarlo y mostrar mostrar los grabado
// ******* programa principal #include #include const int limite =1000; int ne,i int ne,i ; char cadena[limi char cadena[limite]; te]; void MostrarCadena( MostrarCadena(char char cadena[], cadena[], int int ne) ne) { for (i=0;i< (i=0;i< ne;i++) printf("%c" printf("%c",cadena[i]); ,cadena[i]); } void G void GrabarCadena rabarCadena((char cadena[], cadena[], int int ne) ne) { FILE *p; p=fopen("E:\\datos1\\texto1.txt" p=fopen( "E:\\datos1\\texto1.txt",,"w" "w"); ); for (i=0;i< (i=0;i< ne;i++) fprintf(p,"%c" fprintf(p,"%c",cadena[i]); ,cadena[i]); fclose(p); } void recuperar( void recuperar( char cadena[], cadena[], int int &ne) &ne) { FILE *p; int i; int i; if (( (( p= fopen("E:\\datos1\\texto1.txt" fopen("E:\\datos1\\texto1.txt",,"r" "r")) )) ==0) printf("\n printf("\n No existe ese archivo \n"); \n" ); else { i=0; while(!feof(p)) while (!feof(p)) { fscanf(p,"%c" fscanf(p,"%c",&cadena[i]); ,&cadena[i]); i++; } } fclose(p); printf("\n printf("\n el archivo ha sido recuperado y es\n "); "); ne=i; } void Ingresar( char cadena[], void Ingresar( cadena[], int int &ne) &ne) { char car; car; int i; int i; fflush( stdin ); for (i=0;i
- 18 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
} } int main() int main() { printf("\n printf("\n ingrese texto enter para terminar" t erminar"); ); Ingresar(cadena,ne); GrabarCadena(cadena, ne); printf(" printf(" \n recuperado recuperado""); recuperar(cadena,ne); MostrarCadena(cadena MostrarCadena(cadena ,ne); getch(); } Prácticas de laboratorio del jueves 03 de julio del 2014 Clases y objetos
// ***circulo .h #include #include class Circulo class Circulo { float float radio,area; radio,area; int nro; int nro; public:: void public void Ingresar(); Ingresar(); void Calcular(); void Calcular(); void MostrarValores(); MostrarValores(); }; void Circulo::Ingresar() Circulo::Ingresar() {printf("\n {printf("\n ingrese radio"); radio" ); scanf("%f" scanf("%f",&radio); ,&radio); } void Circulo::Calcular() Circulo::Calcular() { area= 3.1416*radio*radio;} 3.1416*radio*radio;} void Circulo::MostrarValores() Circulo::MostrarValores() { printf("\n printf("\n radio %f area = %f ", radio,area);} radio,area);} int main() int main() { Circulo objeto1, objeto2; objeto1.Ingresar objeto1.Ingresar (); objeto1.Calcular(); objeto1.MostrarValores(); getch(); }
Con dos objetos
#include
- 19 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include class Circulo class Circulo { float float radio,area; radio,area; int nro; int nro; public:: void public void Ingresar(); Ingresar(); void Calcular(); void Calcular(); void MostrarValores(); MostrarValores(); }; void Circulo::Ingresar() Circulo::Ingresar() {printf("\n {printf("\n ingrese radio"); radio" ); scanf("%f" scanf("%f",&radio); ,&radio); } void Circulo::Calcular() Circulo::Calcular() { area= 3.1416*radio*radio;} 3.1416*radio*radio;} void Circulo::MostrarValores() Circulo::MostrarValores() { printf("\n printf("\n radio %f area = %f ", radio,area);} radio,area);} int main() int main() { Circulo objeto1, objeto2; objeto1.Ingresar objeto1.Ingresar (); objeto1.Calcular(); objeto1.MostrarValores(); objeto2.Ingresar objeto2.Ingresar (); objeto2.Calcular objeto2.Calcular (); objeto2.MostrarValores(); getch(); } CONSTRUCTORES Y DESTRUCTORES
class Circulo class Circulo { float float radio,area; radio,area; int nro; int nro; public:: Circulo(int public Circulo( int,, float float); ); ~Circulo(); void Ingresar(); void Ingresar(); void Calcular(); void Calcular(); void MostrarValores(); MostrarValores(); void Asignar( void Asignar(int int,, float float); ); }; void Circulo:: void Circulo:: Asignar(int Asignar( int n1=1, n1=1, float float r2=2) r2=2) { nro=n1; radio=r2; } Circulo::Circulo(int Circulo::Circulo(int n1=1, n1=1,float float r1=10) {nro=n1; radio=r1; printf("\n printf("\n Objeto %d construido con radio %f",nro,radio); %f" ,nro,radio); } Circulo::~Circulo() { printf("\n printf("\n Objeto %d destruido con radio %f" ,nro,radio); } void Circulo::Ingresar() Circulo::Ingresar() {printf("\n {printf("\n ingrese radio"); radio" ); scanf("%f" scanf("%f",&radio); ,&radio); } void Circulo::Calcular() Circulo::Calcular() { area= 3.1416*radio*radio;} 3.1416*radio*radio;} void Circulo::MostrarValores() Circulo::MostrarValores()
- 20 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
{ printf("\n radio %f area = %f ", radio,area);} Programa principal
#include #include const float pi=3.1416; #include "circulo2.h" void funcion() { Circulo objeto1, objeto2(2),objeto3(3,4); objeto1.Calcular(); objeto1.MostrarValores(); objeto2.Calcular (); objeto2.MostrarValores (); objeto3.Calcular (); objeto3.MostrarValores(); } int main() { funcion(); getch(); } Arreglo de objetos
#include #include const float pi=3.1416; #include "circulo2.h" void funcion() { int i,n=10; Circulo A[10]; for (i=0;i
#include #include const float pi=3.1416; #include "circulo2.h" void funcion() { int i,n=5,nroobjeto; Circulo A[5]; for (i=0;i
- 21 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
A[nroobjeto].Calcular (); A[nroobjeto].MostrarValores (); } int main() { funcion(); getch(); } PUNTERO A OBJETOS
#include #include const float pi=3.1416; #include "circulo2.h" void funcion() { int i,n=5,nroobjeto; Circulo *A; A= new Circulo(1,2); A->Calcular(); A->MostrarValores (); } int main() { funcion(); getch(); } Objetos con punteros
#include #include const float pi=3.1416; #include "circulo2.h" void funcion() { int i,n=5,nroobjeto; Circulo *A; A= new Circulo [n]; for (i=0;iAsignar(i+1,i*2); (A+i)->Calcular (); (A+i)->MostrarValores(); } delete [] A; } int main() { funcion(); getch(); } Pase de paramteros de objetos Parametros por valor
- 22 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include const float pi=3.1416; #include "circulo2.h" void Modificar( Circulo objeto) { printf("\n ingrese valores "); objeto.Ingresar (); objeto.Calcular (); objeto.MostrarValores(); } int main() { Circulo A(1,3); printf("\n **ANTES"); A.Calcular (); A.MostrarValores(); Modificar(A); printf("\n ** DESPUES"); A.Calcular(); A.MostrarValores(); getch(); } Pase de parametros por referencia
#include #include const float pi=3.1416; #include "circulo2.h" void Modificar( Circulo &objeto) { printf("\n ingrese valores "); objeto.Ingresar (); objeto.Calcular (); objeto.MostrarValores(); } int main() { Circulo A(1,3); printf("\n **ANTES"); A.Calcular (); A.MostrarValores(); Modificar(A); printf("\n ** DESPUES"); A.Calcular(); A.MostrarValores(); getch(); }
- 23 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Pase de parámetros por referencia con punteros
#include #include const float pi=3.1416; #include "circulo2.h" void Modificar( Circulo *objeto) { printf("\n ingrese valores "); objeto->Ingresar (); objeto->Calcular (); objeto->MostrarValores(); } int main() { Circulo A(1,3); printf("\n **ANTES"); A.Calcular (); A.MostrarValores(); Modificar(&A); printf("\n ** DESPUES"); A.Calcular(); A.MostrarValores(); getch(); } Diagrama de clases
JERARQUIA
- 24 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Derivar la clases cilndro de la clase Circulo
class Circulo {protected: float radio,area; int nro; public: Circulo(int, float); ~Circulo(); void Ingresar(); void Calcular(); void MostrarValores(); void Asignar(int, float); }; void Circulo:: Asignar(int n1=1, float r2=2) { nro=n1; radio=r2; } Circulo::Circulo(int n1=1,float r1=10) {nro=n1; radio=r1; printf("\n Objeto %d construido con radio %f" ,nro,radio); } Circulo::~Circulo() { printf("\n Objeto %d destruido con radio %f" ,nro,radio); } void Circulo::Ingresar() {printf("\n ingrese nro"); scanf("%d",&nro); printf("\n ingrese radio"); scanf("%f",&radio); } void Circulo::Calcular() { area= 3.1416*radio*radio;} void Circulo::MostrarValores() { printf("\n nro %d radio %f area = %f ", nro,radio,area);}
- 25 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
class Cilindro : public Circulo {protected: float h,volumen; public: void IngresarAltura(); void CalcularVolumen(); void MostraValoresCilindro(); }; void Cilindro::IngresarAltura() {printf("\n ingrese altura"); scanf("%f",&h); } void Cilindro::CalcularVolumen() { area=pi*radio*radio; volumen= area*h; } void Cilindro::MostraValoresCilindro() { printf("\n Nro =%d", nro); printf("\n radio =%f", radio); printf("\n area de la base =%f", area); printf("\n volumn radio =%f", volumen); } #include #include const float pi=3.1416; #include "circulo2.h" int main() { Cilindro B; B.MostrarValores(); B.Ingresar (); B.IngresarAltura(); B.CalcularVolumen(); B.MostraValoresCilindro(); getch(); } Un objeto se puede asignarse a un objeto Una funcion puede devolver objetos
//Programa principal #include #include const float pi=3.1416; #include "clase.h" Circulo Devolver(Circulo objeto1) { objeto1.Asignar(5,20);
- 26 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 27 -
return objeto1; } int main() { Circulo Objeto1,Objeto2; Objeto2=Objeto1; Objeto2.MostrarValores(); Objeto2=Devolver(Objeto1); Objeto2.Calcular (); Objeto2.MostrarValores(); getch(); } Implementar uma clase vector Esa clase modificar en una funcion y retorna el objeto que puede mostrar valores
//Programa principal #include #include class vector { int n, A[20]; public: void AsignarVector( int Vector[],int n); void Mostrar(); }; void vector::AsignarVector( int Vector[],int n1) {n=n1; for (int i=0;i
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
//Programa principal #include #include struct vector { int n, A[20]; }; vector AsignarVector( vector &A1,int V[],int n1) { int i; A1.n =n1; for ( i=0;i
Tres paradigmas de programación anteriores, son: Programación clásica Programación estructurada Programación Orientada al Objeto Programación genérica Programación clasica Calcular el mayor de dos números con programación clásica sin funciones
// programacion clasica #include #include int main() { int n1=10,n2=50,mayor;
- 28 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 29 -
if (n1>n2)mayor=n1;else mayor=n2; printf("\n el mayor de %d y %d es %d",n1,n2,mayor); getch(); } // programacion estructurada #include #include int mayor(int n1, int n2) { int mayor=0; if (n1>n2)mayor=n1; else mayor=n2; return mayor; } int main() { int a=10,b=50; printf("\n el mayor de %d y %d es %d",a,b , mayor(a,b)); getch(); } Intentamos ahora usar la misma funcion pero usando numeros reales
Y se obtiene cualquier valor #include #include int Mayor( int a, int b) { int resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; } int main() { int a= 10, b=50;; float r1=2.3, r2=5.1; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n el mayor de enteros %d ",Mayor(a,b)); printf("\n el mayor de reales es %f ",Mayor(r1,r2)); getch(); } La solución es implementar dos funciones sobrecargadas uno para enteros y otro para reales
#include
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include int Mayor( int a, int b) { int resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; } float Mayor( float a, float b) {float resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; } int main() { int a= 10, b=50;; float r1=2.3, r2=5.1; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n el mayor de enteros %d ",Mayor(a,b)); printf("\n el mayor de reales es %f ",Mayor(r1,r2)); getch(); }
POO
// programacion POO #include #include class Operacion { int a,b,maximo; public: void Asignar( int ,int ); void mayor( ); void VerDatos(); int ObtenerMayor(); }; int Operacion::ObtenerMayor() {return maximo; } void Operacion::VerDatos() { printf("\n %d %d mayor %d",a,b,maximo); } void Operacion::Asignar( int n1=2,int n2=3) { a=n1; b=n2; }; void Operacion::mayor() { if (a>b)maximo=a; else maximo=b; }
- 30 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 31 -
int main() { Operacion Objeto; Objeto.Asignar(2,3); Objeto.mayor(); Objeto.VerDatos (); printf("\n el mayor es *** %d", Objeto.ObtenerMayor()); getch(); } Usando programación genérica
Plantillas de funciones para el caso dos función tanto para mayor d edos enteros o de dos reales #include #include template < typename Tipo> Tipo Mayor ( Tipo a , Tipo b) { Tipo resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; } int main() { int a= 10, b=50;; float r1=2.3, r2=5.1; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n el mayor de enteros %d ",Mayor(a,b)); printf("\n el mayor de reales es %f ",Mayor(r1,r2)); getch(); }
Se puede generalizar esta plantilla para comparar para todo tipo de datos
#include #include template < typename Tipo> Tipo Mayor ( Tipo a , Tipo b) { Tipo resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; }
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
int main() { int a= 10, b=50;; float r1=2.3, r2=5.1; char car1='Z', car2='B'; char cadena1[20]="VERDE", cadena2[20]= "AZUL"; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n el mayor de enteros %d ",Mayor(a,b)); printf("\n el mayor de reales es %f ",Mayor(r1,r2)); printf("\n el mayor de las letras es %c ",Mayor(car1,car2)); printf("\n el mayor de las cadenas %s ",Mayor(cadena1,cadena2)); getch(); }
Elaborar un programa para mostrar cualquier tipo de matrices
#include #include #include #include #include using std::cout; using std::cin ; using std::endl ; const int maxcol =10; template < typename Tipo> void Generar ( Tipo A[][maxcol], int nf,int nc) { int fila,col; int r; for (fila=0;fila void Imprimir ( Tipo1 A[][maxcol] , int nf,int nc) { int fila,col; for (fila=0;fila
- 32 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
int main() { int A[5][maxcol]; float B[10][maxcol]; char C[10][maxcol]; cout<<"matriz de numeros enteros"<
#include #include template < typename xxx> xxx Mayor ( xxx a , xxx b) { xxx resultado=0; if (a>b)resultado=a; else resultado =b; return resultado; } int main() { int a= 10, b=50;; float r1=2.3, r2=5.1; char car1='Z', car2='B'; char cadena1[20]="VERDE", cadena2[20]= "AZUL"; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n el mayor de enteros %d ",Mayor(a,b)); printf("\n el mayor de reales es %f ",Mayor(r1,r2)); printf("\n el mayor de las letras es %c ",Mayor(car1,car2)); printf("\n el mayor de las cadenas %s ",Mayor(cadena1,cadena2)); getch(); } Pregunta 2
#include #include template < typename tipo1> tipo1 suma ( tipo1 a , tipo1 b) { tipo1 resultado; resultado =a+b; return resultado;
- 33 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
} int main() { int a= 10, b=50; float r1=2.3, r2=5.1; char car1='Z', car2='B'; char cadena1[20]="VERDE", cadena2[20]= "AZUL"; printf("\n los numeros enteros son %d %d ",a,b); printf("\n los numeros reales son %f %f ",r1,r2); printf("\n La suma de enteros %d ",suma(a,b)); printf("\n La suma de reales es %f ",suma(r1,r2)); //printf("\n La suma de las letras es %c ",suma(car1,car2)); //printf("\n La suma de las cadenas %s ",suma(cadena1,cadena2)); getch(); } Listar Cualquier tipo de matriz
#include #include #include #include #include using std::cout; using std::cin ; using std::endl ; const int maxcol =10; template < typename Tipo> void Generar ( Tipo A[][maxcol], int nf,int nc) { int fila,col; int r; for (fila=0;fila void Imprimir ( Tipo1 A[][maxcol] , int nf,int nc) { int fila,col; for (fila=0;fila
- 34 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
cout<<"\n matriz de Letras"<
Public Class vehiculo Private Propietario1 As String Private Año1 As Integer Public Property Propietario() As String Get Propietario = Propietario1 End Get Set(ByVal value As String) Propietario1 = value End Set End Property Public Property Año() As Integer Get Año = Año1 End Get Set(ByVal value As Integer ) Año1 = value End Set End Property Public Sub Prender() End Sub Public Sub Apgar() End Sub End Class Public Class Automovil Inherits vehiculo
- 35 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 36 -
Private Tipo1 As String Public Property Tipo() As String Get Tipo = Tipo1 End Get Set(ByVal value As String) Tipo1 = value End Set End Property End Class Public Class Camion Inherits vehiculo Private Carga1 As Integer Public Property Carga() As Integer Get Carga = Carga1 End Get Set(ByVal value As Integer ) Carga1 = value End Set End Property End Class Module Module1 Sub Main() Dim auto1 As vehiculo Dim auto2 As Automovil Dim camion1 As Camion auto1 = New vehiculo() auto2 = New Automovil() camion1 = New Camion() auto1.Año = 2014 auto1.Propietario = "JUAN PEREZ 1" auto2.Año = 2013 auto2.Propietario = "JUAN PEREZ 2" auto2.Tipo = "SEDAN" camion1.Año = 1999 camion1.Propietario = "JUAN PEREZ 3" camion1.Carga = 2000 Console.ForegroundColor = 14 Console.WriteLine( " DATOS DE LA CLASE AUTO1") Console.WriteLine( "AÑO {0} PROPIETARIO {1} ", auto1.Año, auto1.Propietario) Console.ForegroundColor = 15 Console.WriteLine( " DATOS DE LA CLASE AUTO2") Console.WriteLine( "AÑO {0} PROPIETARIO {1} TIPO {2}", auto2.Año, auto2.Propietario, auto2.Tipo) Console.ForegroundColor = 10 Console.WriteLine( " DATOS DE LA CLASE CAMION") Console.WriteLine( "AÑO {0} PROPIETARIO {1} CARGA {2} ", camion1.Año, camion1.Propietario, camion1.Carga) Console.ReadLine()
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
End Sub End Module Modificacion de la clase vehiculo
Public Class vehiculo Private Propietario1 As String Private Año1 As Integer Public Property Propietario() As String Get Propietario = Propietario1 End Get Set(ByVal value As String) Propietario1 = value End Set End Property Public Property Año() As Integer Get Año = Año1 End Get Set(ByVal value As Integer ) Año1 = value End Set End Property Public Sub MostrarDatos()
- 37 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Console.WriteLine( "Año {0} propietario {1}", Año1, Propietario1) End Sub End Class Public Class Automovil Inherits vehiculo Private Tipo1 As String Public Property Tipo() As String Get Tipo = Tipo1 End Get Set(ByVal value As String) Tipo1 = value End Set End Property Public Sub MostrarDatosAuto() Console.WriteLine( "tipo {0} ", Tipo1) End Sub End Class Public Class Camion Inherits vehiculo Private Carga1 As Integer Public Property Carga() As Integer Get Carga = Carga1 End Get Set(ByVal value As Integer ) Carga1 = value End Set End Property Public Sub MostrarDatosCamion() Console.WriteLine( "carga {0} ", Carga1) End Sub End Class Module Module1 Sub Main() Dim auto1 As vehiculo Dim auto2 As Automovil Dim camion1 As Camion auto1 = New vehiculo() auto2 = New Automovil() camion1 = New Camion() auto1.Año = 2014 auto1.Propietario = "JUAN PEREZ 1" auto2.Año = 2013 auto2.Propietario = "JUAN PEREZ 2" auto2.Tipo = "SEDAN" camion1.Año = 1999 camion1.Propietario = "JUAN PEREZ 3" camion1.Carga = 2000 Console.ForegroundColor = 14 Console.WriteLine( " DATOS DE LA CLASE AUTO1")
- 38 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
auto1.MostrarDatos() Console.ForegroundColor = 15 Console.WriteLine( " DATOS DE LA CLASE AUTO2") auto2.MostrarDatos() auto2.MostrarDatosAuto() Console.ForegroundColor = 10 Console.WriteLine( " DATOS DE LA CLASE CAMION") camion1.MostrarDatos() camion1.MostrarDatosCamion() Console.ReadLine() End Sub End Module
Public Class PERSONA Private DN1 As Integer Private Nombre1 As String Private Color1 As Integer Public Property DNI() As Integer Get DNI = DN1 End Get Set(ByVal valor As Integer ) DN1 = valor End Set End Property Public Property Nombre() As String Get Nombre = Nombre1 End Get Set(ByVal value As String) Nombre1 = value End Set End Property Public Property Color() As Integer Get Color = Color1 End Get Set(ByVal value As Integer ) Color1 = value End Set End Property
- 39 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Public Sub MostrarDatos() Console.ForegroundColor = Color1 Console.WriteLine( " dni {0} NOMBRE {1}", DN1, Nombre1) End Sub Public Sub AsignarColor() Console.ForegroundColor = Color1 End Sub End Class Public Class Profesor Inherits PERSONA Private Sueldo1 As Integer Public Property Sueldo() As Integer Get Sueldo = Sueldo1 End Get Set(ByVal value As Integer ) Sueldo1 = value End Set End Property Public Sub MostrarDatosProfesor() Console.WriteLine( " su sueldo es {0}", Sueldo1) End Sub End Class Module Module1
Dim juan As New PERSONA Dim pedro As Profesor Dim lucas As ALUMNO Sub Main() pedro = New Profesor lucas = New ALUMNO juan.DNI = 123456789 juan.Nombre = "JUAN" juan.Color = 14 juan.MostrarDatos() pedro.DNI = 12345666 pedro.Nombre = "PEDRO " pedro.Sueldo = 5000 pedro.Color = 10 pedro.MostrarDatos() pedro.MostrarDatosProfesor() lucas.DNI = 33333 lucas.Color = 9 lucas.Nombre = "LUCAS" lucas.Nota = 13 lucas.MostrarDatos() lucas.MostrarNota() Console.ReadLine() End Sub End Module
- 40 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Public Class PERSONA Private DN1 As Integer Private Nombre1 As String Private Color1 As Integer Public Sub New(Optional ByVal DN2 As Integer = 11111, Optional ByVal NOMBRE2 As String = "SIN NOMBRE", Optional ByVal COLOR2 As Integer = 15) DN1 = DN2 Nombre1 = NOMBRE2 Color1 = COLOR2 End Sub Public Property DNI() As Integer Get DNI = DN1 End Get Set(ByVal valor As Integer ) DN1 = valor End Set End Property Public Property Nombre() As String Get Nombre = Nombre1 End Get Set(ByVal value As String) Nombre1 = value End Set End Property Public Property Color() As Integer Get Color = Color1 End Get Set(ByVal value As Integer ) Color1 = value End Set End Property Public Sub MostrarDatos() Console.ForegroundColor = Color1 Console.WriteLine( " dni {0} NOMBRE {1}", DN1, Nombre1) End Sub Public Sub AsignarColor() Console.ForegroundColor = Color1 End Sub End Class Module Module1
- 41 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
Dim juan As New PERSONA() Dim PEDRO As New PERSONA(4444) Dim LUCAS As New PERSONA(5555, "LUCAS EL EVANGELISTA") Dim MARIA As New PERSONA(777, "MARIA ", 10) Dim JOSE As New ALUMNO() Sub Main() juan.MostrarDatos() PEDRO.MostrarDatos() LUCAS.MostrarDatos() MARIA.MostrarDatos() JOSE.MostrarDatos() Console.ReadLine() End Sub End Module Module Module1
Dim OBJETO As New PERSONA(111, "maria", 10) Sub Main() OBJETO.MostrarDatos() Console.ReadLine() End Sub End Module Arreglo de objetos
Module Module1 Const n As Integer = 3 Dim OBJETO(n) As PERSONA Sub Main() For i = 0 To n - 1 OBJETO(i) = New PERSONA() OBJETO(i).MostrarDatos() Next Console.ReadLine() End Sub End Module
Module Module1 Const n As Integer = 14 Dim OBJETO(n) As PERSONA Sub Main() For i = 0 To n - 1 OBJETO(i) = New PERSONA() OBJETO(i).DNI = i OBJETO(i).Nombre = "nombre " & i
- 42 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
OBJETO(i).Color = i + 1 OBJETO(i).MostrarDatos() Next Console.ReadLine() End Sub End Module
Module Module1 Const n As Integer = 14 Dim nro As Integer Dim dni7 As Integer Dim nombre7 As String Dim color7 As Integer Dim OBJETO(n) As PERSONA Sub Main() For i = 0 To n - 1 OBJETO(i) = New PERSONA() OBJETO(i).DNI = i OBJETO(i).Nombre = "nombre " & i OBJETO(i).Color = i + 1 OBJETO(i).MostrarDatos() Next Console.WriteLine( "ingrese nro de objeto a modificar" ) nro = Console.ReadLine() Console.WriteLine( "ingrese el nuevo dni") dni7 = Console.ReadLine() Console.WriteLine( "ingrese el nuevo nombre") nombre7 = Console.ReadLine() Console.WriteLine( "ingrese el nuevo color") color7 = Console.ReadLine() OBJETO(nro).DNI = dni7 OBJETO(nro).Nombre = nombre7 OBJETO(nro).Color = color7 OBJETO(nro).MostrarDatos() Console.ReadLine() End Sub Juego de pupiletras
- 43 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
const int maxfilas=20; const int maxcol=20; int nf=20,nc=20; char caracter='.'; char A[maxfilas][maxcol]; void IniciarMatriz(int nf, int nc) { int fila,col; for (fila=0; fila
- 44 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
case 8:x=1;y=-1;break; } for (i=0;i
/// ***** clases.h const int maxfilas =24; const int maxcol =78; class Figura {protected: int X[maxcol], Y[maxcol]; int n,colorlinea,colorNro,cx,cy; int A[maxfilas][maxcol]; public: void Asignar(int n, int X1[], int Y1[],int,int ); void Graficar(); void Mostrar(); void linea (float,float,float,float); void iniciar(int); void MostrarMatriz(int cx, int cy); void MostrarPuntos(int cx, int cy); }; void Figura::MostrarPuntos(int cx1,int cy1) { textcolor(0,colorNro); for (int i=0 ;i0)
- 45 -
;
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
{gotoxy(cx+col,cy+fila); printf("%d",A[fila][col]); } } } void Figura::iniciar(int semilla) {int fila,col; for (fila=0;filaalto)mayor=ancho;else mayor=alto; partex=ancho/mayor; partey=alto/mayor; for (i=0;i<=mayor;i++) { px=i*partex*dx; py=i*partey*dy; xcol=int(x1+px); yfila=int(y1+py); A[yfila][xcol]=1; } } // ** programa principal
- 46 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include #include #include #include "E:\\datos\\milib.h" #include "clases.h" int main() { int X[maxcol]={40,60,20}; int Y[maxcol]={1,20,20}; int n=3; Figura objeto; objeto.iniciar (0); objeto.Asignar (3,X,Y,14,9); objeto.Mostrar(); objeto.Graficar (); objeto.MostrarMatriz(1,1); objeto.MostrarPuntos(1,1); getch(); } Rellenar una figura
// clases .h void RecuperarMatriz( char NombreArchivo[], int nf, int nc) {FILE *p; int fila,col; p=fopen(NombreArchivo, "r"); for (fila=0;fila
"e:\\DATOS\\milib.h"
- 47 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
const int maxcol=40, maxfilas=20; const int maximo=40; int nf=20,nc=40,relleno=2,camino=0; int A[maxfilas][maxcol]; int cont =0; #include "Clases.h" int main() { int cx=5,cy=5; RecuperarMatriz( "e:\\datos1\\matriz40x20.txt",nf,nc); getch(); Rellenar(cx,cy,relleno); A[cy][cx]=12; MostrarMatriz(1,1); textcolor(0,15); printf(" cont %d",cont); getch(); getch(); } El mismo programa con clases y objetos
//**figura.h const int maxfilas =24; const int maxcol =78; class Figura {protected: int X[maxcol], Y[maxcol]; int n,colorlinea,colorNro,cx,cy; int nf,nc,cont; int A[maxfilas][maxcol]; public: void Asignar(int n, int X1[], int Y1[],int c1,int c2 ,int nf ,int nc,int cont1); void Graficar(); void Mostrar(); void linea (float,float,float,float); void iniciar(int); void MostrarMatriz(int cx1, int cy1); void MostrarPuntos(int cx1, int cy1); void Rellenar(int cx1, int cy1, int relleno, int camino); void RecuperarMatriz( char NombreArchivo[], int nf, int nc); }; void Figura::RecuperarMatriz( char NombreArchivo[], int nf, int nc) {FILE *p; int fila,col; p=fopen(NombreArchivo,"r"); for (fila=0;fila
- 48 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
void Figura::Rellenar(int cx,int cy, int relleno, int camino) { cont++; if ( A[cy][cx]==camino) {A[cy][cx]=relleno; Rellenar(cx+1,cy,relleno,camino); Rellenar(cx,cy-1,relleno,camino); Rellenar(cx-1,cy,relleno,camino); Rellenar(cx,cy+1,relleno,camino); } } void Figura::MostrarPuntos(int cx1,int cy1) { textcolor(0,colorNro); for (int i=0 ;i
- 49 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
void Figura::linea(float x1,float y1,float x2,float y2) { int i,vel=10; int yfila,xcol; float mayor,ancho,alto,partex,partey,px,py,dx,dy; ancho=fabs(x2-x1); alto=fabs(y2-y1); if (x1<=x2)dx=1;else dx=-1; if (y1<=y2)dy=1;else dy=-1; if (ancho>alto)mayor=ancho;else mayor=alto; partex=ancho/mayor; partey=alto/mayor; for (i=0;i<=mayor;i++) { px=i*partex*dx; py=i*partey*dy; xcol=int(x1+px); yfila=int(y1+py); A[yfila][xcol]=1; } } #include #include #include #include #include #include "e:\\DATOS\\milib.h" #include "figura.h" int main() { int X[maxcol]={40,60,10}; int Y[maxcol]={2,20,20}; int relleno=2, camino=0; int n=3,nf=24,nc=78; Figura objeto; objeto.iniciar (0); objeto.Asignar (3,X,Y,14,9,nf,nc,0); objeto.Graficar (); objeto.MostrarMatriz(1,1); getch(); objeto.Rellenar (40,10,relleno,camino); objeto.MostrarMatriz(1,1); objeto.MostrarPuntos(1,1); textcolor(0,14); gotoxy(40,10); printf("*"); getch(); } Relleno recuperando una figura y usando punteros
- 50 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
#include #include #include #include #include #include "e:\\DATOS\\milib.h" #include "figura.h" int main() { int X[maxcol]={5,40,70,30}; int Y[maxcol]={22,2,22,16}; int relleno=2, camino=0; int n=4,nf=24,nc=78; Figura *objeto; objeto= new Figura; objeto->iniciar (0); objeto->RecuperarMatriz ("e:\\datos1\\matriz78x24.txt",nf,nc); objeto->Asignar (n,X,Y,14,9,nf,nc,0); //objeto.Graficar (); objeto->MostrarMatriz(1,1); //textcolor(0,14); //gotoxy(40,10); printf("*"); getch(); objeto->Rellenar (40,10,relleno,camino); objeto->MostrarMatriz(1,1); //objeto.MostrarPuntos(1,1); textcolor(0,14); gotoxy(40,10); printf("*"); getch(); Buscador
EL mismo ejercio pero en visual basic
Imports System.IO Module Module2 Public Const maxfilas As Integer = 25 Public Const maxcol As Integer = 80 Public M(maxfilas, maxcol) As Integer Class Figura Public X(maxcol) As Integer Public Y(maxcol) As Integer
- 51 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 52 -
Public n, colorlinea, colorNro, cx, cy As Integer Public nf, nc, cont As Integer Public A(maxfilas, maxcol) As Integer Public Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal nf As Integer , ByVal nc As Integer ) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer , col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = Val(subcadena) inicio = pos + 1 Next Next srLector.Close() End Sub Public Sub MostrarMatriz(ByVal cx1 As Integer , ByVal cy1 As Integer ) Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Console.SetCursorPosition(cx1 + col, cy1 + fila) Console.ForegroundColor = A(fila, col) Console.Write("{0}", A(fila, col)) Next Next End Sub Public Sub Rellenar(ByVal cx As Integer , ByVal cy As Integer , ByVal relleno As Integer , ByVal camino As Integer ) cont = cont + 1 If (A(cy, cx) = camino) Then A(cy, cx) = relleno REM //MostrarMatriz(1,1) REM //Sleep(10) Rellenar(cx + 1, cy, relleno, camino) Rellenar(cx, cy - 1, relleno, camino) Rellenar(cx - 1, cy, relleno, camino) Rellenar(cx, cy + 1, relleno, camino) End If End Sub Public Sub MostrarPuntos(ByVal cx1 As Integer , ByVal cy1 As Integer ) Dim i As Integer Console.ForegroundColor = colorNro For i = 0 To n Console.SetCursorPosition(cx1 + X(i), cy1 + Y(i)) Console.ForegroundColor = colorNro
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 53 -
Console.Write("{0}", i) Next Console.SetCursorPosition(cx1 + cx, cy1 + cy) Console.Write("C") End Sub Public Sub iniciar(ByVal semilla As Integer ) Dim fila, col As Integer For fila = 0 To maxfilas - 1 For col = 0 To maxcol - 1 A(fila, col) = semilla Next Next End Sub Public Sub Graficar() Dim i As Integer Console.ForegroundColor = colorlinea For i = 0 To n - 2 linea(X(i), Y(i), X(i + 1), Y(i + 1)) Next linea(X(n - 1), Y(n - 1), X(0), Y(0)) End Sub Public Sub Asignar(ByVal n1 As Integer , ByVal X1() As Integer , ByVal Y1() As Integer , ByVal c1 As Integer , ByVal c2 As Integer , _ ByVal nf1 As Integer , ByVal nc1 As Integer , ByVal cont1 As Integer ) Dim i As Integer cont = cont1 n = n1 nf = nf1 nc = nc1 cx = 0 cy = 0 colorlinea = c1 colorNro = c2 For i = 0 To n - 1 X(i) = X1(i) Y(i) = Y1(i) cx = cx + X(i) cy = cy + Y(i) Next cx = cx / n cy = cy / n End Sub Public Sub Mostrar() Dim i As Integer For i = 0 To n - 1 Console.WriteLine( "{0}{1}{2}", i, X(i), Y(i)) Next End Sub Public Sub linea(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single) Dim i As Integer , vel As Single = 10 Dim mayor, ancho, alto, partex, partey, px, py, dx, dy As Single ancho = Math.Abs(x2 - x1)
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
alto = Math.Abs(y2 - y1) If (x1 <= x2) Then dx = 1 Else : dx = -1 End If If (y1 <= y2) Then dy = 1 Else : dy = -1 End If If (ancho > alto) Then mayor = ancho Else : mayor = alto End If partex = ancho / mayor partey = alto / mayor For i = 0 To CInt(mayor) px = i * partex * dx py = i * partey * dy A(y1 + py, x1 + px) = 1 REM Console.SetCursorPosition(CInt(x1 + px), CInt(y1 + py)) REM Console.WriteLine("*") Next End Sub End Class End Module Module Module1 Sub Main() Dim X() As Integer = {5, 40, 70, 30} Dim Y() As Integer = {22, 2, 22, 16} Dim relleno As Integer = 2, camino As Integer = 0 Dim n As Integer = 4, nf As Integer = 24, nc As Integer = 78 Dim objeto As Figura objeto = New Figura objeto.iniciar(0) objeto.RecuperarMatriz( "e:\datos1\matriz78x24.txt", nf, nc) objeto.Asignar(n, X, Y, 14, 9, nf, nc, 0) REM //objeto.Graficar () objeto.MostrarMatriz(1, 1) Console.ReadLine() objeto.Rellenar(40, 10, relleno, camino) objeto.MostrarMatriz(1, 1) REM //objeto.MostrarPuntos(1,1) Console.ReadLine() End Sub End Module El mismo ejercicio en progrmacion visual
- 54 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 55 -
Codigo del módulo
Module Module1 Public modo As Integer = 0 Public tipoRelleno As Integer = 2 Public entrada = 0 Public Nombrearchivo As String Public Pincel As Pen Public brocha As SolidBrush Public Grafico As Graphics Public Pict1 As Bitmap Const maxfilas As Integer = 500, maxcol As Integer = 500 Public alto As Integer = maxfilas Public ancho As Integer = maxcol Public Rojos(maxfilas, maxcol) As Integer Public Verdes(maxfilas, maxcol) As Integer Public Azules(maxfilas, maxcol) As Integer Public cx As Integer = 10, cy As Integer = 10 Public Tx As Integer = 0 Public ty As Integer = 0 Public nf As Integer = maxfilas, nc As Integer = maxcol Public ColorCamino As Color Public ColorRelleno As Color Public ColorBorde As Color Public ex As Single = 1 Public ey As Single = 1 Public cont As Integer Sub Cuadro(ByVal x1 As Integer , ByVal y1 As Integer , ByVal x2 As Integer , ByVal y2 As Integer , ByVal relleno As Color) Dim fila, col, rojo, verde, azul rojo = relleno.R verde = relleno.G azul = relleno.B For fila = y1 To y2 For col = x1 To x2 Rojos(fila, col) = rojo Verdes(fila, col) = verde Azules(fila, col) = azul Next Next End Sub
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 56 -
Function Contavecinos(ByVal cx As Integer , ByVal cy As Integer , ByVal Colorelleno As Color) As Integer Dim res As Integer = 0 Dim rRojo, rverde, razul As Integer rRojo = ColorRelleno.R rverde = ColorRelleno.G razul = ColorRelleno.B If Rojos(cy, cx + 1) = rRojo And Verdes(cy, cx + 1) = rverde And Azules(cy, cx + 1) = razul Then res = 1 If Rojos(cy - 1, cx) = rRojo And Verdes(cy - 1, cx) = rverde And Azules(cy - 1, cx) = razul Then res = 1 If Rojos(cy, cx - 1) = rRojo And Verdes(cy, cx - 1) = rverde And Azules(cy, cx - 1) = razul Then res = 1 If Rojos(cy + 1, cx) = rRojo And Verdes(cy + 1, cx) = rverde And Azules(cy + 1, cx) = razul Then res = 1 Return res End Function Function Rellenar(ByVal Colorrelleno As Color, ByVal ColorCamino As Color) Dim fila, col As Integer Dim rRojo, rverde, razul As Integer Dim cRojo, cverde, cazul As Integer rRojo = Colorrelleno.R rverde = Colorrelleno.G razul = Colorrelleno.B cRojo = ColorCamino.R cverde = ColorCamino.G cazul = ColorCamino.B Dim res As Integer = 0 cont = cont + 1 Form1.TextBox1.Text = cont Application.DoEvents() For fila = 1 To nf - 1 For col = 1 To nc - 1 If Contavecinos(col, fila, Colorrelleno) = 1 And Rojos(fila, col) = cRojo And Verdes(fila, col) = cverde And Azules(fila, col) = cazul Then Rojos(fila, col) = rRojo Verdes(fila, col) = rverde Azules(fila, col) = razul res = 1 End If Next Next Return res End Function Function RellenarBorde(ByVal Colorrelleno As Color, ByVal ColorBorde As Color) Dim fila, col As Integer Dim rRojo, rverde, razul As Integer Dim bRojo, bverde, bazul As Integer rRojo = Colorrelleno.R rverde = Colorrelleno.G razul = Colorrelleno.B bRojo = ColorBorde.R bverde = ColorBorde.G bazul = ColorBorde.B Dim res As Integer = 0
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 57 -
cont = cont + 1 Form1.TextBox1.Text = cont Application.DoEvents() For fila = 1 To nf - 1 For col = 1 To nc - 1 If Rojos(fila, col) = bRojo And Verdes(fila, col) = bverde And Azules(fila, col) = bazul Then Continue For Else If Contavecinos(col, fila, Colorrelleno) = 1 Then Rojos(fila, col) = rRojo Verdes(fila, col) = rverde Azules(fila, col) = razul res = 1 End If End If Next Next Return res End Function Sub linea(ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As Single, ByVal y2 As Single, ByVal ColorRelleno As Color) Dim i As Integer , vel As Single = 10 Dim mayor, ancho, alto, partex, partey, px, py, dx, dy As Single Dim rellenorojo, rellenoverde, rellenoazul rellenorojo = ColorRelleno.R rellenoverde = ColorRelleno.G rellenoazul = ColorRelleno.B ancho = Math.Abs(x2 - x1) alto = Math.Abs(y2 - y1) If (x1 <= x2) Then dx = 1 Else : dx = -1 End If If (y1 <= y2) Then dy = 1 Else : dy = -1 End If If (ancho > alto) Then mayor = ancho Else : mayor = alto End If If mayor = 0 Then Exit Sub partex = ancho / mayor partey = alto / mayor For i = 0 To CInt(mayor) px = i * partex * dx py = i * partey * dy Rojos(CInt(y1 + py), CInt(x1 + px)) = rellenorojo Verdes(CInt(y1 + py), CInt(x1 + px)) = rellenoverde Azules(CInt(y1 + py), CInt(x1 + px)) = rellenoazul REM Console.SetCursorPosition(CInt(x1 + px), CInt(y1 + py)) REM Console.WriteLine("*") Next End Sub End Module
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 58 -
Codigo del formulario
Imports System.Drawing Imports System.IO Public Class Form1 Dim x1, y1, x2, y2, xini, yini As Integer Dim cx, cy As Integer Sub GrabarDatos() Dim NombreRojo As String Dim NombreVerde As String Dim NombreAzul As String Dim srEscritor As StreamWriter NombreRojo = Nombrearchivo & "Rojo.txt" srEscritor = New StreamWriter(NombreRojo) For fila = 0 To nf - 1 For col = 0 To nc - 1 srEscritor.Write("{0}{1}", Rojos(fila, col), Chr(9)) Next srEscritor.WriteLine() Next srEscritor.Close() NombreVerde = Nombrearchivo & "Verde.txt" srEscritor = New StreamWriter(NombreVerde) For fila = 0 To nf - 1 For col = 0 To nc - 1 srEscritor.Write("{0}{1}", Verdes(fila, col), Chr(9)) Next srEscritor.WriteLine() Next srEscritor.Close() NombreAzul = Nombrearchivo & "Azul.txt" srEscritor = New StreamWriter(NombreAzul) For fila = 0 To nf - 1 For col = 0 To nc - 1 srEscritor.Write("{0}{1}", Azules(fila, col), Chr(9)) Next srEscritor.WriteLine() Next srEscritor.Close() End Sub Sub MostrarMatriz(ByVal cx As Integer , ByVal cy As Integer , ByVal nf As Integer , ByVal nc As Integer ) Dim fila As Integer , col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 brocha.Color = Color.FromArgb(Rojos(fila, col), Verdes(fila, col), Azules(fila, col)) Grafico.FillRectangle(brocha, cx * ex + col * ex, cy * ey + fila * ey, ex, ey) If modo = 2 Then Grafico.DrawRectangle(Pens.Red, cx * ex + col * ex, cy * ey + fila * ey, ex, ey) End If Next Next End Sub Private Sub Graficar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnObtener.Click For fila = 0 To nf - 1
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 59 -
For col = 0 To nc - 1 ColorCamino = Pict1.GetPixel(col, fila) Rojos(fila, col) = ColorCamino.R Verdes(fila, col) = ColorCamino.G Azules(fila, col) = ColorCamino.B Next col Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load PictureBox2.Width = ancho * ex PictureBox2.Height = alto * ey Grafico = PictureBox2.CreateGraphics Pincel = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.Blue) DataGridView1.RowCount = 6 DataGridView1.ColumnCount = 3 DataGridView1.Columns(0).HeaderText = "Propiedad" DataGridView1.Columns(1).HeaderText = "X" DataGridView1.Columns(2).HeaderText = "Y" DataGridView1.Columns(1).Width = 50 DataGridView1.Columns(2).Width = 50 DataGridView1.Rows(0).Cells(0).Value = "Cx,Cy" DataGridView1.Rows(0).Cells(1).Value = cx DataGridView1.Rows(0).Cells(2).Value = cy DataGridView1.Rows(1).Cells(0).Value = "Traslacion" DataGridView1.Rows(1).Cells(1).Value = Tx DataGridView1.Rows(1).Cells(2).Value = ty DataGridView1.Rows(2).Cells(0).Value = "Escalado" DataGridView1.Rows(2).Cells(1).Value = ex DataGridView1.Rows(2).Cells(2).Value = ey DataGridView1.Rows(3).Cells(0).Value = "Modo" DataGridView1.Rows(3).Cells(1).Value = modo DataGridView1.Rows(4).Cells(0).Value = "Tamaño Nc, Nf" DataGridView1.Rows(4).Cells(1).Value = nf DataGridView1.Rows(4).Cells(2).Value = nc DataGridView1.Rows(5).Cells(0).Value = "Tipo de Rellenof" DataGridView1.Rows(5).Cells(1).Value = tipoRelleno End Sub Private Sub btnGrafico_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrafico.Click SaveFileDialog1.ShowDialog() Nombrearchivo = SaveFileDialog1.FileName GrabarDatos() End Sub Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMostrarGrafico.Click MostrarMatriz(Tx, ty, nf, nc) End Sub Private Sub PictureBox2_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox2.MouseDown Dim rRojo, rverde, razul As Integer cx = e.X / ex cy = e.Y / ey
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
ListBox1.Items.Clear() ListBox1.Items.Add(" X " & cx) ListBox1.Items.Add(" Y" & cy) ListBox1.Items.Add(" boton " & e.Button.ToString) ListBox1.Items.Add("rojo" & Rojos(cy, cx)) ListBox1.Items.Add("verde" & Verdes(cy, cx)) ListBox1.Items.Add("azul" & Azules(cy, cx)) DataGridView1.Rows(0).Cells(1).Value = cx DataGridView1.Rows(0).Cells(2).Value = cy ColorCamino = Color.FromArgb(Rojos(cy, cx), Verdes(cy, cx), Azules(cy, cx)) Select Case tipoRelleno Case 0 'dibuja If entrada = 0 Then xini = e.X / ex yini = e.Y / ey x1 = e.X / ex y1 = e.Y / ey x2 = e.X / ex y2 = e.Y / ey entrada = 1 Grafico.DrawRectangle(Pincel, e.X, e.Y, 4, 4) Else x1 = x2 y1 = y2 x2 = e.X / ex y2 = e.Y / ey linea(x1, y1, x2, y2, ColorBorde) Grafico.DrawLine(Pincel, x1, y1, x2, y2) End If If e.Button.ToString = "Right" Then Grafico.DrawLine(Pincel, x2, y2, xini, yini) linea(x2, y2, xini, yini, ColorBorde) entrada = 0 End If Case 1 ' dibuja lo rellenado Dim valor As Integer Rojos(cy, cx) = ColorRelleno.R Verdes(cy, cx) = ColorRelleno.G Azules(cy, cx) = ColorRelleno.B valor = 1 While (valor = 1) valor = RellenarBorde(ColorRelleno, ColorBorde) End While Case 2 ' dibuja mientras Dim valor As Integer Rojos(cy, cx) = ColorRelleno.R Verdes(cy, cx) = ColorRelleno.G Azules(cy, cx) = ColorRelleno.B valor = 1 While (valor = 1) valor = Rellenar(ColorRelleno, ColorCamino) End While End Select MostrarMatriz(Tx, ty, nf, nc) End Sub
- 60 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 61 -
Private Sub btnEscoger_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEscoger.Click ColorDialog1.ShowDialog() ColorRelleno = ColorDialog1.Color btnEscoger.BackColor = ColorRelleno End Sub Private Sub btnCuadro_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCuadro.Click Cuadro(0, 0, nc, nf, Color.Yellow) Cuadro(4, 4, nc - 4, nf - 4, ColorBorde) Cuadro(10, 10, nc - 10, nf - 10, Color.White) MostrarMatriz(0, 0, nf, nc) End Sub Public Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal A(,) As Integer , ByVal nf As Integer , ByVal nc As Integer ) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer , col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) A(fila, col) = Val(subcadena) inicio = pos + 1 Next Next srLector.Close() End Sub Private Sub btnRecuperar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRecuperarRojo.Click OpenFileDialog1.ShowDialog() RecuperarMatriz(OpenFileDialog1.FileName, Rojos, nf, nc) MostrarMatriz(0, 0, nf, nc) End Sub Private Sub BtnRecuperarVerde_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnRecuperarVerde.Click OpenFileDialog1.ShowDialog() RecuperarMatriz(OpenFileDialog1.FileName, Verdes, nf, nc) MostrarMatriz(0, 0, nf, nc) End Sub Private Sub BtnRecuperarAzul_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnRecuperarAzul.Click OpenFileDialog1.ShowDialog() RecuperarMatriz(OpenFileDialog1.FileName, Azules, nf, nc) MostrarMatriz(0, 0, nf, nc) End Sub
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 62 -
Private Sub BtnBorrar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnBorrar.Click Dim fila, col As Integer For fila = 0 To nf For col = 0 To nc Rojos(fila, col) = 0 Verdes(fila, col) = 0 Azules(fila, col) = 0 Next Next MostrarMatriz(0, 0, nf, nc) End Sub Private Sub BtnRecuperarGrafico_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnRecuperarGrafico.Click OpenFileDialog1.ShowDialog() Pict1 = New Bitmap(OpenFileDialog1.FileName) PictureBox1.Load(OpenFileDialog1.FileName) nf = Pict1.Height nc = Pict1.Width DataGridView1.Rows(4).Cells(1).Value = nc DataGridView1.Rows(4).Cells(2).Value = nf BtnIniciarTodo_Click(sender, e) End Sub Private Sub btnGrabar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGrabar.Click SaveFileDialog1.ShowDialog() Dim fila, col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Pict1.SetPixel(col, fila, Color.FromArgb(Rojos(fila, col), Verdes(fila, col), Azules(fila, col))) Next Next PictureBox3.Image = Pict1 PictureBox3.Image.Save(SaveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Bmp) End Sub Private Sub BtnIniciarTodo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnIniciarTodo.Click cx = DataGridView1.Rows(0).Cells(1).Value cy = DataGridView1.Rows(0).Cells(2).Value Tx = DataGridView1.Rows(1).Cells(1).Value ty = DataGridView1.Rows(1).Cells(2).Value ex = DataGridView1.Rows(2).Cells(1).Value ey = DataGridView1.Rows(2).Cells(2).Value modo = DataGridView1.Rows(3).Cells(1).Value nf = DataGridView1.Rows(4).Cells(1).Value nc = DataGridView1.Rows(4).Cells(2).Value tipoRelleno = DataGridView1.Rows(5).Cells(1).Value PictureBox2.Width = nc * ex PictureBox2.Height = nf * ey End Sub Private Sub BtnBorde_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnBorde.Click
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 63 -
ColorDialog1.ShowDialog() ColorBorde = ColorDialog1.Color BtnBorde.BackColor = ColorBorde Pincel.Color = ColorBorde End Sub Private Sub PictureBox2_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) Handles PictureBox2.MouseLeave entrada = 0 End Sub End Class Laboratorio del 17 de julio del 2014 Ejercicio 1 recuperar una matriz de un un archivo de texto
#include #include int nf=4,nc=5; const int maxfilas=10,maxcol=10; int A[maxfilas][maxcol]; int main() { int fila,col; FILE *p; p=fopen("E:\\datos1\\matriz5x4.txt","r"); for ( fila=0;fila
#include #include int nf=4,nc=5; const int maxfilas=10,maxcol=10; int A[maxfilas][maxcol]; void RecuperarMatriz(char nombre[], int A[][maxcol],int nf, int nc) { int fila,col; FILE *p; p=fopen(nombre,"r"); for ( fila=0;fila
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
fclose(p); } void MostrarMatriz(int A[][maxcol],int nf, int nc) { int fila,col; for ( fila=0;fila
// *** header .h void RecuperarMatriz(char nombre[], int A[][maxcol],int nf, int nc) { int fila,col; FILE *p; p=fopen(nombre,"r"); for ( fila=0;fila #include #include #include #include "e:\\DATOS\\milib.h" int nf=4,nc=5; const int maxfilas=10,maxcol=10; int A[maxfilas][maxcol]; #include "Header.h" int main() { int fila,col;
- 64 -
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 65 -
RecuperarMatriz( "E:\\datos1\\matriz5x4.txt",A, nf, nc); MostrarMatriz(A,nf,nc,1,1); MostrarMatriz(A,nf,nc,40,4); getch(); } Ejerciccio ejemplo de progrmacion visual Metodos numericos discretos
Imports System.IO Module Module1 Public maxfilas As Integer = 20 Public maxcol As Integer = 20 Public Matriz(maxfilas, maxcol) As Single Public Area As Single = 0 Public perimetro As Single = 0 Public CentroX As Single = 0 Public CentroY As Single = 0 Public areaLateral As Single = 0 Public VolDisco As Single = 0 Public VolCilindro As Single Public nf As Integer = 8 Public nc As Integer = 3 Public cx As Integer = 200 Public cy As Integer = 200 Public ex As Single = 10 Public ey As Single = 10 Public tx As Integer = 0 Public ty As Integer = 0 Public Nombrearchivo As String Public Pincel As Pen Public brocha As SolidBrush Public Grafico As Graphics Public alto As Integer = maxfilas Public ancho As Integer = maxcol Public ColorFondo As Color Public X(maxfilas) As Single Public Y(maxfilas) As Single Sub GrabarDatos(ByVal NombreArchivo As String, ByVal nf As Integer , ByVal nc As Integer ) Dim srEscritor As StreamWriter srEscritor = New StreamWriter(NombreArchivo) For fila = 0 To nf - 1 For col = 0 To nc - 1 srEscritor.Write("{0}{1}", Matriz(fila, col), Chr(9))
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 66 -
Next srEscritor.WriteLine() Next srEscritor.Close() End Sub Public Sub RecuperarMatriz(ByVal nombrearchivo As String, ByVal nf As Integer , ByVal nc As Integer ) Dim srLector As StreamReader srLector = New StreamReader(nombrearchivo) Dim fila As Integer , col As Integer Dim cadena As String = "" Dim subcadena As String Dim pos As Integer = 0 Dim inicio As Integer = 1 For fila = 0 To nf - 1 cadena = srLector.ReadLine() cadena = cadena & Chr(9) inicio = 1 For col = 0 To nc - 1 pos = InStr(inicio, cadena, Chr(9)) subcadena = Mid(cadena, inicio, pos - inicio) Matriz(fila, col) = Val(subcadena) inicio = pos + 1 Next Next srLector.Close() End Sub Function Trapecial(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer ) As Single Dim at As Single = 0, ap As Single, dx As Single Dim fx1, fx2 As Single Dim i As Integer For i = 0 To np - 2 dx = X(i + 1) - X(i) fx1 = Y(i) fx2 = Y(i + 1) ap = dx * (fx1 + fx2) / 2 at = at + ap Next Return at End Function Function Longitud(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer ) As Single Dim lt, lp, x1, y1, x2, y2 As Single, i As Integer lt = 0 For i = 0 To np - 2 x1 = X(i) x2 = X(i + 1) y1 = Y(i) y2 = Y(i + 1) lp = CSng(Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2))) lt = lt + lp Next Return lt End Function Function SuperficieRevolucion(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer ) As Single Dim dx, R1, r2, alp, alt, g As Single, i As Integer alt = 0
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 67 -
For i = 0 To np - 2 dx = X(i + 1) - X(i) r2 = Y(i) R1 = Y(i + 1) g = CSng(Math.Sqrt(Math.Pow(dx, 2) + Math.Pow((R1 - r2), 2))) alp = CSng(Math.PI * (R1 + r2) * g) alt = alt + alp Next Return alt End Function Function Volumentrapecial(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer ) As Single Dim vt, vp, dx, fx1, fx2, r As Single Dim i As Integer vt = 0 For i = 0 To np - 1 dx = X(i + 1) - X(i) fx1 = Y(i) fx2 = Y(i + 1) r = (fx1 + fx2) / 2 vp = CSng(r * r * Math.PI * dx) vt = vt + vp Next Return vt End Function Function VolumenCilindro(ByVal X() As Single, ByVal Y() As Single, ByVal np As Integer ) As Single Dim vt, vp, r2, R1, h, rp As Single Dim i As Integer vt = 0 For i = 0 To np - 1 r2 = X(i) R1 = X(i + 1) rp = (R1 + R1) / 2 h = (Y(i) + Y(i + 1)) / 2 REM altura promedio vp = CSng(Math.PI * h * (R1 * R1 - r2 * r2)) vt = vt + vp Next Return vt End Function Function ObtenerCentro(ByVal X() As Single, ByVal np As Integer ) As Single Dim suma As Single = 0, i As Integer For i = 0 To np - 1 suma = suma + X(i) Next Return suma / np End Function End Module CLASE FORMULARIO
Public Class Form1 Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load ColorFondo = Color.FromArgb(220, 220, 220) Pincel = New Pen(Color.Red, 2) brocha = New SolidBrush(Color.Yellow) Grafico = PictureBox1.CreateGraphics
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 68 -
DataGridView1.ColumnCount = 3 DataGridView1.RowCount = 8 DataGridView1.Columns(0).HeaderText = "Propiedad" DataGridView1.Columns(1).HeaderText = "X" DataGridView1.Columns(2).HeaderText = "Y" DataGridView1.Columns(0).Width = 120 DataGridView1.Columns(1).Width = 40 DataGridView1.Columns(2).Width = 40 DataGridView1.Rows(0).Cells(0).Value = "Cx,Cy" DataGridView1.Rows(0).Cells(1).Value = cx DataGridView1.Rows(0).Cells(2).Value = cy DataGridView1.Rows(1).Cells(0).Value = "Traslacion" DataGridView1.Rows(1).Cells(1).Value = Tx DataGridView1.Rows(1).Cells(2).Value = ty DataGridView1.Rows(2).Cells(0).Value = "Escalado" DataGridView1.Rows(2).Cells(1).Value = ex DataGridView1.Rows(2).Cells(2).Value = ey DataGridView1.Rows(3).Cells(0).Value = "Nc,Nf" DataGridView1.Rows(3).Cells(1).Value = nc DataGridView1.Rows(3).Cells(2).Value = nf DataGridView1.Rows(4).Cells(0).Value = "Area perimetro" DataGridView1.Rows(4).Cells(1).Value = Area DataGridView1.Rows(4).Cells(2).Value = perimetro DataGridView1.Rows(5).Cells(0).Value = "Centro figura Cx,cy" DataGridView1.Rows(5).Cells(1).Value = CentroX DataGridView1.Rows(5).Cells(2).Value = CentroY DataGridView1.Rows(6).Cells(0).Value = " Superficie Revolucion" DataGridView1.Rows(6).Cells(1).Value = areaLateral DataGridView1.Rows(7).Cells(0).Value = "Volumen Disco Cilindro" DataGridView1.Rows(7).Cells(1).Value = VolDisco DataGridView1.Rows(7).Cells(2).Value = VolCilindro BtnIniciarTodo_Click(sender, e) End Sub Sub MostrarMatriz(ByVal nf As Integer , ByVal nc As Integer ) Dim fila As Integer , col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 DataGridView2.Rows(fila).Cells(col).Value = Matriz(fila, col) Next Next End Sub Private Sub AbrirToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles AbrirToolStripMenuItem.Click OpenFileDialog1.ShowDialog() RecuperarMatriz(OpenFileDialog1.FileName, nf, nc) BtnIniciarTodo_Click(sender, e) MostrarMatriz(nf, nc) REM MsgBox("archivo RECUPERADO")
Practicas realizadas de Lenguaje de Programación 2014 \Ismael Véliz Vilca
- 69 -
End Sub Private Sub GuardarToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles GuardarToolStripMenuItem.Click SaveFileDialog1.ShowDialog() GrabarDatos(SaveFileDialog1.FileName, nf, nc) MsgBox("archivo grabado") End Sub Private Sub MnuIniciar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MnuIniciar.Click Dim fila, col As Integer cx = DataGridView1.Rows(0).Cells(1).Value cy = DataGridView1.Rows(0).Cells(2).Value tx = DataGridView1.Rows(1).Cells(1).Value ty = DataGridView1.Rows(1).Cells(2).Value ex = DataGridView1.Rows(2).Cells(1).Value ey = DataGridView1.Rows(2).Cells(2).Value nc = DataGridView1.Rows(3).Cells(1).Value nf = DataGridView1.Rows(3).Cells(2).Value DataGridView2.RowCount = nf DataGridView2.ColumnCount = nc For col = 0 To nc - 1 DataGridView2.Columns(col).Width = 50 Next For fila = 0 To nf - 1 DataGridView2.Rows(fila).HeaderCell.Value = fila.ToString Next End Sub Sub ModificarMatriz(ByVal nf As Integer , ByVal nc As Integer ) Dim fila As Integer , col As Integer For fila = 0 To nf - 1 For col = 0 To nc - 1 Matriz(fila, col) = DataGridView2.Rows(fila).Cells(col).Value Next Next Me.Text = "Matriz modificada" End Sub Private Sub MnuVerMatriz_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MnuVerMatriz.Click MostrarMatriz(nf, nc) End Sub Private Sub MnuVectoresXY_Click(ByVal sender As Object, ByVal e As EventArgs) Handles MnuVectoresXY.Click Dim fila As Integer ListBox1.Items.Clear() For fila = 0 To nf - 1 ListBox1.Items.Add("X = " & X(fila) & " Y= " & Y(fila)) Next End Sub