Intro to Arrays

  • Variables are supported in every programming language, and will have some data type.
  • At runtime a variable declared int and with value x will be stored in memory.
  • If we assume this variable takes two bytes, then two bytes will be allocated to x.
  • This type of variable is a single valued variable; can store a single variable and is also called a scalar variable.
int x = 10; // scalar variable
  • What is an array? We can store multiple values, a list / set of values. It is a collection of similar data elements grouped under one name. For an array of integer types of size 5 we can write
int A[5]; // vector variable
  • We can store 5 values in this one, and it has a single dimension. The memory will be contiguously allocated, which means the locations in memory will be side by side. Memory will be allocated together as a single block.

  • All the variables within the array has the same name. But we can differentiate them with their indices. So using the name and the index, we can access any of those integers. This is supported by every programming language.

A[2] = 15;

Declaration of Arrays

  • If I'm declaring an array with the name A, and of size 5, then this will allocate the space for five integers. This is just a declaration and the values inside will be garbage values. Nothing is initialized, so the values are unknown; random values that are not useful for us.

  • To initialize an array with values, we must initialize like this. This method is called declaration + initialization.

int A[5] = {2, 4, 6, 8, 10};
  • Third method is to mention the size, but if you don't want to initialize all the values, it's possible to initialize just a few, and the remaining ones will be initialized with zero. Because one the initialization process starts, it will try to initialize all the elements.
int A[5] = {2, 4};
int A[5] = {0};
  • Another method is to just mention the values. Then, depending on the number of elements you have mentioned in the initialization list, the array size will be the same as that one.
int A[] = {2, 4, 6, 8, 10};

Access Elements in an Array

printf("%d", A[0]);
  • For traversing elements in an array, visiting all the elements once, take the help of a for loop.
for (i = 0; i < 5; i++) {
  printf("%d", A[i]);
}
  • You can also use the index outside, and the name of an array inside the subscript.
printf("%d", 2[A]);
  • You can also use pointer arithmetic.
printf("%d", *(A + 2));