C Arrays
Arrays
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list. A two dimensional array is like a table. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To create an array, define the data type (like int) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces:
Declaring an Array
There are various ways in which we can declare an array. It can be done by specifying its type and size, by initializing it or both.
data_type array_name[array_size];
Example - array declaration
Access the Elements of an Array
To access an array element, refer to its index number. Array indexes start with 0: [0] is the first element. [1] is the second element, etc. This statement accesses the value of the first element [0] in studentMarksData:
Change an Array Element
Refer to the index number, to change the value of a specific element.
Loop Through an Array
With the for loop you can loop through the array elements.
The following example outputs all elements in the myNumbers array:
Set Array Size
To specify the size of the array, and add elements later is the another common way to create arrays.
Example
Arrays in Detail:-
A programmer should follow the below concepts while using array:-
- Multi-dimensional Array:- Instead of writing a single array, you can also do a two-dimensional array.
- Passing arrays to functions:- You can pass an array to a function by specifying the array name.
You can pass an array to a function in two ways:-
- call by value:- Values of the actual parameters are copied into the function’s formal parameters. And these two types of parameters are stored in different memory locations.
- call by reference:- In this, the actual and formal parameters refer to the same memory locations. Any changes made into the actual parameter will affect formal parameters. To implement it, we have to use pointers.
- Return array from a function:- With the help of C, you can also return an array from a function.
- Pointer to an array:- By specifying the name of the array, one can generate a pointer to the first element of the array.