0% found this document useful (0 votes)
63 views

Chapter 4

This document provides an overview of compound data types in C++, specifically arrays. It defines an array as a series of elements of the same type placed in contiguous memory locations that can be referenced using an index. Arrays must be declared before use with the syntax type name[elements];. Elements can be initialized or left uninitialized. Individual elements are accessed using name[index]. Multidimensional arrays are also discussed, which can be thought of as arrays of arrays. Examples are provided for declaring, initializing, accessing, and sorting arrays.

Uploaded by

api-3700783
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Chapter 4

This document provides an overview of compound data types in C++, specifically arrays. It defines an array as a series of elements of the same type placed in contiguous memory locations that can be referenced using an index. Arrays must be declared before use with the syntax type name[elements];. Elements can be initialized or left uninitialized. Individual elements are accessed using name[index]. Multidimensional arrays are also discussed, which can be thought of as arrays of arrays. Examples are provided for declaring, initializing, accessing, and sorting arrays.

Uploaded by

api-3700783
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Compound Data Types

IGEN 2120
Introducción en Ingeniería de
Computación
Arrays
An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique
identifier. That means that, for example, we can store 5 values of type int in
an array without having to declare 5 different variables, each one with a
different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.

For example, an array to contain 5 integer values of type int called billy could
be represented like this:

where each blank panel represents an element of the array, that in this case
are integer values of type int. These elements are numbered from 0 to 4
since in arrays the first index is always 0, independently of its length.

Like a regular variable, an array must be declared before it is used. A typical


declaration for an array in C++ is:

type name [elements];


Arrays
where type is a valid type (like int, float...), name is a valid identifier and the
elements field (which is always enclosed in square brackets [ ]), specifies
how many of these elements the array has to contain.

Therefore, in order to declare an array called billy as the one shown in the
above diagram it is as simple as:

int billy [5];

NOTE: The elements field within brackets [ ] which represents the number of
elements the array is going to hold, must be a constant value, since arrays
are blocks of non-dynamic memory whose size must be determined before
execution. In order to create arrays with a variable length dynamic memory
is needed, which is explained later in these tutorials.
Initializing arrays.
When declaring a regular array of local scope (within a function, for example), if
we do not specify otherwise, its elements will not be initialized to any value
by default, so their content will be undetermined until we store some value
in them. Global and static arrays, on the other hand, are automatically
initialized filled with zeros. In both cases, local and global, when we declare
an Array, we have the possibility to assign initial values to each one of its
elements by enclosing the values in braces { }. For example:

int billy [5] = { 16, 2, 77, 40, 12071 }; This declaration would have created an
array like this:

The amount of values between braces { } must not be larger than the number of
elements that we declare for the array between square brackets [ ]. For
example, in the example of array billy we have declared that it has 5
elements and in the list of initial values within braces { } we have specified 5
values, one for each element.
Initializing arrays.
When an initialization of values is provided for an array, C++ allows the
possibility of leaving the square brackets empty [ ]. In this case, the compiler
will assume a size for the Array that matches the number of values included
between braces { }:

int billy [ ] = { 16, 2, 77, 40, 12071 };

After this declaration, Array billy would be 5 ints long, since we have provided 5
initialization values.
Accessing the values of an Array.
In any point of a program in which an array is visible, we can access the value
of any of its elements individually as if it was a normal variable, thus being
able to both read and modify its value. The format is as simple as:

name[index]

Following the previous examples in which billy had 5 elements and each of
those elements was of type int, the name which we can use to refer to each
element is the following:

For example, to store the value 75 in the third element of billy, we could write
the following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable
called a, we could write:
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type int.
Accessing the values of an Array.
Notice that the third element of billy is specified billy[2], since the first one is
billy[0], the second one is billy[1], and therefore, the third one is billy[2]. By
this same reason, its last element is billy[4]. Therefore, if we write billy[5],
we would be accessing the sixth element of billy and therefore exceeding
the size of the array.

In C++ it is syntactically correct to exceed the valid range of indices for an


Array. This can create problems, since accessing out-of-range elements do
not cause compilation errors but can cause runtime errors. The reason why
this is allowed will be seen farther ahead when we begin to use pointers.

At this point it is important to be able to clearly distinguish between the two


uses that brackets [ ] have related to arrays. They perform two differt tasks:
one is to specify the size of arrays when they are declared; and the second
one is to specify indices for concrete array elements. Do not confuse these
two possible uses of brackets [ ] with arrays.

int billy[5]; // declaration of a new Array


billy[2] = 75; // access to an element of the Array.
Arrays Example
// arrays example
#include <iostream>
using namespace std;
int billy [ ] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n]; // result = result + billy[n];
}
cout << result;
return 0;
} 12206
Arrays Example

//Uso de arreglos en C++


#include <iostream>
using namespace std;
int main()
{
int arregloEntero[10] = {0}; //Arreglo entero de 10 elementos inicializados todos en 0.
cout << "Arreglo recien declarado: " << endl;
for (int i = 0 ; i < 10 ; i++) //Notar el menor estricto (<) para ir desde 0 hasta 9
cout << "arregloEntero["<<i<<"]="<<arregloEntero[i] << endl;
cout << "Introduzca 10 nuevos valores " << endl;
for (int i = 0 ; i < 10 ; i++) //Notar el menor estricto (<) para ir desde 0 hasta 9
{
cout << " Introduzca nuevo valor para arregloEntero["<<i<<"]" << endl;
cin >> arregloEntero[i];
}
cout << "Luego de los valores introducidos, el arreglo quedo asi: " << endl;
for (int i = 0 ; i < 10 ; i++) //Notar el menor estricto (<) para ir desde 0 hasta 9
cout << "arregloEntero["<<i<<"]="<<arregloEntero[i] << endl;
return 0;
}
Ejercicios
• Hacer un programa que lea diez valores
enteros en un array desde el teclado y calcule
y muestre: la suma, el valor medio, el mayor y
el menor.
• Hacer un programa que lea diez valores
enteros en un array y los muestre en pantalla.
Después que los ordene de menor a mayor y
los vuelva a mostrar. Y finalmente que los
ordene de mayor a menor y los muestre por
tercera vez.
for (i=1; i<TAM; i++)
for (j=0 ; j<TAM - 1; j++)
if (lista[j] > lista[j+1])
temp = lista[j];
lista[j] = lista[j+1];
lista[j+1] = temp;
Vamos a ver un ejemplo. Esta es nuestra lista:
4-3-5-2-1
Tenemos 5 elementos. Es decir, TAM toma el valor 5. Comenzamos
comparando el primero con el segundo elemento. 4 es mayor que 3, así
que intercambiamos. Ahora tenemos:
3-4-5-2-1
Ahora comparamos el segundo con el tercero: 4 es menor que 5, así que no
hacemos nada. Continuamos con el tercero y el cuarto: 5 es mayor que 2.
Intercambiamos y obtenemos:
3-4-2-5-1
Comparamos el cuarto y el quinto: 5 es mayor que 1. Intercambiamos
nuevamente:
3-4-2-1-5
Repitiendo este proceso vamos obteniendo los siguientes resultados:
3-2-1-4-5
2-1-3-4-5
1-2-3-4-5
//Uso de arreglos en C++
#include <iostream>
using namespace std;
int main()
{
int temp;
int i;
int j;
int arreglo[10];
int arreglotemp[10];
for (i = 0 ; i < 10 ; i++)
{
cout << " Introduzca valor para arreglo["<<i<<"]" << endl;
cin >> arreglo[i];
}
cout << "El arreglo introducido es el siguiente: " << endl;
for (i = 0 ; i < 10 ; i++)
cout << "arreglo["<<i<<"]="<<arreglo[i] << endl;
for (i=1; i<10; i++)
{
for (j=0 ; j<10 - 1; j++)
{
if (arreglo[j] > arreglo[j+1])
{
temp = arreglo[j];
arreglo[j] = arreglo[j+1];
arreglo[j+1] = temp;
}
}
}

cout << "El arreglo ordenado de menor a mayor es: " << endl;
for (i = 0 ; i < 10 ; i++)
{
cout << "arreglo["<<i<<"]="<<arreglo[i] << endl;
arreglotemp[i]=arreglo[i];
}
for (i = 0 ; i < 10 ; i++)
{
arreglo[i]=arreglotemp[9 - i];
}

cout << "El arreglo ordenado de mayor a menor es: " << endl;
for (i = 0 ; i < 10 ; i++)
cout << "arreglo["<<i<<"]="<<arreglo[i] << endl;

return 0;
}
Multidimensional Arrays .
Multidimensional arrays can be described as "arrays of arrays". For example, a
bidimensional array can be imagined as a bidimensional table made of
elements, all of them of a same uniform data type.

jimmy represents a bidimensional array of 3 per 5 elements of type int. The way
to declare this array in C++ would be:
int jimmy [3][5];
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
jimmy[1][3]
Ejercicios
• Elabora un programa 15 8 7 6 35 8 9
en el cual puedas
introducir desde teclado
la siguiente tabla en un 48 5 2 37 10 1 6
arreglo Bidimensional:
94 58 7 58 6 45 68

• Hacer un programa que 30 15 26 10 20 30 50


lea 25 valores enteros
en una tabla de 5 por 5,
y que después muestre 1 2 7 8 9 4 6
la tabla y las sumas de
cada fila y de cada 17 28 39 74 85 96 46
columna.
//Uso de arreglos Bidimensionales en C++
#include <iostream>
using namespace std;
int main()
{
int i;
int j;
int matriz[6][7];
for (i = 0 ; i < 6 ; i++)
{
for (j = 0 ; j < 7 ; j++)
{
cout << " Introduzca valor para matriz["<<i<<"]" << "["<<j<<"]" << endl;
cin >> matriz[i][j];
}
}
cout << "El arreglo introducido es el siguiente: " << endl;
for (i = 0 ; i < 6 ; i++)
{
for (j = 0 ; j < 7 ; j++)
{
cout << "matriz["<<i<<"]" << "["<<j<<"] = " << matriz[i][j] << endl;
}
}
return 0;
}

You might also like