Array in C – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Tue, 27 Jun 2023 03:59:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Array in C – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Multi-Dimensional Array in C https://shishirkant.com/multi-dimensional-array-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=multi-dimensional-array-in-c Tue, 27 Jun 2023 03:59:03 +0000 https://shishirkant.com/?p=3935 Multi-Dimensional Array in C Language:

An array of arrays is called a multi-dimensional array. In simple words, an array created with more than one dimension (size) is called a multi-dimensional array. The multi-dimensional array can be of a two-dimensional array or three-dimensional array or four-dimensional array or more. 

Syntax: type name[size1][size2]…[sizeN];
Example: int a[3][3][3];

Program to understand Multi-Dimensional Array in C Language:
#include <stdio.h>
void arr(int x[][3]); //function prototype
int main ()
{ 
  int a[2][3] = {{1,2,3}, {4,5,6}}; //initializing array
  int b[2][3] = {1, 2, 3, 4, 5};
  int c[2][3] = {{1, 2}, {4}};
  printf("values in array a by row:\n");
  arr(a);
  printf("values in array b by row:\n");
  arr(b);
  printf("values in array c by row:\n");
  arr(c);
return 0;
} // end of main
void arr(int x[][3])
{
  int i; //row counter
  int j; //column counter
  for (i = 0; i <= 1; ++i)
  {
   for (j = 0; j<= 2; ++j)
   {
     printf("%d", x[i][j]);
   } //end of inner for
  printf("\n");
  } //end of outer for
 }
Output:
Multi-Dimensional Array in C

The most popular and commonly used multi-dimensional array is a two-dimensional array. The 2-D arrays are used to store data in the form of a table. We also use 2-D arrays to create mathematical matrices.

Two-Dimensional Array in C Language:

The Two-dimensional array is nothing but a table with rows and columns. A two-dimensional array can be expressed as a contiguous and tabular block in memory where the data can be stored in a table structure.

Declaration of Two-Dimensional Array in C Language
Syntax: datatype arrayName [ rowSize ] [ columnSize ];

Initialization of Two-Dimensional Array in C Language
Syntax: datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, …},{r2c1, r2c2,…}…};

Example: int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} };

The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and the second row is initialized with values 4, 5 & 6. We can also initialize as follows:

Two-Dimensional Array in C
Accessing Individual Elements of Two-Dimensional Array in C Language

To access elements of a two-dimensional array we use the array name with the row index value and column index value of the element that is to be accessed. Here the row and column index values must be in separate square braces. In the case of the two-dimensional array, the compiler assigns separate index values for rows and columns.

Syntax: arrayName [ rowIndex ] [ columnIndex ];
Example: a[0][1] = 20;
Here, the element with row index 0 and column index 1 of the array a is assigned a value of 10.

Implementation of Two-Dimensional Array in C Language:

A two-dimensional array can be implemented in two ways:

  1. Row major implementation
  2. Column major implementation
#include <stdio.h>
#define ROW_SIZE 4 // Define constant row size
#define COL_SIZE 3 // Define constant column size
int main()
{
  int matrix[ROW_SIZE][COL_SIZE];
  int row, col;
  printf("Enter elements in matrix of size %dx%d \n", ROW_SIZE, COL_SIZE);
  /* Outer loop to iterate through each row */
  for(row=0; row<ROW_SIZE; row++)
  {
   /* Inner loop to iterate through columns of each row */
   for(col=0; col<COL_SIZE; col++)
   {
     /* Input element in array */
     scanf("%d", &matrix[row][col]);
   }
  }

/* Print all elements of array */
printf("\nElements in matrix are: \n"); 
for(row=0; row<ROW_SIZE; row++)
{
  for(col=0; col<COL_SIZE; col++)
  {
    printf("%d ", matrix[row][col]);
  }
 printf("\n");
}
return 0;
}
Output:
Implementation of Two-Dimensional Array in C
Points to Remember while working with 2D Array in C:
  1. In a 2d array, elements are arranged in rows and columns format.
  2. When we are working with the 2D array we require to use 2 subscript operators which indicate the row and column sizes.
  3. In a 2D array when we are referring to one subscript operator then it gives the rows address, 2nd subscript operator gives the element
  4. The main memory of the 2D array is rows and the sub-memory is columns.
  5. On the 2D array, the array name always gives the main memory that is the 1st-row base address, arr+1 will give the next row base address.
Program for 3-D Array in C Language:
#include <stdio.h>
#define SIZE1 2
#define SIZE2 2
#define SIZE3 3
int main()
{
 int arr[SIZE1][SIZE2][SIZE3];
 int i, j, k;
 /*Input elements in array*/
 printf("Enter elements in three-dimensional array of size %dx%dx%d \n", SIZE1, SIZE2, SIZE3);

 for(i = 0; i < SIZE1; i++)
 {
   for(j = 0; j < SIZE2; j++)
   {
     for (k = 0; k < SIZE3; k++)
     {
       scanf("%d", &arr[i][j][k]);
     }
   }

/*Print elements of array*/
printf("\nElements in three-dimensional array are: \n");

 for(i = 0; i < SIZE1; i++)
 {
  for(j = 0; j < SIZE2; j++)
  {
   for (k = 0; k < SIZE3; k++)
   { 
     printf("%d\n", arr[i][j][k]);
   }
  }
 }
return 0;
}
Output:
Program for 3-D Array in C
Applications of Arrays in C

In C Programming language, arrays are used in a wide range of applications. A few of them are as follows…

  • Arrays are used to store a list of values: In C Programming language, single-dimensional arrays are used to store a list of values of the same datatype. In other words, single-dimensional arrays are used to store a row of values. In a single-dimensional array, data is stored in linear form.
  • Arrays are used to Perform Matrix Operations: We use two-dimensional arrays to create a matrix. We can perform various operations on matrices using two-dimensional arrays.
  • Arrays are used to implement Search Algorithms: We use single-dimensional arrays to implement search algorithms like Linear Search, Binary Search
  • Arrays are used to implement Sorting Algorithms: We use single-dimensional arrays to implement sorting algorithms like Insertion Sort, Bubble Sort, Selection Sort, Quick Sort, Merge Sort, etc.,
  • Arrays are used to implement Data structures: We use single-dimensional arrays to implement data structures like Stack Using Arrays and Queue Using Arrays
]]>
3935
One Dimensional Array in C https://shishirkant.com/one-dimensional-array-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=one-dimensional-array-in-c Tue, 27 Jun 2023 03:45:32 +0000 https://shishirkant.com/?p=3930 One Dimensional Array in C:

One dimensional array is an array that has only one subscript specification that is needed to specify a particular element of an array. A one-dimensional array is a structured collection of components (often called array elements) that can be accessed individually by specifying the position of a component with a single index value.

Syntax: data-type arr_name[array_size];

Rules for Declaring One Dimensional Array
  1. An array variable must be declared before being used in a program.
  2. The declaration must have a data type(int, float, char, double, etc.), variable name, and subscript.
  3. The subscript represents the size of the array. If the size is declared as 10, programmers can store 10 elements.
  4. An array index always starts from 0. For example, if an array variable is declared as s[10], then it ranges from 0 to 9.
  5. Each array element is stored in a separate memory location.
Initialization of One-Dimensional Array in C

An array can be initialized at the following states:

  1. At compiling time (static initialization)
  2. Dynamic Initialization
Compiling time initialization:

The compile-time initialization means the array of the elements is initialized at the time the program is written or array declaration.

Syntax: data_type array_name [array_size]=(list of elements of an array);
Example: int n[5]={0, 1, 2, 3, 4};

Program:
#include<stdio.h>
int main()
{
 int n[5]={0, 1, 2, 3, 4};
 printf("%d", n[0]);
 printf("%d", n[1]);
 printf("%d", n[2]);
 printf("%d", n[3]);
 printf("%d", n[4]);
}
Output: 0 1 2 3 4
Run time initialization:

Run time initialization means the array can be initialized at runtime. That means array elements are initialized after the compilation of the program.

Program:
#include<stdio.h>
#include<conio.h>
void main ()
{
 int a[5], i;
 printf ("Enter Array Elements:\n");
 for (i = 0; i < 5; i++)
 {
  scanf ("%d", &a[i]); //Run time array initialization
 }
 printf ("Entered Array Elements are : ");
 for (i = 0; i < 5; i++)
 {
  printf ("%d ", a[i]);
 }
 getch ();
}
Output:
Run Time Initialization of Array in C
Array declaration, initialization, and accessing 

Array declaration syntax: data_type arr_name [arr_size];
Array initialization syntax: data_type arr_name [arr_size]=(value1, value2, value3,….);
Array accessing syntax: arr_name[index];

Example: Integer array example:

int age [5];
int age[5]={0, 1, 2, 3, 4};

age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/

Example: Character array example:

char str[10];
char str[10]={‘H’,‘a’,‘i’};
(or)
char str[0] = ‘H’;
char str[1] = ‘a’;
char str[2] = ‘i;

str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/

Example of One Dimensional Array in C
#include<stdio.h>
int main()
{
 int i;
 int arr[5] = {10,20,30,40,50};
 // declaring and Initializing array in C
 //To initialize all array elements to 0, use int arr[5]={0};
 /* Above array can be initialized as below also
 
 arr[0] = 10;
 arr[1] = 20;
 arr[2] = 30;
 arr[3] = 40;
 arr[4] = 50; */
 for (i=0;i<5;i++)
{
 // Accessing each variable
 printf("value of arr[%d] is %d \n", i, arr[i]);
 }
}
Output:
Example of One Dimensional Array in C
Example:

Create an integer array with size 5 and then takes the values from the keyboard and store them in the array and display the elements.

#include<stdio.h>
int main()
{
 int arr[5];
 int i;
 printf("\n Enter the array elemnts : ");
 for(i = 0; i<5; i++)
 {
  scanf("%d", &arr[i]);
 }
 printf("\n The array elemts are : ");
 for(i = 0; i<5; i++)
 {
  printf(" %d ", arr[i]);
 }
return 0;
}
Output:
1d Array Example in C
Example:

Create an integer array with size 5 and then calculate the larger element of that array using the function.

#include<stdio.h>
int max(int arr[], int size)
{
 int r, i;
 r = arr[0];
 for(i = 1; i<size; i++)
 {
  if (arr[i] > r)
  r = arr[i];
 }
return r;
}

int main()
{
  int arr[5];
  int m, i;
  printf("Enter the array elements : ");
  for(i = 0; i<5; i++)
  scanf("%d", &arr[i]);
  m = max(arr, 5);
  printf("The largest element is : %d", m);
  return 0;
}

Output:
One Dimensional Array in C with Examples

In parameter creation, it is not possible to create an entire array as an argument. In formal argument location if we constructed array syntax then it creates pointer variable only. In formal argument location when we have int arr[] syntax, then it creates pointer variable only and the syntax will indicate that it holds single dimensional array address.

Copying 1d arrays in C:

We have two arrays list1 and list2
int list1[6] = {2, 4, 6, 8, 10, 12};
int list2[6];

and we want to copy the contents of list1 to list2. For general variables (e.g. int x=3, y=5) we use simple assignment statement (x=y or y=x). But for arrays the following statement is wrong.
list2 = list1;

We must copy between arrays element by element and the two arrays must have the same size.

Example of Copying One Dimensional Array in C
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
  int source[MAX_SIZE], dest[MAX_SIZE];
  int i, size;
  
/* Input size of the array */
  printf("Enter the size of the array : ");
  scanf("%d", &size);
  
/* Input array elements */
  printf("Enter elements of source array : ");
  for(i=0; i<size; i++)
  {
    scanf("%d", &source[i]);
  }

/*
* Copy all elements from source array to dest array
*/
  for(i=0; i<size; i++)
  {
    dest[i] = source[i];
  }

/*
* Print all elements of source array
*/
  printf("\nElements of source array are : ");
  for(i=0; i<size; i++)
  {
    printf("%d\t", source[i]);
  }

/*
* Print all elements of dest array
*/
  printf("\nElements of dest array are : ");
  for(i=0; i<size; i++)
  {
    printf("%d\t", dest[i]);
  }
  return 0;
 }

Output:

Example of Copying One Dimensional Array in C
Points to Remember About Array in C:
  1. An array is a derived data type in C that is constructed from the fundamental data type of the C language.
  2. An array is a collection of similar types of values in a single variable.
  3. In implementation when we required the ‘n’ number of the variable of a similar data type then we need to go for the array.
  4. When we are working with an array always memory will be created in the contiguous memory location, so randomly we can access the data.
  5. In an array, all elements will share the same name with a unique identification value called index.
  6. Always array index will start from 0 and ends with size – 1.
  7. When we are working with an array compile-time memory management will occur i.e. static memory allocation.
  8. Always size of the array must be an unsigned integer value which should be greater than zero.
]]>
3930
Array in C https://shishirkant.com/array-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=array-in-c Wed, 13 May 2020 04:57:54 +0000 http://shishirkant.com/?p=167 What are Arrays in C?

The array is defined as a collection of similar data elements. If you have some sets of integers, and some sets of floats, you can group them under one name as an array.

Method of declaring an array

If you want an integer-type array, let’s say int A[5];

Then, you will get 5 integers, and the array name is “A” and you can access all those integers using the name “A”. So, “A” is an array and you get 5 integers spaces and the indices will be 0,1,2,3,4. So, 5 locations mean indices will start from 0 and end at 4, a total of 5 spaces. For a better understanding, please have a look at the below image.

Method of declaring an array

Now we can store 5 integers. Every location is an integer. If we assume an integer is taking 2 bytes then there are a total of 10 bytes i.e. 2 bytes each. Now each location can be accessed like A[0]=27; //Here, 27 will store in array “A” with indices 0. Now if I store A[1]=10; //10 is stored in a place with indices 1. For a better understanding, please have a look at the below image,

Arrays

So, we can have a group of elements in a single place.

How to Declare and Initialize an Array in C Language?

Now I’ll show you how to declare and initialize an array. In the main function, suppose I want to declare an array “A” of size 5. Then you need to declare the array as shown below.

int main()
 {
   int A[5];
  }

Now, an array of size 5 will be created. When a program is running, then it is running inside the main memory. The main memory is divided into 3 sections i.e. Code section, the Stack section & Heap section as shown in the below image.

How to declare and initialize an array?

As you can see in the above image, whatever code we write will be inside the code section. The point that you need to understand is, the variables that we declared, will be created inside the Stack section. So, here the Array is also going to be created inside the Stack as the array is also a variable.

Those variables that are created inside the stack section are directly accessed by the Main method from the code section. So, the array is directly accessible to the main function and can directly store the values in the array.

Now, I hope you understand how the array is declared and where the array is created inside the main memory.

How to declare and initialize an array?

You can declare and initialize an array in the same line as shown in the below example.

int main()
{
  int A[5]={1,3,5,7,9};
}

The above code shows the declaration of an array with size 5, along with this, the array is also initialized with the values 1,3,5,7,9. So, this is a declaration as well as the initialization of an array. The memory representation of the above is shown below.

How to declare and initialize an array?
How to access an array?

We can access all the elements of an array one by one using a “for” loop. To understand this better please have a look at the following code.

int main()
{
  int A[5]={2, 4,6,8,10};
  int i;
  for(i=0;i<5;i++)
  {
    printf("%d",A[i]);
  }
}

I hope you understand the basics of the array. Let us proceed and understand the array in depth.

What is an Array in C?

An array is a derived data type in C that is constructed from the fundamental data type of the 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’ & end with (size-1). When we are working with arrays, we are 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.

What is an Array in C
Why do 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 a similar type which can be referred to 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 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 from 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, 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, the compiler creates an array of size 4. The above statement is the same as the below statement.
int arr[4] = {10, 20, 30, 40}

Array declaration by specifying the size and initializing elements:

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

Index of an Array

In an array, every element has its index and we can access any element 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]
For example: if the name of an array is ‘n’, then to access the first element (which is at 0 indexes), we write n[0].

Array declaration by initializing elements in C

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 for 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.

Assigning Values to Array in C Language

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.

Assigning Values to Array in C Language with Examples

You can understand this by treating n[0], n[1], and n[2] as similar to the 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 in C Language

#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 Language

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 the 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.

Runtime Array initialization Examples in C:
#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 in C Language

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 Language:

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.

Access Array Elements in C Language

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 the 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 the array minus 1.

Array Example in C Language:
#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: Facts about Array in C

In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just a 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:
Array in C with Examples

The array elements are stored at contiguous memory locations. The following C program demonstrates that array elements are stored in 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 in C Language with Examples
Advantages of Arrays in C Language
  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.
Disadvantage of Arrays in C Language

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 whether 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 the One-Dimensional Array in C with examples. Here, in this article, I try to explain Arrays in C Language with Examples. I hope you enjoy this Arrays in C Language with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article

]]>
167