jueves, 9 de diciembre de 2010

APUNTADORES

APUNTADORES

Los apuntadores son una parte fundamental de C. Si usted no puede usar los apuntadores apropiadamente entonces esta perdiendo la potencia y la flexibilidad que C ofrece básicamente. El secreto para C esta en el uso de apuntadores.
C usa los apuntadores en forma extensiva. ¿Porqué?
·    Es la única forma de expresar algunos cálculos.
·    Se genera código compacto y eficiente.
·    Es una herramienta muy poderosa.
C usa apuntadores explícitamente con:
·    Es la única forma de expresar algunos cálculos.
·    Se genera código compacto y eficiente.
·    Es una herramienta muy poderosa.
C usa apuntadores explícitamente con:
·    Arreglos,
·    Estructuras y
·    Funciones
Un apuntador es una variable que contiene la dirección en memoria de otra variable. Se pueden tener apuntadores a cualquier tipo de variable.
El operador unario o monádico & devuelve la dirección de memoria de una variable.
El operador de indirección o dereferencia * devuelve el ``contenido de un objeto apuntado por un apuntador''.
Para declarar un apuntador para una variable entera hacer:
int *apuntador;
Se debe asociar a cada apuntador un tipo particular. Por ejemplo, no se puede asignar la dirección de un short int a un long int.
Para tener una mejor idea, considerar el siguiente código:
main()
{
    int x = 1, y = 2;
    int *ap;

    ap = &x;

    y = *ap;

    x = ap;

    *ap = 3;
}

EJEMPLO

#include<stdio.h>
#include<conio.h>
void main()
{
int *punt=NULL, var=14;
printf("%#x, %#x", punt, &var);
printf("\n%d, %d", *punt, var);
punt=&var;
printf("%#x, %#x", punt, &var);
printf("\n%d, %d", *punt, var);
printf("%d,%d", *(punt+1), var+1);
getch();
}

ASIGNACION FIJA Y DINAMICA: EJMPLOS DE PROGRAMAS

ASIGNACION FIJA
#include<iostream.h>
#include<conio.h>

struct alumno{
char nombre[20];
double matri;
int cal1,cal2,cal3;
void datos()
{
cout<<endl;
cout<<endl;
cout<<"Nombre"<<endl;
cin>>nombre;
cout<<"Matricula"<<endl;
cin>>matri;
cout<<"Calificacion 1"<<endl;
cin>>cal1;
cout<<"Calificacion 2"<<endl;
cin>>cal2;
cout<<"Calificacion 3"<<endl;
cin>>cal3;
}

void resultado()
{
cout<<endl;
cout<<"\tDatos"<<endl;
cout<<endl;
cout<<"Alumno"<<"\tMatricula"<<"\tCalificacion 1"<<"\tCalificacion 2"<<"\tcalificacion 3"<<endl;
cout<<endl;
cout<<nombre<<"\t"<<matri<<"\t\t"<<cal1<<"\t\t"<<cal2<<"\t\t"<<cal3<<endl;
cout<<endl;
}
}esc[3];
int main()
{
//clrscr();

for(int i=0;i<3;i++)
{
esc[i].datos();
esc[i].resultado();
}
getch();
return 0;
}

ASIGNACION DINAMICA

#include<iostream.h>
#include<conio.h>
int main(void)
{
 int *vector, tm;
 int indice;
 cout<<"Ingrese el numero de elemnetos:";
 cin>>tm;
 vector = new int(tm); //Asignacion dinamica de memoria.
 for(indice=0;indice<tm;indice++)
 {
  cout<<"Introduzca vector["<<indice + 1<< "]: ";
  cin>>vector[indice];
 }
 for(int i=0;i<tm;i++)
 {

 cout<<"El vector es"<<vector[i]<<endl;
 }
getch();
}

miércoles, 24 de noviembre de 2010

GRAFICOS Y PROGRAMAS

GRAFOS
En el modo gráfico existe una enorme cantidad de funciones que realizan desde la tarea mas sencilla como es pintar un píxel, hasta la tarea mas compleja como pudiera ser dibujar un carácter por medio de trazos.

Para trabajar el modo gráfico es necesario incluir la librería graphics.h como hacer uso de la BGI (Borlan Graphics Interphase)

Para usar cualquier función es necesario colocar el adaptador de video en modo grafico y esto se logra a través de la función initgraph(); y al terminares necesario regresar al modo original a través de la función closegraph();

Para iniciar un programa en ambiente gráfico es recomendable correr una subrutina de inicialización de gráficos y detección de errores.

Algunos ejemplos de las funciones que se pueden encontrar en la librería de gráphics.h son:
Line(); circle(); arc(); elipse();rectangle(); ottextxy(); putpixel();
Para saber mas de las funciones de la librería de gráficos lo pueden buscar en el índice de turbo c

ESTRUCTURA DEL PROGRAMA

#include <graphics.h>  
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
   VARIABLES PARA INICIALIZAR MODO GRAFICO
   int gdriver = DETECT, gmode, errorcode;

   INICIALIZAR MODO GRAFICO
   initgraph(&gdriver, &gmode, "");

  DETECTA SI HAY ALGUN ERROR PARA USAR MODO GRAFICO
   errorcode = graphresult();
  
   if (errorcode != grOk)
   {
      printf("Graphics error: %s\n", grapherrormsg(errorcode));
      printf("Press any key to halt:");
      getch();
      exit(1);
   }
 
   line(0, 0, 50,50 ); DIBUJA UNA LINEA

   getch();
   closegraph(); CERRAR MODO GRAFICO
   return 0;
}

FUNCIONES PARA DIBUJAR

cleardevice(void); LIMPIA LA PANTALLA

setcolor(int color); COLOR DE LINEA

setbkcolor(int color); COLOR DE FONDO (PANTALLA)

line(int x1, int y1, int x2, int y2); DIBUJA UNA LINEA

rectangle(int left, int top, int right, int bottom); DIBUJA UN RECTANGULO
rectangle(izqierda,arriba,derecha,abajo);

putpixel(int x, int y, int color); PINTA UN PIXEL

outtextxy(int x, int y, char far *textstring); DIBUJA TEXTO
outtextxy(100,100,”Programa 1”);

settextstyle(int font, int direction, int charsize); TIPO DE LETRA A USAR
settextstyle(tipo letra, direccion, tamaño letra);

TIPOS DE LETRA (FONT)

0   DEFAULT_FONT       
1   TRIPLEX_FONT        
2   SMALL_FONT            
3   SANS_SERIF_FONT  
4   GOTHIC_FONT           

DIRECTION

0   HORIZ_DIR   
1   VERT_DIR    

settextjustify(int horiz, int vert); JUSTIFICAR TEXTO

HORIZ  

0   LEFT_TEXT     IZQUIERDA
1   CENTER_TEXT   CENTRADO
2   RIGHT_TEXT   DERECHA
 
VERT   

0   BOTTOM_TEXT  ABAJO
1   CENTER_TEXT   CENTRADO
2   TOP_TEXT      ARRIBA

RELLENADO DE FIGURAS

floodfill(int x, int y, int border); RELLENAR FIGURA

setfillstyle(int pattern, int color); TIPO DE RELLENO Y COLOR A USAR

TIPOS DE RELLENADO(FILL PATTERNS)

0   EMPTY_FILL       
1   SOLID_FILL       
2   LINE_FILL        
3   LTSLASH_FILL     
4   SLASH_FILL       
5   BKSLASH_FILL     
6   LTBKSLASH_FILL   
7   HATCH_FILL       
8   XHATCH_FILL      
9   INTERLEAVE_FILL  
10 WIDE_DOT_FILL   
11 CLOSE_DOT_FILL  
12 USER_FILL       

COLORES

0   BLACK         
1   BLUE          
2   GREEN         
3   CYAN          
4   RED           
5   MAGENTA       
6   BROWN         
7   LIGHTGRAY     
8   DARKGRAY      
9   LIGHTBLUE     
10 LIGHTGREEN   
11 LIGHTCYAN    
12 LIGHTRED     
13 LIGHTMAGENTA 
14 YELLOW       
15 WHITE        
128  BLINK       






PROGRAMAS DE GRAFICOS
PROGRAMAS DE CONFETI
#include"conio.h"
#include"stdlib.h"
#include"stdio.h"
#include"graphics.h"
using namespace std;
int main()
{
      int pantalla=DETECT,modo,error;
      printf("gaby");
      _getch();
      initgraph(&pantalla,&modo,"");
      error=graphresult();
      if(error!=grOk)
      {
            printf("error al iniciar el modo grafico!");
            _getch();
            exit(0);
      }
      int y,x,radio,color;
      rand();
      while(!kbhit())
{
            x=rand()%(680);
            y=rand()%(680);
            radio=rand()%(50);
            color=rand()%(5);
            setcolor(RED);
            setfillstyle(8,YELLOW);
            fillellipse(x,y,radio,radio);
            delay(50);
}
}

                                             

PROGRAMA DE CASITA
//#include "stdio.h"
//#include "stdlib.h"
//#include "conio.h"
//#include "graphics.h"
#include "Dibujo.h"

int main()
{
      int iGraphicsDriver = DETECT, iGraphicsMode, iError, x, y;
      system("cls");
      initgraph(&iGraphicsDriver, &iGraphicsMode, "");
      iError = graphresult();
      if(iError != grOk)
      {
            printf("\n\tERROR AL INICAR EL MODO GRAFICO %c", 7);
            _getch();
            exit(EXIT_SUCCESS);
      }    
      setcolor(BLUE);
      line(90,195,240,90);
      line(240,90,390,195);
      setcolor(YELLOW);
      rectangle(90,195,390,420);
      setcolor(RED);
      rectangle(120,240,165,285);
      rectangle(285,240,330,285);
      setcolor(GREEN);
      rectangle(210,345,270,420);
      setcolor(WHITE);
      circle(240,150,30);
      circle(255,390,5);
      //Casa();

     

      //Casa();

      _getch();
      return 0;
}

PROGRAMA DE PROYECTO
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "graphics.h"
//#include "Dibujo.h"
void wmouseclick()
{
      clearmouseclick(WM_LBUTTONDOWN);
      int x,y;
      while(!ismouseclick(WM_LBUTTONDOWN))
            delay(50);
      getmouseclick(WM_LBUTTONDOWN,x,y);
}
int main()
{
      int iGraphicsDriver = DETECT, iGraphicsMode, iError;
    system("cls");
      initgraph(&iGraphicsDriver, &iGraphicsMode, "");
      iError = graphresult();
      if(iError != grOk)
      {
            printf("\n\tERROR AL INICAR EL MODO GRAFICO %c", 7);
            _getch();
            exit(EXIT_SUCCESS);
      }
      int x,y,radio,color;
      rand();
    outtextxy(200,400,"DA UN CLICK Y OBSERVA LO QUE PASA");
      outtextxy(270,420,"Proyecto de Programcion II");
      outtextxy(270,435,"Ana Gabriela Santos Lopez");
    outtextxy(270,450,"Yazmín García Jimenez");
     
    setcolor(5); 
      line(180,45,405,45);
      line(180,45,90,105);
      line(90,105,150,105);
      line(405,45,495,105);
      line(435,105,495,105);
      rectangle(150,105,435,330);
      setcolor(3);
      rectangle(165,120,240,180);//vetana1
      rectangle(180,135,225,165);
      rectangle(345,120,420,180);//ventana2
      rectangle(360,135,405,165);
      rectangle(165,225,240,285);//ventana3
      rectangle(180,240,225,270);
      rectangle(345,225,420,285);//ventana4
      rectangle(360,240,405,270);
    rectangle(270,240,315,330);//puerta
      rectangle(285,255,300,270);
      circle(300,285,5);
    rectangle(210,15,255,30);//chimenea
    rectangle(225,30,240,45);
    setcolor(GREEN);
     


     
            x=rand()%(20);
            radio=rand()%(60);
            color=rand()%(5);
            setcolor(WHITE);
            setfillstyle(8,WHITE);
            fillellipse(x,y,radio,radio);
            delay(10);


      wmouseclick();



      setcolor(5); 
      line(180,45,405,45);
      line(180,45,90,105);
      line(90,105,150,105);
      line(405,45,495,105);
      line(435,105,495,105);
      rectangle(150,105,435,330);
      setcolor(3);
      rectangle(165,120,240,180);//vetana1
      rectangle(180,135,225,165);
      rectangle(345,120,420,180);//ventana2
      rectangle(360,135,405,165);
      rectangle(165,225,240,285);//ventana3
      rectangle(180,240,225,270);
      rectangle(345,225,420,285);//ventana4
      rectangle(360,240,405,270);
    rectangle(270,240,315,330);//puerta
      rectangle(285,255,300,270);
      circle(300,285,5);
    rectangle(210,15,255,30);//chimenea
    rectangle(225,30,240,45);
    setcolor(GREEN);
      line(75,165,45,210);//pino1
      line(105,210,75,165);
      line(45,210,60,210);
      line(90,210,105,210);
      line(60,210,30,240);//pino2
      line(120,240,90,210);
      line(30,240,60,240);
      line(90,240,120,240);
      line(60,240,30,270);//pino3
      line(120,270,90,240);
      line(30,270,60,270);
      line(90,270,120,270);
    line(60,270,60,330);//troco
      line(90,270,90,330);
      line(60,330,90,330);
      setcolor(GREEN);
      setfillstyle(SOLID_FILL,GREEN);
      floodfill(70,315,GREEN);
     

    setcolor(9);
      setfillstyle(SOLID_FILL,9);
      circle(75,180,5);//esferas
      floodfill(75,180,9);

      setcolor(9);
      setfillstyle(SOLID_FILL,9);
      circle(60,195,5);
      floodfill(60,195,9);

      setcolor(14);
      setfillstyle(SOLID_FILL,14);
      circle(90,195,5);
      floodfill(90,195,14);
     
      setcolor(14);
      setfillstyle(SOLID_FILL,14);
      circle(75,210,5);
      floodfill(75,210,14);

      setcolor(12);
      setfillstyle(SOLID_FILL,12);
      circle(60,225,5);
      floodfill(60,225,12);


      setcolor(12);
      setfillstyle(SOLID_FILL,12);
      circle(75,240,5);
      floodfill(75,240,12);



      setcolor(1);
      setfillstyle(SOLID_FILL,1);
      circle(90,225,5);
      floodfill(90,225,1);

      setcolor(1);
      setfillstyle(SOLID_FILL,1);
      circle(75,225,5);
      floodfill(75,225,1);


     

while(!kbhit())
{
            x=rand()%(20);
            radio=rand()%(60);
            color=rand()%(5);
            setcolor(WHITE);
            setfillstyle(8,WHITE);
            fillellipse(x,y,radio,radio);
            delay(10);
}
      _getch();
      return 0;
}