In the realm of C programming, arrays prove advantageous when there is a need to store homogeneous elements. To illustrate, consider the scenario where marks for six subjects of a student require storage. Instead of creating separate variables for each subject's marks, an array can be employed to store all subject marks in a sequential memory arrangement.
By leveraging the array, we can conveniently retrieve its elements with minimal code. Accessing the elements within an array is a straightforward process that necessitates only a small amount of code.
Properties of an Array
The array contains the following properties:
- Each element of an array is of the same data type and carries the same size, i.e., int = 4 bytes.
- Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
- Elements of the array can be randomly accessed because we can calculate the address of each element of the array with the given base address and the size of the data element.
Declaration of C Array
An array can be defined in the C programming language using the following syntax.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Here, int represents the datatype, marks is the arrayname, and 5 signifies the array_size.
Initialization of C Array
Initializing an array can be achieved by assigning values to each element based on its index. Each element in the array can be initialized by referencing its corresponding index. Let's illustrate this with an example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C Array Example
Let's consider an illustration to demonstrate an Array in the C programming language.
Example
#include<stdio.h>
int main(){ //main function
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output:
80
60
70
85
75
Explanation:
In this instance, we define an integer array named marks containing 5 elements. Each element is assigned a specific value such as 80, 60, 70, and so on. A for loop is utilized to iterate over the array starting from index 0 up to 4, displaying the values using the printf function.
C Array Declaration with Initialization Example
Let's consider an example to demonstrate how to define and set values for an array during declaration in the C programming language.
Example
#include<stdio.h>
int main(){ //main function
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output:
20
30
40
50
60
Explanation:
In this instance, we declare and set up an integer array called mark containing five elements with values 20, 30, 40, 50, and 60. Subsequently, we employ a for loop to traverse the array starting from index 0 up to 4, displaying each element using the printf function.
Accessing Array Elements
In C programming, arrays allow for direct access to individual elements, enabling retrieval of any element by specifying its position known as the index. Index values start at 0 and go up to one less than the size of the array. To access an element, we provide its index enclosed in square brackets after the array's name.
Syntax
It has the following syntax:
array_name [index];
Where the index value falls within this range - (0 ≤ index ≤ size-1).
C Example to Access Array Elements
Let's consider an example to demonstrate how to retrieve array elements in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int numbers[4] = {10, 20, 30, 40};
printf("Accessing array elements:\n");
printf("Element at index 0: %d\n", numbers[0]);
printf("Element at index 1: %d\n", numbers[1]);
printf("Element at index 2: %d\n", numbers[2]);
printf("Element at index 3: %d\n", numbers[3]);
return 0;
}
Output:
Accessing array elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Explanation:
In this illustration, we include the standard input-output library along with a declaration of the main function. The program initializes an integer array named numbers with a length of 4 containing the values 10, 20, 30, and 40. Subsequently, it displays each element using printf by referencing them based on their indices ranging from 0 to 3. Finally, the program concludes by returning 0, indicating successful execution.
Updating the Array Element
In the C programming language, we have the ability to modify the value of array elements at a specific index by utilizing the array square brackets along with the assignment operator (=) in a similar manner to accessing elements.
Syntax
It has the following syntax:
array_name[i] = new_value;
C Example to Update the Array Elements
Let's consider a scenario to demonstrate the process of modifying array elements in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int numbers[5] = {5, 10, 15, 20, 25};
printf("Original value at index 2: %d\n", numbers[2]);
numbers[2] = 99;
printf("Updated value at index 2: %d\n", numbers[2]);
return 0;
}
Output:
Original value at index 2: 15
Updated value at index 2: 99
Explanation:
In this instance, we define an integer array containing a set of 5 numbers. Subsequently, the program displays the original value located at index 2, which is 15. Following this, it updates the value at index 2 to 99 using an assignment statement (numbers[2] = 99;) and then displays the updated value.
Array Traversal
In C programming, array traversal refers to the process of iterating through each element of the array in a specific order. In C array traversal, loops are employed to retrieve each element within the array.
C Array Traversal Example
Let's consider an example to demonstrate array traversal in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int numbers[5] = {2, 4, 6, 8, 10};
printf("Traversing the array:\n");
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
return 0;
}
Output:
Traversing the array:
Element at index 0: 2
Element at index 1: 4
Element at index 2: 6
Element at index 3: 8
Element at index 4: 10
Explanation:
In this instance, we create an integer array named 'numbers' with a length of 5, holding the values 2, 4, 6, 8, and 10. A for loop is utilized to traverse the array from index 0 to 4 inclusive. Inside the loop, the printf function is used to display the index along with the corresponding element from the array. The execution concludes by returning 0.
Size of Array
The dimensions of the array represent the count of items held within the array. Determining this count can be achieved by utilizing the sizeof operator.
- When employing the sizeof operator, the output denotes the size in bytes. Specifically, sizeof(arr) reveals the complete byte size of the array.
- Every individual element within an array is categorized as type int, which typically occupies 4 bytes of memory. Consequently, the array's size can be computed by dividing the total byte size by the byte size of an individual element.
C Size of Array Example
Let's consider an example to demonstrate the concept of array size in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Size of the array: %d\n", size);
return 0;
}
Output:
Size of the array: 5
Explanation:
In this instance, we define an integer array containing numbers with a length of 5. Subsequently, the program determines the count of elements by dividing the total memory allocated for the array (sizeof(numbers)) by the memory size of an individual element (sizeof(numbers[0])). The resulting value is stored in the variable size and displayed on the screen.
Two-Dimensional Array in C
A Two-Dimensional array, or 2D array in C, is an array that has exactly two dimensions. It can be visualized as a structure of rows and columns organized in a two-dimensional grid.
Syntax
It has the following syntax:
return_type array_name[size1]
[size2] .. [sizen];
2-Dimensional Example in C
Let's consider an example to demonstrate the concept of a 2D Array in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int matrix[2][3];
int value = 1;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = value;
value++;
}
}
printf("2D Array:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output:
2D Array:
1 2 3
4 5 6
Explanation:
In this instance, we define a two-dimensional array named matrix with dimensions of 2 rows and 3 columns. An integer variable named value is initialized to 1. Through nested iterations, sequential numbers from 1 to 6 are assigned to each element within the array. The outer loop iterates over the rows while the inner loop iterates over the columns. Subsequently, a second set of nested loops is employed to display the array in a column-row sequence.
Three-Dimensional Array in C
In the C programming language, another frequently encountered type of multi-dimensional array is a Three-Dimensional Array or 3D Array. A 3D array consists of exactly three dimensions. It can be visualized as a stack of 2D arrays arranged one above the other to create the third dimension.
3-Dimensional Array Example
Let's consider a scenario to demonstrate the concept of a 3-Dimensional array in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int arr[2][2][3];
int value = 1;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
arr[i][j][k] = value;
value++;
}
}
}
printf("3D Array Elements:\n");
for (int i = 0; i < 2; i++) {
printf("Block %d:\n", i);
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
Output:
3D Array Elements:
Block 0:
1 2 3
4 5 6
Block 1:
7 8 9
10 11 12
Explanation:
In this illustration, we define a 3D array named arr2[3], meaning it consists of 2 blocks, each with 2 rows and 3 columns. An initial value of 1 is assigned to a variable, which is then utilized to set the value of every element in the array using three nested for loops. The outer loop iterates through the blocks, the middle loop through the rows, and the innermost loop through the columns.
Arrays and Pointers
In C, arrays and pointers are closely connected, allowing us to perform array operations using pointers. The array name acts as a reference to the initial array element, and the array can be converted into pointers and then passed to functions.
Array and Pointers Example in C
Let's consider an example to demonstrate the usage of arrays and pointers in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int numbers[5] = {10, 20, 30, 40, 50};
int *ptr = numbers;
printf("Accessing array elements using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i));
}
return 0;
}
Output:
Accessing array elements using pointer:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
Explanation:
In this instance, we define an integer array containing five numbers. Subsequently, a pointer named ptr is assigned the starting address of the array, indicating it points to the initial element. The for loop cycles through indices 0 to 4, each time retrieving the element at that index through pointer arithmetic: *(ptr + i) fetches the value at the i-th location in the array. The printf function displays the index along with its associated value.
Passing array to Function
In C, arrays are passed to functions through pointers since the name of the array decays to a pointer to the first element. There exist three popular ways through which an array is passed to function in C:
- Unsized array notation, where an array is passed as a pointer without mentioning its size.
- Array notation of size, in which size is included in the declaration for clarity, but it is still passed as a pointer.
- Pointer notation, in which the array is passed as a pointer explicitly, usually along with its length.
Passing Array to Function in C Example
Let's consider an example to demonstrate how to send an array as a parameter to a function in the C programming language.
Example
#include <stdio.h>
void sized_array(int arr[4]) {
printf("Inside sized_array:\n");
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void unsized_array(int arr[]) {
printf("Inside unsized_array:\n");
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
void pointer(int* arr) {
printf("Inside pointer:\n");
for (int i = 0; i < 4; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
}
int main() { //main function
int arr[] = {1, 2, 3, 4};
sized_array(arr);
unsized_array(arr);
pointer(arr);
return 0;
}
Output:
Inside sized_array:
1 2 3 4
Inside unsized_array:
1 2 3 4
Inside pointer:
1 2 3 4
Explanation:
In this illustration, we define three functions, each taking an array as an argument in three distinct manners: with a specified size, without a specified size, and as a pointer. Within each function, a loop ranging from 0 to 3 is used to iterate through and display the elements of the array. The main function includes an array named arr with 4 elements {1, 2, 3, 4}. All three functions invoke this array.
C Array Example: Sorting an array
In this program, the bubble sort algorithm is implemented to arrange the array elements in a descending order.
Example
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Output:
Printing Sorted Element List ...
101
78
44
34
23
23
12
10
9
7
Advantages of C Array
Several advantages of the array in C are as follows:
- Code Optimization: It need less code to access the data.
- Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
- Ease of sorting: We need a few lines of code only to sort the elements of the array.
- Random Access: We can access any element randomly using the array.