2 arreglos

25
SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 1 DE 25 TEMA 1 ALMACENAMIENTO INTERNO DE DATOS OBJETIVOS METAS TEMÁTICA: ARRAYS REGISTROS PUNTEROS GENERAR HABILIDADES Y DESTREZAS EN EL MANEJO DE ARREGLOS UNIDIMENSIONALES Y BIDIMENSIONALES GENERAR HABILIDADES Y DESTREZAS EN EL MANEJO DE ESTRUCTURAS Y UNIONES GENERAR HABILIDADES Y DESTREZAS EN EL MANEJO DE PUNTEROS EL ALUMNO PODRÁ RESOLVER DIFERENTES PROBLEMAS SOBRE ARRAYS ESTRUCTURAS Y PUNTEROS, CON EFICIENCIAS Y EFICACIA

Upload: janeth-gallo

Post on 28-Dec-2015

6 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 1 DE 25

TEMA 1 ALMACENAMIENTO INTERNO DE DATOS

OBJETIVOS METAS TEMÁTICA:

• ARRAYS • REGISTROS • PUNTEROS

• GENERAR HABILIDADES Y DESTREZAS EN EL

MANEJO DE ARREGLOS UNIDIMENSIONALES Y

BIDIMENSIONALES

• GENERAR HABILIDADES Y DESTREZAS EN EL

MANEJO DE ESTRUCTURAS Y UNIONES

• GENERAR HABILIDADES Y DESTREZAS EN EL

MANEJO DE PUNTEROS

• EL ALUMNO PODRÁ RESOLVER DIFERENTES

PROBLEMAS SOBRE ARRAYS ESTRUCTURAS Y

PUNTEROS, CON EFICIENCIAS Y EFICACIA

Page 2: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 2 DE 25

ALGORITMOS + ESTRUCTURAS DE DATOS = PROGRAMAS ESTRUCTURA DE DATOS UNA ESTRUCTURA DE DATOS ES UNA COLECCIÓN DE DATOS ORGANIZADOS DE UN MODO PARTICULAR, LAS ESTRUCTURAS DE DATOS PUEDEN SER DE DOS TIPOS : ESTRUCTURAS DE DATOS ESTÁTICAS Y ESTRUCTURAS DE DATOS DINÁMICOS

DATOS SIMPLES

DATOS ESTRUCTURADOS

ESTANDAR

DEFINIDO POR EL PROGRAMADOR (NO ESTANDAR)

SIMPLES O ESTATICOS

COMPUESTOS O DINÁMICOS

ENTERO (int) REAL (float) CARÁCTER (char) LÒGICO (boolean)

SUBRRANGO ENUMERATIVO (enum)

ARRAYS (VECTORS / MATRICES) REGISTROS FICHEROS CONJUNTOS CADENAS(strings)

LISTAS (PILAS / COLAS) LISTAS ENLAZADAS ARBOLES GRAFOS

ESTRUCTURAS DE DATOS

Page 3: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 3 DE 25

Arreglos (Arrays) • Un array es una colección de elementos del mismo tipo que se

denominan por un nombre común.

Calabazas • A un elemento específico de un array se accede mediante un índice.

0 1 2 3 4 5 6 7 8

Candelero

Nombre

A B C D E F G H I

0 1 2 3 4 5 6 7 8

INDIECE

J

Nombre

LETRAS

POSICIONES DE 0 .. N

Page 4: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 4 DE 25

• En C todos los arrays constan de posiciones de memoria contiguas. • Los arrays pueden tener una o varias dimensiones.

AAOO1714

AAOO1715

AAOO1716

0000AA10 0000AA11 0000AA11 0000AA12 0000AA13 0000AA14 00000AA15

ARRAY UNIDIMENSIONAL VECTOR

ARRAY BIDIMENSIONAL MATRIZ

ARRAY BIDIMENSIONAL CUBO

Page 5: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 5 DE 25

ARRAYS UNIDIMENSIONALES (VECTORES)

Un vector es un array unidimensional, es decir, sólo utiliza un índice para referenciar a cada uno de los elementos.

VEC 0 1 2 3 4 5 6 7 8 9 INDICE

Su declaración será:

tipo nombre [tamaño];

int datos[10];

IDENTIFICADOR [ TAMAÑO ]TIPO DE DATO ;

Page 6: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 6 DE 25

Como acceder a los campos de un vector DATOS[i] VEC[3] ASIGNACIÓN DATOS[i]=45; VEC[2]=4.67; COMO SACAR DATOS DE UN VECTOR

Empleando instrucciones de salida printf o cout VEC

0 1 2 3 4 5 6 7 8 9

IDENTIFIACARO [ INDICE / VALOR ]

IDENTIFIACARO [ INDICE / VALOR ] = EXPRESIÓN ;

Page 7: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 7 DE 25

Ejemplo: construya un programa que genere un histograma

1 /* Fig. 6.8: fig06 08.c

2 Histogram printing program */

3 #include <stdio.h>

4 #define SIZE 10

5

6 int main()

7 {

8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

9 int i, j;

10

11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );

12

13 for ( i = 0; i <= SIZE - 1; i++ ) {

14 printf( "%7d%13d ", i, n[ i ]) ;

15

16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */

17 printf( "%c", '*' );

18

19 printf( "\n" );

20 }

21

22 return 0;

23 }

INICIALIZACIÓN DEL VECTOR INDICES CICLO REPETITIVO IMPRESIÓN

Page 8: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 8 DE 25

VEC 0 1 2 3 4 5 6 7 8 9

Array de caracteres La cadena “first” es un array estático de caracteres

– El array de caracteres puede ser inicializado por una cadena literal

char string1[] = "first"; • El carácter nulo '\0' termina una cadena • string1 actualmente tiene 6 caracteres • esto es equivalente a

char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; – Los caracteres pueden ser accedidos individualmente

string1[ 3 ] is character ‘s’ – El nombre del Array es la dirección del array,

Page 9: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 9 DE 25

1 /* Fig. 6.10: fig06_10.c

2 Treating character arrays as strings */

3 #include <stdio.h>

4

5 int main()

6 {

7 char string1[ 20 ], string2[] = "string literal";

8 int i;

9

10 printf(" Enter a string: ");

11 scanf( "%s", string1 );

12 printf( "string1 is: %s\nstring2: is %s\n"

13 "string1 with spaces between characters is:\n",

14 string1, string2 );

15

16 for ( i = 0; string1[ i ] != '\0'; i++ )

17 printf( "%c ", string1[ i ] );

18

19 printf( "\n" );

20 return 0;

21 }

Initializa la cadena Lee la cadena Imprime la cadena Imprime por caracteres

Page 10: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 10 DE 25

Como pasar array a funciones Se puede pasar como un argumento de la función, especificando el nombre del array sin su dimensión

int myArray[ 24 ]; myFunction( myArray, 24 );

El tamaño del Array genralmente es pasado a la función El nombre del array es una dirección del primer elemento

• La función sabe donde la serie se guarda • Generalmente se modifican los datos originales en sus

posiciones de memoria El prototipo de la función podria ser

void modifyArray( int b[], int arraySize ); Los nombres de los parámetros en el prototipo

• int b [] podría escribirse tambien int [] • int arraySize simplemente podrían ser int

Page 11: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 11 DE 25

1 /* Fig. 6.13: fig06 13.c2 Passing arrays and individual array elements to functions3 #include <stdio.h>4 #define SIZE 556 void modifyArray( int [], int ); /* appears strange */7 void modifyElement( int );89 int main()10 {11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;1213 printf( "Effects of passing entire array call "14 "by reference:\n\nThe values of the "15 "original array are:\n" );1617 for ( i = 0; i <= SIZE - 1; i++ )18 printf( "%3d", a[ i ] );1920 printf( "\n" );21 modifyArray( a, SIZE ); /* passed call by reference */22 printf( "The values of the modified array are:\n" );2324 for ( i = 0; i <= SIZE - 1; i++ )25 printf( "%3d", a[ i ] );2627 printf( "\n\n\nEffects of passing array element call "28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );29 modifyElement( a[ 3 ] );30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );31 return 0;32 }

Paso Arrays a una funcioón llamada por referencia, puede ser modificado

Elementos del Array pasados por valor, y no pueden ser modificados

Page 12: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 12 DE 25

33

34 void modifyArray( int b[], int size )

35 {

36 int j;

37

38 for ( j = 0; j <= size - 1; j++ )

39 b[ j ] *= 2;

40 }

41

42 void modifyElement( int e )

43 {

44 printf( "Value in modifyElement is %d\n", e *= 2 );

45 }

Page 13: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 13 DE 25

/* Lee 10 enteros, los lista en orden inverso y calcula su suma */ #include<stdio.h> #define NUM 10 main() {

int i, total = 0, nums[NUM]; printf("Introducir 10 números:\n "); for (i = 0; i < NUM; i++) /* Lectura */

scanf("%d", &nums[i]); /* Listado al rev_es y suma */ printf("\nListado en orden inverso: \n"); for (i = NUM-1; i >= 0; i--) {

printf("%d ", nums[i]); total = total + nums[i];

} printf("\nSuma: %d\n", total);

}

Page 14: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 14 DE 25

/* Lee 10 enteros. Luego pide mas datos y, para cada nuevo dato, cuenta su frecuencia de aparición entre los 10 datos originales */ #include<stdio.h> #define NUM 10 main() { int x=1, i, frec, nums[NUM];

printf("Introducir %d números:\n", NUM); for (i=0; i<NUM; i++) scanf("%d", &nums[i]); while (x!=0)

{ printf("\nPara terminar = 0\nNúmero a buscar: "); scanf("%d", &x); frec = 0; for (i=0; i<NUM; i++)

if (nums[i] == x) frec++; printf("El %d esta %d veces.\n", x, frec);

} }

Page 15: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 15 DE 25

/* Lee 10 enteros. Luego pide mas datos y, para cada uno, determina si esta entre los datos originales y que posición ocupa. */ #include<stdio.h> #define N 10 main() { int i, x=0, V[N]; /* V: datos a buscar */

printf("Introducir %d números:\n", N); for (i=0; i<N; i++)

scanf("%d", &V[i]); while (x!=0) {

printf("\nPara terminar = 0\nNúmero a buscar: "); scanf("%d", &x); /* BUSQUEDA LINEAL */ for (i=0; i<N; i++)

if (V[i]==x) break; if (i==N) printf("No encuentro %d.\n", x);

else printf("%d: posici_on %d.\n", x, i); }

}

Page 16: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 16 DE 25

#include<stdio.h> #include<conio.h> void rotar(int a[10]); int v[10]={1,2,3,4,5,6,7,8,9,0},i,j; main() { clrscr(); for (i=0;i<10;i++) printf("%d ",v[i]); for (j=0;j<10;j++) { rotar(v);

printf("\n"); for (i=0;i<10;i++) printf("%d ",v[i]);

} return 0; } void rotar(int a[10]) { int b; b=a[0]; for (i=0;i<9;i++) a[i]=a[i+1]; a[9]=b; }

Page 17: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 17 DE 25

ARRAYS BIDIMENSIONALES (MATRICES) Una matriz es un array bidimensional, es decir, utiliza dos índice para referenciar a cada uno de los elementos.

INDICE MAT

0 1 2 3 4

0 1 INDICE 2 3 DOS RECORRIDOS A LAS MATRICES

• RECORRIDO POR FILAS • RECORRIDO POR COLUMNAS

Page 18: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 18 DE 25

Su declaración será:

tipo nombre [tamaño_1][tamaño_2];

int datos[10][5];

Como acceder a los campos de una matriz

DATOS[i][j] MAT[3][6] ASIGNACIÓN DATOS[i][j]=45; MAT[2][4]=4.67;

IDENTIFICADOR [ TAMAÑO ]TIPO DE DATO ; [ TAMAÑO ]

IDENTIFIACARO [ INDICE / VALOR ] [ INDICE / VALOR ]

= EXPRESIÓN ;

IDENTIFIACARO [ INDICE / VALOR ] [ INDICE / VALOR ]

Page 19: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 19 DE 25

COMO SACAR DATOS DE UNA MATRIZ Empleando instrucciones de salida printf o cout

INDICE

MAT 0 1 2 3 4

0

1 INDICE 2 3

Row 0Row 1Row 2

Column 0 Column 1 Column 2 Column 3

a[ 0 ][ 0 ]

a[ 1 ][ 0 ]

a[ 2 ][ 0 ]

a[ 0 ][ 1 ]

a[ 1 ][ 1 ]

a[ 2 ][ 1 ]

a[ 0 ][ 2 ]a[ 1 ][ 2 ]a[ 2 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 3 ]

a[ 2 ][ 3 ]

Row subscriptArray name

Column subscript

Page 20: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 20 DE 25

/* Genera la matriz M[i,j] = (i+2j)2, y muestra M, su transpuesta */ #include<stdio.h> #define I 5 /* filas */ #define J 6 /* columnas */ main() { int i, j, x, M[I][J]; /* M[i][j]: i = 0..I-1, j = 0..J-1 */

for (i=0; i<I; i++) for (j=0; j<J; j++)

{ x = i+2*j; M[i][j] = x*x;

} /* Genera M */ printf("M[0..%d, 0..%d]:\n", I-1, J-1); for (i=0; i<I; i++) /* muestra M */

{ for (j=0; j<J; j++) printf(" %3d", M[i][j]);

printf("\n"); } printf("\nM'[0..%d, 0..%d]:\n", J-1, I-1);

for (j=0; j<J; j++) /* muestra M' = */ { for (i=0; i<I; i++)

printf(" %3d", M[i][j]); /* transpuesta(M)*/ printf("\n"); }

}

Page 21: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 21 DE 25

// programa que genera el cuadrado mágico #include<conio.h> #include<stdio.h> int matriz[15][15]; main() { int i=0,j,grado,cont=1; clrscr(); printf("\n Grado de la matriz :"); scanf("%d",&grado); j=grado/2; matriz[i][j]=1; for(cont=2;cont<=grado*grado;cont++) { if((cont-1) % grado) { i = i-1; j = j +1; if(i ==-1 ) i =grado-1; if(j == grado) j =0; } else i=i+1;

Page 22: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 22 DE 25

matriz[i][j]=cont; } printf("\n Esta es la matriz\n"); for(i=0;i<grado;i++) { for(j=0;j<grado;j++) printf("%5d",matriz[i][j]); printf("\n"); } getch(); }

Page 23: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 23 DE 25

// Verificar si una matriz es cuadrado mágico #include<iostream.h> #include<conio.h> #include<stdlib.h> int n=5,m[10][10]; int f,c,sdp=0,sds=0,sf[10],sc[10]; void lee(void) { randomize(); for (f=1;f<=n;f++) for (c=1;c<=n;c++) m[f][c]=random(10)+1; } void imp(void) { for (f=1;f<=n;f++) { for (c=1;c<=n;c++) cout << m[f][c] << " ";

cout << "\n"; } } void sumdia(void) { for (f=1;f<=n;f++) for (c=1;c<=n;c++) { if (f==c) sdp=sdp+m[f][c];

Page 24: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 24 DE 25

if (f+c==n+1) sds=sds+m[f][c]; } } void sumfil(void) { for (f=1;f<=n;f++) { sf[f]=0; for (c=1;c<=n;c++) sf[f]=sf[f]+m[f][c]; } } void sumcol(void) { for (c=1;c<=n;c++) { sc[c]=0; for (f=1;f<=n;f++) sc[c]=sc[c]+m[f][c]; } } void verifica(void) { int suf,suc; for (f=1;f<=n;f++) suf=suf+sf[f]; for (f=1;f<=n;f++) suc=suc+sc[f];

Page 25: 2 Arreglos

SIS - 1101 ING. CARLOS BALDERRMA VÁSQUEZ PAG. 25 DE 25

suf=suf/n; suc=suc/n; if ((sdp==sds) && (suc==suf))

cout << " \nes Cuadrado perfecto "; else cout << " \nNO es Cuadrado perfecto "; } main() { clrscr(); cout << " Dimension n = "; cin >> n; lee(); imp(); sumdia(); sumfil(); sumcol(); verifica(); return(0); }