Array in C

Array in C with Examples

In this article, I am going to discuss the Array in C with Examples. Please read our previous articles, where we discussed the Preprocessing Directives in C. As part of this article, you will learn what is Array in C, it’s type and when and how to use Array in C Program with examples.

What is an Array in C?

An array is a derived data type in C which is constructed from the fundamental data type of C programming language. An array is a collection of similar types of data elements in a single entity. In implementation when we require ‘n’ no. of values of the same data type, then recommended creating an array.

When we are working with arrays always memory is constructed in a continuous memory location that’s why possible to access the data randomly. When we are working with arrays all values will share the same name with a unique identification value called ‘index’.

Always array index must be required to start with ‘0’ & ends with (size-1). When we are working with arrays, we required to use an array subscript operator i.e. [ ]. Always array subscript operators require one argument of type unsigned integer constant, whose value is always ‘>0’ only.

Arrays in C

Why we need Array?

We can use normal variables (v1, v2, v3, …) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable. C array is useful if we have to store similar elements.

For example, if we want to store the scores of a student in 6 subjects, then we don’t need to define different variables for the scores in the different subjects. Instead of that, we can define an array that can store the scores in each subject at the contiguous memory locations.

By using the array, we can easily access the elements.

Properties of Array in C:

The array contains the following properties:

  1. Each element of an array is of the same data type and carries the same size, i.e., int = 4 bytes.
  2. Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
  3. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
Characteristics of Array
  1. Arrays are always stored in consecutive memory locations.
  2. An array can store multiple values of similar type which can be referred by a single name.
  3. The array name is actually a pointer to the first location of the memory block allocated to the name of the array.
  4. An array either be an integer, character, or float data type can be initialized only during the declaration but not afterward.
  5. Any particular element of an array can be modified separately without distributing other elements.
  6. All elements of an array said the same name and they are distinguished with each other with the help of element number.
How to declare an array in C?

Syntax: datatype   array_name [ array_size ] ;
Example: take an array of integers ‘n’.
int n[6];

Here, n[ ] is used to denote an array ‘n’. It means that ‘n’ is an array. So, int n[6] means that ‘n’ is an array of 6 integers. Here, 6 is the size of the array i.e. there are 6 elements in the array ‘n’.

How to declare an array in C?

We have to specify the array size because the compiler needs to allocate space in the memory which is not possible without knowing the size. The compiler specifies the size required for an array with the help of the number of elements of an array and the size of the data type present in the array.

Here int n[6]‘ will allocate space to 6 integers. We can also declare an array by another method as shown below.

int n[ ] = {2, 3, 15, 8, 48, 13};

In this case, we are declaring and assigning values to the array at the same time. Here, there is no need to specify the array size because the compiler gets it from { 2,3,15,8,48,13 }.

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.

Array declaration by specifying size:

int arr1[10];
With recent C versions, now we can also declare an array of user specified size
int n = 10;
int arr2[n];

Array declaration by initializing elements:

int arr[] = { 10, 20, 30, 40 }
Here, compiler creates an array of size 4. The above statement is same as the below statement.
int arr[4] = {10, 20, 30, 40}

Array declaration by specifying size and initializing elements:

int arr[6] = { 10, 20, 30, 40 }
Here, compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements as 0. The above statement is same as the below statement.
int arr[] = {10, 20, 30, 40, 0, 0}

Index of an Array

In array every element has its index and we can access any elements by using its index.

Index of an Array

0, 1, 2, 3, 4, and 5 are indices. It is like they are the identity of 6 different elements of an array. The index always starts at 0. So, the first element of an array has an index of 0.

Note: The index of an array starts with 0. We access any element of an array using its index:
Syntax: array_name[index]
Example: if the name of an array is ‘n’, then to access the first element (which is at 0 index), we write n[0].

Array in C with Examples

Here,
n[0] is 2
n[1] is 3
n[2] is 15
n[3] is 8
n[4] is 48
n[5] is 13

Note: n[0], n[1], etc. are like any other variables we were using till now i.e., we can set there value as n[0] = 5; like we do with any other variables (x = 5;, y = 6;, etc.).

Assigning Values to Array in C:

By writing int n[ ]={ 2,4,8 };, we are declaring and assigning values to the array at the same time, thus initializing it.

But when we declare an array like int n[3];, we need to assign values to it separately. Because ‘int n[3];’ will allocate space of 3 integers in memory but there are no integers in that space. To initialize it, assign a value to each of the elements of the array as shown below.

Assigning Values to Array in C

It is just like we are declaring some variables and then assigning values to them.

Why we need Array?

Thus, the first way of assigning values to the elements of an array is by doing so at the time of its declaration i.e. int n[ ]={ 2,4,8 };

And the second method is declaring the array first and then assigning values to its elements as shown below.

Properties of Array in C

You can understand this by treating n[0], n[1], and n[2] as similar to different variables you used before. Just like a variable, an array can be of any other data type also.

float f[ ]= { 1.1, 1.4, 1.5}; Here, ‘f’ is an array of floats.

Program: Array Example
#include <stdio.h>
int main()
{
    int  marks[3];
    float  average;
    printf("Enter marks of first student\n");
    scanf(" %d" , &marks[0]);
    printf("Enter marks of second student\n");
    scanf(" %d" , &marks[1]);
    printf("Enter marks of third student\n");
    scanf(" %d" , &marks[2]);
    average = (marks[0] + marks[1] + marks[2]) / 3.0;
    printf ("Average marks : %f\n" , average);
    return 0;
}

Output:

Array Example in C

In the above example, the average value should be of type ‘float’ because the average of integers can be float also. While taking out the average, the sum of the numbers should be divided by 3.0 and not 3, otherwise, you will get the average value as an integer and not float.

Note: If we have declared an array with some array size and assigned values to only some elements of that array, then the values of other elements are automatically assigned zero.

Suppose we declare and initialize an array as int n[5] = { 12, 13, 5 }; This means that n[0]=12, n[1]=13 and n[2]=5 and rest all elements are zero i.e. n[3]=0 and n[4]=0.

Similarly,

int n[5];
n[0] = 12;
n[1] = 13;
n[2] = 5;

In the above code, n[0], n[1] and n[2] are initialized to 12, 13 and 5 respectively. Therefore, n[4] and n[5] are both 0.

Note: Array allocates contiguous memory. Thus, if the address of the first element of an array of integers is 223698688 then the address of the second element will be 223698692 (223698688+4 (4 is the size of one integer)) and third will be 223698696 and so on. This means that the memories of all elements of an array are allocated together and are continuous.

Runtime Array initialization in C:

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large arrays or to initialize arrays with user-specified values.

Example:

#include<stdio.h>
void main()
{
    int arr[3];
    int i, j;
    printf("Enter array element :");
    for(i = 0; i < 3; i++)
    {
        scanf("%d", &arr[i]);    //Run time array initialization
    }
    printf("Array elements are : ");
    for(j = 0; j < 3; j++)
    {
        printf("%d\n", arr[j]);
    }
}

Output:

Runtime Array initialization in C

Input data into the array

Here, the size of the array is 5. Inside the loop, we are displaying a message to the user to enter the number. All the input values are stored in similar array elements using the scanf function.

for (i=0; i<5; i++)
{
        printf(“Enter the number %d \n”, (i+1));
        scanf(“%d”, &num[i]);
}

Reading out data from an array

If we want to display the elements of the array then we can display like this.
for (i=0; i<5;i++)
{
       printf(“num[%d]\n”, num[i]);
}

Access Array Elements in C:

We can access elements of an array by index. Suppose we declared an array n. The first element is n[0], the second element is n[1], and so on.

Accessing Arrays Elements in C

Arrays have 0 as the first index, not 1. For example, n[0] is the first element. If the size of an array is 7, to access the last element, the 7-1 index is used. For example n[6]=10

Note: Array allocates contiguous memory. Thus, if the address of the first element of an array of integers is 223698684 then the address of the second element will be 223698688 (223698684+4 (4 is the size of 1 integer)) and third will be 223698692 and so on. This means that the memories of all elements of an array are allocated together in a continuous manner.

Facts about Array in C:

Array elements are accessed by using an integer index. Array index starts with 0 and goes till the size of array minus 1.

Example:

#include <stdio.h> 
int main() 
{ 
    int arr[5]; 
    arr[0] = 5; 
    arr[2] = -10; 
    arr[3 / 2] = 2; // this is same as arr[1] = 2 
    arr[3] = arr[0]; 
    printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]); 
    return 0; 
}

Output: 5 2 -10 5

There is no index out of bounds checking in C, for example, the following program compiles fine but may produce unexpected output when run.

#include <stdio.h> 
int main() 
{ 
    int arr[2]; 
    printf("%d ", arr[3]); 
    printf("%d ", arr[-2]); 
    return 0; 
}

Output: no index out of bounds checking in C

In C, it is not compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just Warning.

#include <stdio.h> 
int main() 
{ 
    // Array declaration by initializing it with more elements than specified size. 
    int arr[2] = { 10, 20, 30, 40, 50 }; 
    return 0; 
}

Output:

initialize an array with more elements than the specified size

The array elements are stored at contiguous memory locations. The following C program demonstrates that array elements are stored contiguous locations

#include <stdio.h> 
int main() 
{ 
    // an array of 10 integers. If arr[0] is stored at address x, 
    // then arr[1] is stored at x + sizeof(int) 
    // arr[2] is stored at x + sizeof(int) + sizeof(int) and so on. 
    int arr[5], i; 
    printf("Size of integer in this compiler is %lu\n", sizeof(int)); 
    for (i = 0; i < 5; i++) 
    // The use of '&' before a variable name, yields address of variable. 
    printf("Address arr[%d] is %p\n", i, &arr[i]); 
    return 0; 
}

Output:

array elements are stored at contiguous memory locations

Advantage of C Array
  1. Code Optimization: By using an array only a few lines of code are required to access the data.
  2. Ease of traversing: By using the for loop, we can easily traverse the elements of an array.
  3. Ease of sorting: Only a few lines of code are required to sort the elements of an array.
  4. Random Access: We can randomly access any of the elements by using an array.
The disadvantage of C Array

Fixed Size: Whatever size, we define at the time of declaration of the array, we can’t exceed the limit. So, it doesn’t grow the size dynamically.

Insertion and deletion Costly: Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.

Operation of an Array:
  1. Traversing: Process each and every element in the array sequentially.
  2. Searching: Searching an element to find out the element is present or not.
  3. Sorting: Arranging the element in an array in a particular sequence.
  4. Inserting: To insert the element into the array.
  5. Deleting: To delete the element from the array.
Types of C Arrays:

There are 2 types of C arrays. They are,

  1. One dimensional array
  2. Multi-dimensional array (Two-dimensional array, Three-dimensional array, Four-dimensional array, etc…)

In the next article, I am going to discuss One dimensional array in C with examples. Here, in this article, I try to explain Arrays in C. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article

Leave a Reply

Your email address will not be published. Required fields are marked *