Вы находитесь на странице: 1из 25

SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG.

1 DE 25
TEMA 1
ALMACENAMIENTO INTERNO DE DATOS

OBJETIVOS





METAS





TEMTICA:
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
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 2 DE 25
ALGORITMOS + ESTRUCTURAS DE DATOS = PROGRAMAS

ESTRUCTURA DE DATOS

UNA ESTRUCTURA DE DATOS ES UNA COLECCIN DE DATOS
ORGANIZADOS DE UN MODO PARTICULAR, LAS ESTRUCTURAS DE DATOS
PUEDEN SER DE DOS TIPOS : ESTRUCTURAS DE DATOS ESTTICAS Y
ESTRUCTURAS DE DATOS DINMICOS















DATOS
SIMPLES
DATOS
ESTRUCTURADOS
ESTANDAR
DEFINIDO POR EL
PROGRAMADOR
(NO ESTANDAR)
SIMPLES O ESTATICOS
COMPUESTOS O
DINMICOS
ENTERO (int)
REAL (float)
CARCTER (char)
LGICO (boolean)
SUBRRANGO
ENUMERATIVO (enum)
ARRAYS (VECTORS /
MATRICES)
REGISTROS
FICHEROS
CONJUNTOS
CADENAS(strings)
LISTAS (PILAS / COLAS)
LISTAS ENLAZADAS
ARBOLES
GRAFOS
ESTRUCTURAS
DE DATOS
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 3 DE 25
Arreglos (Arrays)
Un array es una coleccin de elementos del mismo tipo que se
denominan por un nombre comn.

Calabazas



A un elemento especfico 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
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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



SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 5 DE 25
ARRAYS UNIDIMENSIONALES (VECTORES)

Un vector es un array unidimensional, es decir, slo utiliza un ndice para referenciar
a cada uno de los elementos.


VEC



0 1 2 3 4 5 6 7 8 9



INDICE


Su declaracin ser:

tipo nombre [tamao];




int datos[10];
IDENTIFICADOR
[
TAMAO
]
TIPO DE DATO
;
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 6 DE 25
Como acceder a los campos de un vector




DATOS[i] VEC[3]

ASIGNACIN


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
]
= EXPRESIN ;
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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 }
INICIALIZACIN DEL
VECTOR






INDICES




CICLO REPETITIVO





IMPRESIN
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 8 DE 25












VEC



0 1 2 3 4 5 6 7 8 9




Array de caracteres
La cadena first es un array esttico de caracteres
El array de caracteres puede ser inicializado por una cadena
literal
char string1[] = "first";
El carcter 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 direccin del array,
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 10 DE 25
Como pasar array a funciones
Se puede pasar como un argumento de la funcin, especificando el nombre
del array sin su dimensin
int myArray[ 24 ];
myFunction( myArray, 24 );

El tamao del Array genralmente es pasado a la funcin
El nombre del array es una direccin del primer elemento
La funcin sabe donde la serie se guarda
Generalmente se modifican los datos originales en sus
posiciones de memoria

El prototipo de la funcin podria ser
void modifyArray( int b[], int arraySize );

Los nombres de los parmetros en el prototipo
int b [] podra escribirse tambien int []
int arraySize simplemente podran ser int
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 11 DE 25



















1 /* Fig. 6.13: fig06 13.c
2 Passing arrays and individual array elements to functions
3 #include <stdio.h>
4 #define SIZE 5
5
6 void modifyArray( int [], int ); /* appears strange */
7 void modifyElement( int );
8
9 int main()
10 {
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i;
12
13 printf( "Effects of passing entire array call "
14 "by reference:\n\nThe values of the "
15 "original array are:\n" );
16
17 for ( i = 0; i <= SIZE - 1; i++ )
18 printf( "%3d", a[ i ] );
19
20 printf( "\n" );
21 modifyArray( a, SIZE ); /* passed call by reference */
22 printf( "The values of the modified array are:\n" );
23
24 for ( i = 0; i <= SIZE - 1; i++ )
25 printf( "%3d", a[ i ] );
26
27 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 funcion
llamada por referencia, puede ser
modificado
Elementos del Array pasados
por valor, y no pueden ser
modificados
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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 }
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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 nmeros:\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);
}


SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 14 DE 25
/* Lee 10 enteros. Luego pide mas datos y, para cada nuevo dato,
cuenta su frecuencia de aparicin entre los 10 datos originales */

#include<stdio.h>
#define NUM 10
main()
{ int x=1, i, frec, nums[NUM];
printf("Introducir %d nmeros:\n", NUM);
for (i=0; i<NUM; i++)
scanf("%d", &nums[i]);
while (x!=0)
{ printf("\nPara terminar = 0\nNmero 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);
}
}




SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 15 DE 25
/* Lee 10 enteros. Luego pide mas datos y, para cada uno, determina
si esta entre los datos originales y que posicin ocupa. */

#include<stdio.h>
#define N 10
main()
{ int i, x=0, V[N]; /* V: datos a buscar */
printf("Introducir %d nmeros:\n", N);
for (i=0; i<N; i++)
scanf("%d", &V[i]);
while (x!=0)
{
printf("\nPara terminar = 0\nNmero 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);
}
}


SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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;
}
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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


SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 18 DE 25
Su declaracin ser:

tipo nombre [tamao_1][tamao_2];




int datos[10][5];

Como acceder a los campos de una matriz



DATOS[i][j] MAT[3][6]

ASIGNACIN


DATOS[i][j]=45; MAT[2][4]=4.67;
IDENTIFICADOR
[
TAMAO
]
TIPO DE DATO
; [
TAMAO
]
IDENTIFIACARO
[
INDICE / VALOR
] [
INDICE / VALOR
]
= EXPRESIN ;
IDENTIFIACARO
[
INDICE / VALOR
] [
INDICE / VALOR
]
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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 0
Row 1
Row 2
Col umn 0 Col umn 1 Col umn 2 Col umn 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 subscr i pt
Ar r ay name
Col umn subscr i pt
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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"); }
}

SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 21 DE 25
// programa que genera el cuadrado mgico
#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;
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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();
}

SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ PAG. 23 DE 25
// Verificar si una matriz es cuadrado mgico
#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];
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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];
SIS - 1101 ING. CARLOS BALDERRMA VSQUEZ 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);
}

Вам также может понравиться