Arrays C (com exemplos)

Neste tutorial, você aprenderá a trabalhar com arrays. Você aprenderá a declarar, inicializar e acessar elementos de um array com a ajuda de exemplos.

Uma matriz é uma variável que pode armazenar vários valores. Por exemplo, se você deseja armazenar 100 inteiros, pode criar uma matriz para ele.

 int data(100); 

Como declarar um array?

 dataType arrayName (arraySize); 

Por exemplo,

 marca flutuante (5);

Aqui, declaramos uma matriz, marca, do tipo de ponto flutuante. E seu tamanho é 5. Ou seja, ele pode conter 5 valores de ponto flutuante.

É importante observar que o tamanho e o tipo de uma matriz não podem ser alterados depois de declarada.

Elementos de matriz de acesso

Você pode acessar os elementos de uma matriz por índices.

Suponha que você tenha declarado uma marca de matriz como acima. O primeiro elemento é a marca (0), o segundo elemento é a marca (1) e assim por diante.

Algumas palestras :

  • As matrizes têm 0 como o primeiro índice, não 1. Neste exemplo, marca (0) é o primeiro elemento.
  • Se o tamanho de um array for n, para acessar o último elemento, o n-1índice é usado. Neste exemplo, marque (4)
  • Suponha que o endereço inicial de mark(0)seja 2120d . Então, o endereço do mark(1)será 2124d . Da mesma forma, o endereço de mark(2)será 2128d e assim por diante.
    Isso ocorre porque o tamanho de a floaté 4 bytes.

Como inicializar um array?

É possível inicializar um array durante a declaração. Por exemplo,

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

Você também pode inicializar um array como este.

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

Aqui, não especificamos o tamanho. No entanto, o compilador sabe que seu tamanho é 5, pois o estamos inicializando com 5 elementos.

Aqui,

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

Alterar o valor dos elementos do array

 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 e saída

Veja como você pode obter a entrada do usuário e armazená-la em um 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)); 

Veja como você pode imprimir um elemento individual de uma 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)); 

Exemplo 1: entrada / saída de array

 // 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; ) 

Resultado

 Insira 5 inteiros: 1 -3 34 0 3 Exibindo inteiros: 1 -3 34 0 3 

Aqui, usamos um forloop para pegar 5 entradas do usuário e armazená-las em um array. Em seguida, usando outro forloop, esses elementos são exibidos na tela.

Exemplo 2: Calcular a média

 // 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).

Artigos interessantes...