13
FUNCIONES EN C USANDO ARRAYS Y MATRICES

FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

Embed Size (px)

Citation preview

Page 1: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

FUNCIONES EN C USANDO ARRAYS Y MATRICES

Page 2: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

MENU DEL DIA

• Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa).

• Inicialización de arreglos de dos dimensiones.

• Funciones en C y arreglos.• Comparación al trabajar con

funciones y sin funciones.• Sin funciones.• Con funciones.

• Mas anotaciones sobre funciones en C.

• Ejercicios.

Page 3: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

INICIALIZACION DE ARREGLOS DE DOS DIMENSIONES

Page 4: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

INICIALIZACION DE ARREGLOS DE DOS DIMENSIONES

Para barrer matrices se usan ciclos anidados. Hay que prestar atención a tres cosas:• Las dimensiones de la matriz, las cuales

definen los limites de los ciclos.• Que índice será usado como filas y cual

como columnas.• Que se va a barrer primero, si filas o

columnas. El ciclo mas interno define lo que se barre primero (Ojo con las dimensiones).

int i,j,k = 0;int M[3][4];for(i=0;i<3;i++){ for(j=0;j<4;j++) { M[i][j]=k++; }}

int i,j,k = 0;int M[3][4];for(j=0;j<4;j++){ for(i=0;i<3;i++) { M[i][j]=k++; }}

Page 5: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

FUNCIONES EN C Y ARREGLOS• Es posible usar vectores y

matrices como parametros de una funcion.

• Para declarar un array como argumento se usa la siguiente sintaxis en la definicion: tipo nombre_parametro[], tipo *nombre_parametro.

• Siempre que tengamos un array como parámetro a una función, ésta debe saber hasta donde va el arreglo. Generalmente se envía el tamaño del arreglo

#include <stdio.h>

void sumar_array(int [],int [], int); void restar_array(int *,int *, int);int main() { int a[] = {2,3,-1,4}; int b[4] = {2,3,-1,4}; c[4]={0,0,0,0}; sumar_array(a,b,4); sumar_array(c,b,4); return 0;}

void sumar_array(int a[],int b[], int len) { int i; for(i=0;i<len;i++) { b[i] = b[i] + a[i]; }}

void restar_array(int *a,int *b, int len) { int i; for(i=0;i<len;i++) { b[i] = b[i] - a[i]; }}

Nota: Complementar con las diapositivas de los profesores Sebastian y Byron.

Page 6: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

FUNCIONES EN C Y ARREGLOS• También es posible usar matrices como parámetros en una función.• Cuando se pasa una matriz

double maximum( int , int , double [][] )

. . .

double maximum( int nrows, int ncols, double matrix[nrows][ncols] ){ double max = matrix[0][0]; int c,r; for ( r = 0; r < nrows; ++r ) for ( c = 0; c < ncols; ++c ) if ( max < matrix[r][c] ) max = matrix[r][c]; return max;}

• Nota: Complementar con las diapositivas de Byron y Sebastian.

Page 7: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

#include <stdio.h>

int a[3],b[3],c[3];

int main() { int i; printf(" Ingrese el primer vector: "); for(i=0;i<3;i++) { scanf("%d",&a[i]); } printf(" vec1 = [%d %d %d]\n\n",a[0],a[1],a[2]); printf(" Ingrese el segundo vector: "); for(i=0;i<3;i++) { scanf("%d",&b[i]); } printf(" vec2 = [%d %d %d]\n\n",b[0],b[1],b[2]); for(i=0;i<3;i++) { c[i]=a[i]+b[i]; } printf(" vec3 = vec1 + vec2 = [%d %d %d]\n\n",c[0],c[1],c[2]); return 0;}

TRABAJANDO SIN FUNCIONES

Page 8: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

TRABAJANDO CON FUNCIONES#include <stdio.h>

int a[3],b[3],c[3];

void ingresar_vector(int []);void imprimir_vector(int []);void sumar_vectores(int [],int [],int );

int main() { int i; printf(" Ingrese el primer vector: "); ingresar_vector(a); printf(“vec1 = ”); imprimir_vector(a); printf(“\n\n”); . . . return 0;}

void ingresar_vector(int v[]) { for(i=0;i<3;i++) { scanf("%d",&v[i]); }}

void imprimir_vector(int v[]) { printf(“[%d %d %d]”,v[0],v[1],v[2]);}

void sumar_vectores(int v1[],int v2[],int res) { for(i=0;i<3;i++) { res[i]=v1[i]+v2[i]; }}

Prototipos de las funciones

Función principal

Definición de las funciones

Page 9: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

MAS ANOTACIONES SOBRE FUNCIONES EN C

• Una función puede devolver cualquier tipo de dato simple (char, short, int, long, etc), compuesto (estructura) o un puntero a cualquiera de estos dos tipos.int suma(int a, int b, int c)unsigned posicion(char cadena[],char letra) long potencia(int base,int exponente)char *strchr (char *s, int c)struct estudiante getEstudiante(struct estudiante *a,char *c)

• Una función solo puede retornar un solo valor a menos que devuelva un puntero o una estructura.

char *char *s

int c

strchr char *strchr (char *s, int c)

struct estudiantechar *s

struct estudiante *a

getEstudiante

struct estudiante getEstudiante(struct estudiante *a,char *c)

Page 10: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

ANOTACIONES SOBRE FUNCIONES EN C• Una función no puede retornar un array o una matriz.

int C[ ]int B[ ]

sumarVectores

int [] sumarVectores(int A[], int B[], int tam)

int A[ ]

int tam

int B[ ]

sumarVectores

void sumarVectores(int A[], int B[], int C[], int tam)

int A[ ]

int C[ ]

int tam

Error!!!

Page 11: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

EJERCICIOSEscribir una lista de funciones que realice las siguientes operaciones sobre una Matriz entera de M filas por N columnas:a. Mostrar menor elemento.b. Mostrar el mayor elemento.c. Realizar la transpuesta.d. Sumar dos matrices llevando el resultado de la suma primera de las matrices.

Page 12: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos

EJERCICIOSLos resultados de las ultimas elecciones a alcalde en el pueblo x han sido los siguientes:

Distrito Candidato A Candidato B Candidato C Candidato D

1 194 48 206 45

2 180 20 320 16

3 221 90 140 20

4 432 51 821 14

5 820 61 946 18

Escribir un programa que haga las siguientes tareas:a. Imprimir la tabla anterior con cabeceras incluidas.b. Calculas e imprimir el numero total de votos recibidos por cada candidato y el

porcentaje total de votos emitidos. Así mismo, visualizar el candidato mas votado.

c. Si algún candidato recibe mas del 50% de los votos, el programa imprimirá un mensaje declarándole ganador.

d. Si algún candidato recibe menos del 50% de los votos, el programa debe imprimir el nombre de los dos candidatos mas votados que serán los que pasen a la segunda ronda de las elecciones.

Page 13: FUNCIONES EN C USANDO ARRAYS Y MATRICES. MENU DEL DIA Repaso rápido.(Diapositivas Profesores Byron Buitrago y Sebastian Villa). Inicialización de arreglos