La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument.

Presentaciones similares


Presentación del tema: "1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument."— Transcripción de la presentación:

1 1 Chapter 12 Arrays Dale/Weems/Headington

2 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument Using const in Function Prototypes Using an Array of struct or class Objects Using an enum Index Type for an Array l Declaring and Using a Two-Dimensional Array l Two-Dimensional Arrays as Function Parameters l Declaring a Multidimensional Array

3 3 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

4 4 Structured Data Type Un “structured data type” es un tipo de dato que: l Almacena una colección de componentes individuales con un nombre de variable l Permite a cada componente individual ser alamcenado y acedido

5 5 Declarar variables para almacenar y sumar 3 muestras de presiones sanguíneas int bp1, bp2, bp3; int total; 400240004004 bp2bp1bp3 cin >> bp1 >> bp2 >> bp3; total = bp1 + bp2 + bp3;

6 6 ¿Qué pasaría si se desea almacenar un total de 1000 muestras de sangre? int bp[ 1000 ] ; // declares an array of 1000 int values bp[0] bp[1] bp[2].... bp[999] 5000 5002 5004 5006....

7 7 Definición de un arreglo de una sola Dimensión Un arreglo es una colección estructurada de componentes (llamados elementos) del mismo tipo de dato, utilizando solamente un nombre. Estos datos se almacenan en localizaciones adyacentes de memoria. Los componentes se pueden aceder individualmente utilizando el nombre del arreglo en unión a un valor entero que se pone entre “brackets”. El índice indica la posición del componente dentro del arreglo.

8 8 Otro Ejemplo Declare un arreglo llamado temps el cual puede almacenar hasta 5 valores individuales tipo float. float temps[5]; // declaration allocates memory temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 numero de elementos en el arreglo indexes or subscripts Base Address

9 9 Declaracion de un Arreglo l El índice(“index”) tambien se le dice suscrito (“subscript“) l En C++, el primer elemento del arreglo siempre comienza con suscrito 0. El segundo elemento tiene suscrito de 1, etc. l La dirección base (“base address“) de un arreglo es su dirección inicial en memoria. SYNTAX DataType ArrayName [ConstIntExpression];

10 10 Otro Ejemplo Mas… Declare un arreglo llamado name el cual puede tener hasta 10 valores individuales tipo char. char name[10]; // declaration allocates memory numero de elementos en el arreglo name[0] name[1] name[2] name[3] name[4]..... name[9] 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 Base Address

11 11 Asignando Valores a Elementos Individuales de un Arreglo float temps[ 5 ] ; // allocates memory for array int m = 4 ; temps[ 2 ] = 98.6 ; temps[ 3 ] = 101.2 ; temps[ 0 ] = 99.4 ; temps[ m ] = temps[ 3 ] / 2.0 ; temps[ 1 ] = temps[ 3 ] - 1.2 ; // what value is assigned? temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6

12 12 ¿ Qué valores se asignan? float temps[ 5 ] ; // allocates memory for array int m ; for (m = 0; m < 5; m++) { temps[ m ] = 100.0 + m  0.2 ; } temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 ? ? ? ? ?

13 13 Y ahora… ¿ Que valores se imprimen? float temps[ 5 ] ; // allocates memory for array int m ;..... for (m = 4; m >= 0; m-- ) { cout << temps[ m ] << endl ; } temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8

14 14 Variables en los Suscritos float temps[ 5 ] ; // allocates memory for array int m = 3 ;...... What is temps [ m + 1] ? What is temps [ m ] + 1 ? temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8

15 15 Un Vistazo al Compilador float temps[5]; // this declaration allocates memory Para el compilador, el valor del “identifier” temps solo es la dirección base del arreglo. Decimos que temps es un “pointer” (debido a que su valor es una dirreción). Lo que hace esa dirección es “apuntar” a una localización de memoria. temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8

16 16 Inicializando en una Declaración int ages[ 5 ] = { 40, 13, 20, 19, 36 } ; for ( int m = 0; m < 5; m++ ) { cout << ages[ m ] ; } ages[0] ages[1] ages[2] ages[3] ages[4] 6000 6002 6004 6006 6008 40 13 20 19 36

17 17 Pasando Arreglos como Argumentos l en C++, los arreglos siempre se pasan por referencia l siempre que un arreglo se pase como un argumento, su “base address” es enviado a la función invocada

18 18 En C++, no hay operaciones “Aggregate” para los arreglos l Lo único que se puede hacer con un arreglo entero como un todo (“aggregate”) independientemente de su tipo de dato es pasarlo como un argumento a una funcion l EXCEPCIÓN: “aggregate I/O” es permitida para strings en C (Ciertos arreglos especiales de tipo char)

19 19 Usando Arreglos como Argumentos en Funciones Generalmente, las funciones que trabajan con arreglos, requieren 2 items como argumentos: l La dirección inicial de memoria del arreglo (“base address”) l El número de elementos para procesar en el arreglo

20 20 #include void Obtain ( int [ ], int ) ; // prototypes here void FindWarmest ( const int[ ], int, int & ) ; void FindAverage ( const int[ ], int, int & ) ; void Print ( const int [ ], int ) ; using namespace std ; int main ( ) { int temp[31] ; // array to hold up to 31 temperatures int numDays ; int average ; int hottest ; int m ; Ejemplo con Parámetros en Arreglos 20

21 21 cout << “How many daily temperatures? ” ; cin >> numDays ; Obtain( temp, numDays ) ; // call passes value of numDays and // address of array temp to function cout << numDays << “ temperatures“ << endl ; Print ( temp, numDays ) ; FindAverage ( temp, numDays, average ) ; FindWarmest ( temp, numDays, hottest ) ; cout << endl << “Average was: “ << average << endl ; cout << “Highest was: “ << hottest << endl ; return 0 ; } Ejemplo (continuación) 21

22 22 Localizar en Memoria para el Arreglo temp[0] temp[1] temp[2] temp[3] temp[4]..... temp[30] 6000 Base Address 50 65 70 62 68...... int temp[31] ; // array to hold up to 31 temperatures

23 23 void Obtain ( /* out */ int temp [ ], /* in */ int number ) // Has user enter number temperature values at keyboard // Precondition: // number is assigned && number > 0 // Postcondition: // temp [ 0.. number -1 ] are assigned { int m; for ( m = 0 ; m < number; m++ ) { cout << “Enter a temperature : “ ; cin >> temp [m] ; } 23

24 24 void Print ( /* in */ const int temp [ ], /* in */ int number ) // Prints number temperature values to screen // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // temp [ 0.. number -1 ] have been printed 5 to a line { int m; cout << “You entered: “ ; for ( m = 0 ; m < number; m++ ) { if ( m % 5 == 0 ) cout << endl ; cout << setw(7) << temp [m] ; } 24

25 25 El uso de const l Es debido a que el “identifier” de un arreglo mantiene el “base address” del arreglo. Por lo tanto el ‘&’ no se necesita para un arreglo en la lista de parámetros. l Los arreglos siempre se pasan por referencia l Para prevenir que elementos de un arreglo se cambien sin intencion en la función, se pone const en el encabezamiento de la función y en el prototipo

26 26 Uso de const en los prototipos void Obtain ( int [ ], int ) ; void FindWarmest ( const int [ ], int, int & ) ; void FindAverage ( const int [ ], int, int & ) ; void Print ( const int [ ], int ) ; No usar const en funciones donde se va a modificar el contenido (elementos) del arreglo Utilizar const en funciones que solo van a leer valores del arreglo para prevenir que se puedan modificar

27 27 void FindAverage ( /* in */ const int temp [ ], /* in */ int number, /* out */ int & avg ) // Determines average of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // avg == arithmetic average of temp[0.. number-1] { int m; int total = 0; for ( m = 0 ; m < number; m++ ) { total = total + temp [m] ; } avg = int (float (total) / float (number) +.5) ; } 27

28 28 void FindWarmest ( /* in */ const int temp [ ], /* in */ int number, /* out */ int & largest ) // Determines largest of temp[0.. number-1] // Precondition: // number is assigned && number > 0 // temp [0.. number -1 ] are assigned // Postcondition: // largest== largest value in temp[0.. number-1] { int m; largest = temp[0] ; // initialize largest to first element // then compare with other elements for ( m = 0 ; m < number; m++ ) { if ( temp [m] > largest ) largest = temp[m] ; } 28

29 29 Usando Arreglos para Contadores l Escriba un programa para contar el número de cada letra del alfabeto en un archivo de texto letterASCII ‘A’ 65 ‘B’ 66 ‘C’ 67 ‘D’ 68.. ‘Z’ 90 This is my text file. It contains many things! 5 + 8 is not 14. Is it? A:\my.dat

30 30 const int SIZE = 91; int freqCount[SIZE]; freqCount [ 0 ] 0 freqCount [ 1] 0.. freqCount [ 65 ] 2 freqCount [ 66 ] 0.. freqCount [ 89] 1 freqCount [ 90 ] 0 Sin uso counts ‘A’ and ‘a’ counts ‘B’ and ‘b’. counts ‘ Y’ and ‘y’ counts ‘Z’ and ‘z’

31 31 Pseudocódigo del módulo Main Level 0 Open dataFile (and verify success) Zero out freqCount Read ch from dataFile WHILE NOT EOF on dataFile If ch is alphabetic character If ch is lowercase alphabetic Change ch to uppercase Increment freqCount[ch] by 1 Read ch from dataFile Print characters and frequencies

32 32 // Program counts frequency of each alphabetic character in text file. #include const int SIZE 91; void PrintOccurrences ( const int [ ] ) ; // prototype using namespace std ; Contando Frecuencia de los caracteres alfabéticos

33 33 int main ( ) { ifstream dataFile ; int freqCount [SIZE ] ; char ch ; char index; dataFile.open ( “A:\\my.dat” ) ; // open and verify success if ( ! dataFile ) { cout << “ CAN’T OPEN INPUT FILE ! “ << endl; return 1; } for ( int m = 0; m < SIZE; m++ )// zero out the array freqCount [ m ] = 0 ; 33

34 34 // read file one character at a time dataFile.get ( ch ) ;// priming read while ( dataFile )// while last read was successful { if (isalpha ( ch ) ) { if ( islower ( ch ) ) ch = toupper ( ch ) ; freqCount [ ch ] = freqCount [ ch ] + 1 ; } dataFile. get ( ch ) ; // get next character } PrintOccurrences ( freqCount ) ; return 0; } 34

35 35 void PrintOccurrences ( /* in */ const int freqCount [ ] ) // Prints each alphabet character and its frequency // Precondition: //freqCount [ ‘A’.. ‘Z’ ] are assigned // Postcondition: //freqCount [ ‘A’.. ‘Z’ ] have been printed {char index ; cout << “File contained “ << endl ; cout << “LETTER OCCURRENCES” << endl ; for ( index = ‘A’ ; index < = ‘Z’ ; index ++ ) { cout << setw ( 4 ) << index << setw ( 10 ) << freqCount [ index ] << endl ; } 35

36 36 Más sobre el índice del arreglo “array index” El “array index” puede ser “integral” de cualquier tipo. Esto incluye char y enum. l Es responsabilidad del programador asegurarse de que el índice (suscrito) no se salga de los límites del arreglo. El índice debe tener un rango entre cero hasta el tamaño del arreglo menos uno. l Si se utiliza un índice con valor mayor al del suscrito, causa que el programa aceda localizaciones de memoria fuera del arreglo con valores impredecibles.

37 37 Arreglo utilizando un índice tipo enum DECLARACIÓN enum Department { WOMENS, MENS, CHILDRENS, LINENS, HOUSEWARES, ELECTRONICS }; float salesAmt [ 6 ] ; Department which; USO for ( which = WOMENS ; which <= ELECTRONICS ; which = Department ( which + 1 ) ) cout << salesAmt [ which ] << endl; 37

38 38 float salesAmt[6]; salesAmt [ WOMENS ] ( i. e. salesAmt [ 0 ] ) salesAmt [ MENS] ( i. e. salesAmt [ 1 ] ) salesAmt [ CHILDRENS ] ( i. e. salesAmt [ 2 ] ) salesAmt [ LINENS ] ( i. e. salesAmt [ 3 ] ) salesAmt [ HOUSEWARES ] ( i. e. salesAmt [ 4 ] ) salesAmt [ ELECTRONICS ] ( i. e. salesAmt [ 5 ] )

39 39 Arreglos Paralelos DEFINICIÓN Arreglos paralelos son 2 o mas arreglos que tienen la misma cantidad de elementos y tienen relación entre si a nivel del índice. Posiblemente tienen diferente tipos de datos. EXAMPLE const int SIZE 50 ; int idNumber [ SIZE ] ; float hourlyWage [ SIZE ] ; Arreglos paralelos

40 40 const int SIZE 50 ; int idNumber [ SIZE ] ; // parallel arrays hold float hourlyWage [ SIZE ] ; // related information idNumber [ 0 ] 4562 hourlyWage [ 0 ] 9.68 idNumber [ 1 ] 1235 hourlyWage [ 1 ] 45.75 idNumber [ 2 ] 6278 hourlyWage [ 2 ] 12.71.... idNumber [ 48 ] 8754 hourlyWage [ 48 ] 67.96 idNumber [ 49 ] 2460 hourlyWage [ 49 ] 8.97

41 41 Arreglo de Estructuras (“struct”) const int MAX_SIZE = 500 ; enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType// declares struct data type { long id ; string name ; string genus ; string species ; string country ; // 8 struct members int age ; float weight ; HealthType health ; } ; AnimalType bronxZoo [ MAX_SIZE ] ;// declares array 41

42 42 AnimalType bronxZoo[MAX_SIZE]; bronxZoo [ 0 ] [ 1 ].. [ 498 ] [ 499 ] bronxZoo [ 0 ].id 3456219 bronxZoo [ 0 ].name “camel” bronxZoo [ 0 ].genus “Camelus” bronxZoo [ 0 ].species “dromedarius” bronxZoo [ 0 ].country “India” bronxZoo [ 0 ].age 10 bronxZoo [ 0 ].weight 992.8 bronxZoo [ 0 ].health Fair

43 43 AnimalType bronxZoo[MAX_SIZE];.id.name.genus.species. country. age. weight. health bronxZoo [ 0 ] 3456219 “camel” “Camelus”“dromedarius” “India” 10 992.8 Fair bronxZoo [ 1 ] bronxZoo [ 2 ] bronxZoo [ 3 ]. bronxZoo[498] bronxZoo[499]

44 44 Sumar 1 al campo age en cada elemento del arreglo bronxZoo for ( j = 0 ; j < MAX_SIZE ; j++ ) bronxZoo[ j ].age = bronxZoo[ j ].age + 1 ; OR, for ( j = 0 ; j < MAX_SIZE ; j++ ) bronxZoo[ j ].age++ ;

45 45 Encontrar el peso total de todos los elementos en el arreglo bronxZoo float total = 0.0 ; for ( j = 0 ; j < MAX_SIZE ; j++ ) total += bronxZoo[ j ].weight ;

46 46 Arreglo de Dos Dimensiones Es una colección de componentes, todos del mismo tipo de dato, estructurado en dos dimensiones (filas y columnas). Cada elemento por individual se acede por un par de índices que representan la posición del elemento en cada dimensión. DataType ArrayName [ConstIntExpr] [ConstIntExpr]... ; SYNTAX FOR ARRAY DECLARATION

47 47 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 66 64 72 78 85 90 99 105 98 90 88 80 row 2, col 7 might be Arizona’s high for August EJEMPLO – Para mantener mensualmente las temperaturas altas para los 50 estados en un solo arreglo. const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 1 ] [ 2 ].. stateHighs [2] [7]. [ 48 ] [ 49 ]

48 48 [JAN]... [AUG].. [DEC] 66 64 72 78 85 90 99 105 98 90 88 80 row 2, col AUG could be Arizona’s high for August enum MonthType { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } ; const int NUM_MONTHS = 12 ; const int NUM_STATES = 50 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 1 ] [ 2 ].. stateHighs [2] [AUG]. [ 48 ] [ 49 ]

49 49 enum StateType { AL, AK, AZ, AR, CA, CO, CT, DE, FL, GA, HI, ID, IL, IN, IA, KS, KY, LA, ME, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, OH, OK, OR, PA, RI, SC, SD, TN, TX, UT, VT, VA, WA, WV, WI, WY }; enum MonthType { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } ; const int NUM_MONTHS = 12 ; const int NUM_STATES = 50 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ AL] [ AK] [ AZ].. stateHighs [AZ] [AUG]. [ WI ] [ WY] [JAN]... [AUG].. [DEC] 66 64 72 78 85 90 99 105 98 90 88 80 row AZ, col AUG holds Arizona’s high for August

50 50 Buscando la temperatura alta promedio de los 12 meses para el Estado de Arizona int total = 0 ; int month ;// WITHOUT ENUM TYPES int average ; for ( month = 0 ; month < NUM_MONTHS ; month ++ ) total = total + stateHighs [ 2 ] [ month ] ; average = int ( total / 12.0 + 0.5 ) ; average 85

51 51 Buscando la temperatura alta promedio de los 12 meses para el Estado de Arizona int total = 0 ; MonthType month ; // WITH ENUM TYPES DEFINED int average ; for ( month = JAN ; month <= DEC ; month = MonthType( month + 1) ) total = total + stateHighs [ AZ] [ month ] ; average = int ( total / 12.0 + 0.5 ) ; average 85

52 52 const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; l En memoria, C++ almacena los arreglos en forma de fila. La primera fila es seguida por la segunda y asi por el estilo. Base Address... 12 highs for state 0 12 highs for state 1 etc. Alabama Alaska first row second row 800080248048 Almacenamiento filas columnas

53 53 Visto de otra forma... stateHighs[ 0 ] [ 0 ] stateHighs[ 0 ] [ 1 ] stateHighs[ 0 ] [ 2 ] stateHighs[ 0 ] [ 3 ] stateHighs[ 0 ] [ 4 ] stateHighs[ 0 ] [ 5 ] stateHighs[ 0 ] [ 6 ] stateHighs[ 0 ] [ 7 ] stateHighs[ 0 ] [ 8 ] stateHighs[ 0 ] [ 9 ] stateHighs[ 0 ] [10 ] stateHighs[ 0 ] [11 ] stateHighs[ 1 ] [ 0 ] stateHighs[ 1 ] [ 1 ] stateHighs[ 1 ] [ 2 ] stateHighs[ 1 ] [ 3 ]. Para localizar un elemento como: stateHighs [ 2 ] [ 7] El compilador necesita saber que hay 12 columnas en este arreglo de 2 dimensiones. At what address will stateHighs [ 2 ] [ 7 ] be found? Assume 2 bytes for type int. Base Address 8000

54 54 Arreglos como Parametros l Al igual que los arreglos de una sola dimensión, al pasar un arreglo bidimensional como argumento, lo que se envia a la función es la dirección de memoria de ese arreglo de dos dimensiones. l El tamaño de todas las dimensiones, menos la primera, debe ser incluida en el encabezamiento y prototipo de la función. l Los tamaños de esas dimensiones en la lista de parámetros de la función debe ser la misma que se declaro cuando se definio el arreglo.

55 55 const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; int stateAverages [ NUM_STATES ] ; [ 0 ] 62 [ 1 ] 85 [ 2 ]. [ 48 ] [ 49 ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 43 42 50 55 60 78 80 85 81 72 63 40 66 64 72 78 85 90 99 105 98 90 88 80 Escribir una función que use el arreglo bi-dimensional stateHighs para crear un arreglo de una sola dimensión que tenga las temperaturas altas promedios Alaska Arizona 55

56 56 void FindAverages( /* in */ const int stateHighs [ ] [ NUM_MONTHS], /* out */ int stateAverages [ ] ) // PRE: stateHighs[ 0..NUM_STATES] [ 0..NUM_MONTHS] assigned // POST: stateAverages[ 0..NUM_STATES] contains rounded average // high temperature for each state { int state; int month; int total; for ( state = 0 ; state < NUM_STATES; state++ ) { total = 0 ; for ( month = 0 ; month < NUM_MONTHS ; month++ ) total += stateHighs [ state ] [ month ] ; stateAverages [ state ] = int ( total / 12.0 + 0.5 ) ; } 56

57 57 Utilizando typedef con Arreglos Ayuda a eliminar las prosibilidades de error en el largo del arreglo entre los argumentos y los parámetros. Por Ejemplo; typedef int StateHighsType [ NUM_STATES ] [ NUM_MONTHS ] ; typedef int StateAveragesType [ NUM_STATES ] ; void FindAverages( /* in */ const StateHighsType stateHighs, /* out */ StateAveragesType stateAverages ) {. } 57

58 58 Declaring Multidimensional Arrays Ejemplo de un Arreglo de tres Dimensiones const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson int monthlySales [ NUM_DEPTS ] [ NUM_MONTHS ] [ NUM_STORES ] ; rows columns sheets OR USING TYPEDEF typedef int MonthlySalesType [NUM_DEPTS] [NUM_MONTHS] [NUM_STORES] ; MonthlySalesType monthlySales; 58

59 59 const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson int monthlySales [ NUM_DEPTS ] [ NUM_MONTHS ] [ NUM_STORES ] ; monthlySales [ 3 ][ 7 ][ 0 ] sales for electronics in August at White Marsh 12 MONTHS columns 5 DEPTS rows 3 STORES sheets

60 60 COMBINED SALES FOR January DEPT # DEPT NAMESALES $ 0 Mens 8345 1 Womens 9298 2 Childrens 7645 3 Electronics 14567 4 Furniture 21016.... COMBINED SALES FOR December DEPT # DEPT NAMESALES $ 0 Mens 12345 1 Womens 13200 2 Childrens 11176 3 Electronics 22567 4 Furniture 11230 Imprimir las ventas de cada mes por departamento de todas las tiendas

61 61 const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson int monthlySales [NUM_DEPTS] [NUM_MONTHS] [ NUM_STORES] ;.. for ( month = 0 ; month < NUM_MONTHS ; month++ ) { cout << “COMBINED SALES FOR ” ; WriteOut(month) ; // function call to write the name of month cout << “DEPT # DEPT NAMESALES $” << endl; for (dept = 0 ; dept < NUM_DEPTS ; dept++ ) { totalSales = 0; // sum over all stores for (store = 0 ; store < NUM_STORES ; store++ ) totalSales = totalSales + monthlySales [dept] [month] [store] ; WriteDeptNameAndSales(dept, totalSales ) ; // function call } 61

62 62 Incluir una cuarta Dimensión... const NUM_DEPTS = 5 ; // mens, womens, childrens, electronics, furniture const NUM_MONTHS = 12 ; const NUM_STORES = 3 ; // White Marsh, Owings Mills, Towson const NUM_YEARS = 2 ; int moreSales [NUM_DEPTS] [NUM_MONTHS] [ NUM_STORES] [NUM_YEARS] ; moreSales[3] [7] [0] [1] year 0year 1 for electronics, August, White Marsh, one year after starting year


Descargar ppt "1 Chapter 12 Arrays Dale/Weems/Headington. 2 Chapter 12 Topics l Declaring and Using a One-Dimensional Array l Passing an Array as a Function Argument."

Presentaciones similares


Anuncios Google