Matrices C (con ejemplos)

En este tutorial, aprenderá a trabajar con matrices. Aprenderá a declarar, inicializar y acceder a elementos de una matriz con la ayuda de ejemplos.

Una matriz es una variable que puede almacenar varios valores. Por ejemplo, si desea almacenar 100 enteros, puede crear una matriz para ello.

 int data(100); 

¿Cómo declarar una matriz?

 dataType arrayName (tamaño de matriz); 

Por ejemplo,

 marca de flotación (5);

Aquí, declaramos una matriz, marca, de tipo de punto flotante. Y su tamaño es 5. Es decir, puede contener 5 valores de punto flotante.

Es importante tener en cuenta que el tamaño y el tipo de una matriz no se pueden cambiar una vez que se declara.

Acceso a elementos de matriz

Puede acceder a los elementos de una matriz mediante índices.

Suponga que declaró una marca de matriz como se indicó anteriormente. El primer elemento es marca (0), el segundo elemento es marca (1) y así sucesivamente.

Algunas notas clave :

  • Las matrices tienen 0 como primer índice, no 1. En este ejemplo, mark (0) es el primer elemento.
  • Si el tamaño de una matriz es n, para acceder al último elemento, n-1se utiliza el índice. En este ejemplo, marque (4)
  • Suponga que la dirección inicial de mark(0)es 2120d . Entonces, la dirección del mark(1)será 2124d . Del mismo modo, la dirección de mark(2)será 2128d y así sucesivamente.
    Esto se debe a que el tamaño de a floates de 4 bytes.

¿Cómo inicializar una matriz?

Es posible inicializar una matriz durante la declaración. Por ejemplo,

 int mark(5) = (19, 10, 8, 17, 9);

También puede inicializar una matriz como esta.

 int mark() = (19, 10, 8, 17, 9);

Aquí, no hemos especificado el tamaño. Sin embargo, el compilador sabe que su tamaño es 5 ya que lo estamos inicializando con 5 elementos.

Aquí,

 la marca (0) es igual a 19 marca (1) es igual a 10 marca (2) es igual a 8 marca (3) es igual a 17 marca (4) es igual a 9

Cambiar el valor de los elementos de la matriz

 int mark(5) = (19, 10, 8, 17, 9) // make the value of the third element to -1 mark(2) = -1; // make the value of the fifth element to 0 mark(4) = 0; 

Elementos de matriz de entrada y salida

Así es como puede tomar la entrada del usuario y almacenarla en un elemento de matriz.

 // take input and store it in the 3rd element scanf("%d", &mark(2)); // take input and store it in the ith element scanf("%d", &mark(i-1)); 

He aquí cómo puede imprimir un elemento individual de una matriz.

 // print the first element of the array printf("%d", mark(0)); // print the third element of the array printf("%d", mark(2)); // print ith element of the array printf("%d", mark(i-1)); 

Ejemplo 1: entrada / salida de matriz

 // Program to take 5 values from the user and store them in an array // Print the elements stored in the array #include int main() ( int values(5); printf("Enter 5 integers: "); // taking input and storing it in an array for(int i = 0; i < 5; ++i) ( scanf("%d", &values(i)); ) printf("Displaying integers: "); // printing elements of an array for(int i = 0; i < 5; ++i) ( printf("%d", values(i)); ) return 0; ) 

Salida

 Ingrese 5 enteros: 1-3 34 0 3 Visualización de enteros: 1-3 34 0 3 

Aquí, hemos utilizado un forbucle para tomar 5 entradas del usuario y almacenarlas en una matriz. Luego, usando otro forbucle, estos elementos se muestran en la pantalla.

Ejemplo 2: Calcular promedio

 // Program to find the average of n numbers using arrays #include int main() ( int marks(10), i, n, sum = 0, average; printf("Enter number of elements: "); scanf("%d", &n); for(i=0; i  

Output

 Enter n: 5 Enter number1: 45 Enter number2: 35 Enter number3: 38 Enter number4: 31 Enter number5: 49 Average = 39 

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

 int testArray(10);

You can access the array elements from testArray(0) to testArray(9).

Now let's say if you try to access testArray(12). The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.

Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays

In this tutorial, you learned about arrays. These arrays are called one-dimensional arrays.

In the next tutorial, you will learn about multidimensional arrays (array of an array).

Articulos interesantes...