Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, double, or user-defined data types, like structures. However, to be stored together in a single array, all the elements should be of the same data type. The elements are stored from left to right, with the left-most index being the 0th index and the rightmost index being the (n-1) index.
Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer – MERN Stack Master’s program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!
Arrays in C are of two types: Single-dimensional arrays and multidimensional arrays.
- Single-Dimensional Arrays: A single-dimensional array (1-D array) is the simplest form of array in C. It consists of elements of similar types, which can be accessed through their indices.
- Multi-dimensional Arrays: The most common type of multi-dimensional array used in the C language is a 2-D array. However, the number of dimensions can be more than 2 depending upon the compiler of the user’s system. These arrays consist of elements that are array themselves.
Why Do We Need Arrays?
If we have a small number of elements, we want 3 variables; we can declare them separately as var1, var2, and var3. But if we have a large number of variables, we can store them in arrays.
Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits. Now, in C language, you can achieve this by 2 methods. The first one is to make 100 variables, store the numbers from 1-100 in those variables separately, and then print each digit. The second method is to create an array of size 100 and store the numbers in that array using a loop. These digits can be printed using a single loop in linear complexity. The second method is more optimized and desirable than the first one as storing these values in a single array is more convenient than creating 100 variables.
Become job-ready for Programmer/ Developer roles today with C Basics Online Tutorial Course for Beginners!
Declaration and Initialization of Array in C
There are various ways in which an array can be declared and initialized. You can declare an array of any data type (i.e. int, float, double, char) in C. The following ways can be used to declare and initialize an array in C.
Array Declaration by Specifying the Size
Arrays can be declared by specifying the size or the number of array elements. The array size specifies the maximum number of elements the array can hold. In the latest version of C, you can declare an array by specifying the size at the time of the declaration, or you can provide a user-specified size. The following syntax can be used to declare an array simply by specifying its size.
// declare an array by specifying size in [].
int my_array1[20];
char my_array2[5];
// declare an array by specifying user defined size.
int size = 20;
int my_array3[size];
Image Reference
When an array is declared without allocating a value, it stores a garbage value. If you access an uninitialized array value, it will give you a garbage value, just like any uninitialized variable.
Array Declaration by Initializing Elements
An array can be initialized at the time of its declaration. In this method of array declaration, the compiler will allocate an array of size equal to the number of the array elements. The following syntax can be used to declare and initialize an array at the same time.
// initialize an array at the time of declaration.
int my_array[] = {100, 200, 300, 400, 500}
In the above syntax, an array of 5 elements is created. Even though the array size has not been specified here, the compiler will allocate an array of 5 integer elements.
Array Declaration by Specifying the Size and Initializing Elements
An array can also be created by specifying the size and assigning array elements at the time of declaration. This method of array creation is different from the previous one. Here, if the number of initialized elements is less than the size of the array specified, then the rest of the elements will automatically be initialized to 0 by the compiler. See the following syntax to understand this.
// declare an array by specifying size and
// initializing at the time of declaration
int my_array1[5] = {100, 200, 300, 400, 500};
// my_array1 = {100, 200, 300, 400, 500}
// int my_array2[5] = {100, 200, 300};
// my_array2 = {100, 200, 300, 0, 0}
In the above array syntax, my_array1 is an array of size 5 with all five elements initialized. Whereas, my_array2 is an array of size 5 with only three of its elements initialized. The remaining two elements of the second array will be initialized to 0 by the compiler.
Array Initialization Using a Loop
An array can also be initialized using a loop. The loop iterates from 0 to (size – 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.
// declare an array.
int my_array[5];
// initialize array using a "for" loop.
int i;
for(i = 0; i < 5; i++)
{
my_array[i] = 2 * i;
}
// my_array = {0, 2, 4, 6, 8}
In the above syntax, an array of size 5 is declared first. The array is then initialized using a for loop that iterates over the array starting from index 0 to (size – 1).
Beginner’s guide to start your career with C programming skills
Job roles |
Salary (Average) |
Certification Courses |
Top companies hiring |
C Developer |
$98,000 (USA) | Rs.10LPA (IND) |
BOSCH Group, Capgemini, Amazon, Microsoft, Accenture, IBM, Meta, Adobe, Apple, Mozilla |
|
Backend Developer |
$105,000 (USA) | Rs.12LPA (IND) |
C Basics Online Tutorial for Beginners + Introduction to C++ |
VISA, JP Morgan, Accenture, Wipro, Freshworks |
Fullstack Developer |
$180,000 (USA) | Rs.18LPA (IND) |
C Basics Online Tutorial for Beginners + Full Stack Java Development Course for Beginners |
Meta, Netflix, Airbnb, Uber, Infosys,Wipro, Zomato, Swiggy, Ola, Paytm, Amazon, Microsoft |
Access Array Elements
Since an array is stored contiguously in the memory, it has indices starting from ”0” to “array_size – 1”, also known as zero-based indexing. This indexing represents the position in the array.
The array indices are used to access any element of the array in the following way:
array_name[index]
The index of the element to be accessed is specified within square brackets “[]”. The range of the index is- integers in the range [0, size).
Examples:
int my_array[6];
// access 1st element
my_array[0] = 100;
// access 4th element
my_array[2] = 300;
// access last element
my_array[5] = 600;
Input and Output Array Elements
Array values can be stored by taking input from the user and storing them in the array. The following example illustrates this:
// input an integer element and store it
// in 1st position of the array
scanf("%d", &my_array[0]);
// input a float element and store it
// in ith position of the array
scanf("%f", &my_array[i-1]);
Similarly, array elements can also be displayed in the output using the printf() method. The index is specified, indicating the element’s position to be printed. The following example illustrates this:
// print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);
Advantages of Array in C
Arrays have a great significance in the C language. They provide several advantages to the programmers while programming. Some of them are:
- Arrays make the code more optimized and clean since we can store multiple elements in a single array at once, so we do not have to write or initialize them multiple times.
- Every element can be traversed in an array using a single loop.
- Arrays make sorting much easier. Elements can be sorted by writing a few lines of code.
- Any array element can be accessed in any order either from the front or rear in O(1) time.
- Insertion or deletion of the elements can be done in linear complexity in an array.
Also Read: Difference Between Coding and Programming
Disadvantages of Array in C
Every advantage comes with some disadvantages as well. This stands true for arrays as well. Below are some of the disadvantages of the array in C:
- Accessing an array out of bounds: The first disadvantage of arrays is that they are statically allocated. This means that their size can not be increased or decreased once their size is initialized. To understand this point, consider the example given below:
#include
int main()
{
//declaring the array of size 20
int my_array[20];
//initialising the array elements
for (int i = 0; i < 20; i++)
{
//i will be the value of e
//very ith element of the array
my_array[i] = i;
}
// Print value at index 5 of the array
printf("Element at index 5"
" is %d\n",
my_array[5]);
// Print value at index 13 of the array
printf("Element at index 13"
" is %d\n",
my_array[13]);
// Print value at index 21 of the array
printf("Element at index 21"
" is %d",
my_array[21]);
return 0;
}
In the above example, the array arr’s initial value is 20, so printing the values of elements up to index 20 gives the desired output. But when we try to print the element at the 21st index, it gives a garbage value. This is because the array was accessed out of the bound index.
This issue can be resolved using malloc() and calloc() functions. These functions allocate the memory dynamically. We have a free() function that allows us to free the unwanted memory at our will. The below example illustrates the same:
#include
#include
int main()
{
//*ptr will be storing the base
//address of the array elements
int *ptr;
int size, i;
// size of the array will be 5
size = 5;
printf("Size of the array is: %d\n", size);
// allocating the array memory
//dynamically using malloc()
ptr = (int *)malloc(size * sizeof(int));
// Checking whether the memory has
//been successfully allocated by malloc
if (ptr == NULL)
{
printf("Memory has not been allocated allocated\n");
exit(0);
}
else
{
// Memory has been successfully allocated
printf("Memory has been allocated successfully\n");
// initializing the array elements
for (i = 0; i < size; ++i)
{
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < size; ++i)
{
printf("%d ", ptr[i]);
}
}
return 0;
}
- Homogeneity: We can store only a single type of element in the array, i.e., homogeneous arrays. We can not use it as a template. For example, if the array data type is char, only characters can be stored in the array. Trying to store integers or any other element of a different data type will throw an error. To understand this point, consider the example given below:
#include
int main()
{
// such declaration will throw
// Compilation Error
int my_array[6] = {1, 2, "mango", 4, 5, 6.2};
int i;
printf("Elements of the array are: ");
for (i = 0; i < 6; i++)
{
printf("%d ", my_array[i]);
}
return 0;
}
In the above example, the array’s data type is int. However, when we try to declare string and float values to the array, it throws a compilation error.
This issue can be resolved by creating a structure to store heterogeneous (non-homogeneous) values. Consider the below example to understand this concept:
#include
// create a structure
struct example
{
int fruit_quant;
float fruit_rate;
char fruit_name[30];
};
int main()
{
// s1 - object of the structure
struct example s1 = {10, 90.45, "Mango"};
// accessing structure members
// using structure object
printf("%d\n", s1.fruit_quant);
printf("%f\n", s1.fruit_rate);
int i;
for (i = 0; s1.fruit_name[i] != '\0'; i++)
{
printf("%c", s1.fruit_name[i]);
}
return 0;
}
Examples of the 1-D Array in C
Boost your career with our Full Stack Developer – MERN Stack Master’s program! Gain in-depth expertise in development and testing with the latest technologies. Enroll today and become a skilled MERN Stack Developer!
The following programs illustrate declaration, initialization, input/output operations, and basic operations like insertion, deletion, sorting, and searching in the 1-D array in C.
Example 1: Array Declaration, Input, and Output
#include
int main()
{
// declare an array.
int my_array[6];
printf("Enter array elements:\n");
// input array elements.
int i;
for (i = 0; i < 6; i++)
{
scanf("%d", &my_array[i]);
}
printf("\nArray elements are:\n");
// print array elements.
for (i = 0; i <= 5; i++)
{
printf("%d ", my_array[i]);
}
return 0;
}
In the above example, an integer array of size 6 is declared. This array can hold at most 6 integer elements. A “for loop” is used to input the array elements from the user. Similarly, a “for loop” prints these elements in the output. Both times, the loop runs from 0 to 5 to iterate over all the array elements.
Example 2: Insertion and Deletion in an Array.
#include
int main()
{
int i;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
// input index where the element is to be inserted.
int pos;
printf("Enter the position: ");
scanf("%d", &pos);
// input the element to be inserted.
int element;
printf("Enter the element: ");
scanf("%d", &element);
if (pos > 10)
{
printf("Input is invalid !");
}
else
{
// right shifting array elements.
for (i = 9; i >= pos - 1; i--)
my_array[i + 1] = my_array[i];
// insert the element at "pos".
my_array[pos - 1] = element;
printf("Array after insertion is:\n");
// print array elements.
for (i = 0; i <= 10; i++)
printf("% d ", my_array[i]);
}
return 0;
}
In the above example, an element that needs to be inserted is taken as input. The position where this element is to be stored is also taken as input. The array elements are shifted to the right to make space for the new element. After insertion, the size of the array is incremented.
Example 3: Sorting Elements of an Array
#include
int main()
{
int i, j, temp;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
// print unsorted array.
printf("Original array is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
// sort the array elements in descending order.
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (my_array[j] > my_array[i])
{
temp = my_array[i];
my_array[i] = my_array[j];
my_array[j] = temp;
}
}
}
// print the sorted elements.
printf("\n\nSorted array in descending order is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
return 0;
}
In the above example, an array of size 10 is initialized. The array elements are sorted in descending order using the bubble sort algorithm.
One Dimensional Array in C
A one-dimensional array in C is a collection of elements of the same data type, stored sequentially in memory. Each element in the array is identified by an index, starting from zero. Arrays are used to store multiple values in a single variable rather than declaring separate variables for each value.
Syntax
data_type array_name[size];
Accessing Elements
Elements are accessed using their index:
numbers[0] = 10; // First element
Example
#include
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
In this example, a one-dimensional array number is initialized with five values, and a loop is used to print each element.
2 Dimensional Array in C
A 2-dimensional array or 2-D array is the simplest form of multi-dimensional array in C. Each element in a 2-D array can be represented as a separate 1-D array. A 2-D array contains a certain number of rows and columns and the total number of array elements can be found by multiplying the number of rows and columns. For example, if the array is my_array[2][3], then the total number of elements in the array is 6.
A matrix is said to be a square matrix when the number of rows is equal to the number of columns. When the number of rows differs from the number of columns, the matrix is said to be a rectangle matrix. Processing a 2-D array requires a nested loop. The outer loop signifies the number of rows and the inner loop signifies the column of elements of each row. However, the significance of the outer and inner loops can be interchanged depending on whether the user wants a row order matrix or a column order matrix.
Declaration of 2-D Array in C
Syntax to Declare a 2-Dimensional Array in C:
// declaring a 2-d array
dataType arrayName[no_of_rows][no_of_columns];
Description of the syntax:
- dataType: This data type specifies the type of elements to be stored in the array. It can be int, float, double, or char.
- arrayName: This is the name of the array. To specify the name of an array, you must follow the same rules applicable while declaring a usual variable in C.
- no_of_rows: This is the first dimension of the array. It is an integer specifying the number of rows the array will hold.
- no_of_columns: This is the second dimension of the array. It’s an integer value representing the number of columns of the array.
Examples
// 5 x 10 matrix.
int my_array1[5][10];
// 3 x 3 square matrix.
float my_array2[3][3];
// 2 x 1 matrix.
char my_array3[2][1];
Note: The total number of elements that the array can hold is (no_of_rows * no_of_columns). For example, an array arr[2][4] can have at most 8 elements.
Initialization of 2-D Array in C
In 1-D arrays, you can skip specifying its size when an array is initialized at the time of its declaration. However, this scenario is different with 2-D arrays. Only the first dimension can be skipped, and the second is mandatory at initialization.
The following ways can be used to initialize a 2-D array in C:
- The conventional way: This is the most common way to initialize an array in C. 1-D arrays equal to the number of the first dimension (or rows) are created having elements equal to the number of the second dimension (or columns).
Example
int my_array[3][2] = {
{11, 12},
{21, 22},
{31, 32}
};
In the above example, there are 3 1-D arrays (3 = number of rows) with 2 elements each (2 = number of columns).
- The compact way: In this method, all array elements are written in the same line separated by commas. It looks like a 1-D array initialization. This way is not recommended as the initialized array has less readability.
Example
int my_array[3][2] = {11, 12, 21, 22, 31, 32};
All array elements are written inside a single pair of braces “{}” in the above example. This type of initialization is less readable.
- Using a loop: Like the 1-D arrays, 2-D arrays can also be initialized using a loop. The most commonly used loop is the “for loop”. Two nested loops are required to initialize the array.
Example
int my_array[2][3];
int i, j;
// The first loop runs till the number of rows.
for(i = 0; i < 2; i++)
{
// second loop runs till number of columns.
for (j = 0; j < 3; j++)
{
my_array[i][j] = i + j;
}
}
/* my_array = {
{0, 1, 2},
{1, 2, 3}
} */
In the above example, two “for loops” initialize a 2-D array. The first loop runs from 0 to the number of rows. The second loop runs from 0 to the number of columns.
Ready to master the MERN Stack? Join our Full Stack Developer – MERN Stack Master’s program and accelerate your career with comprehensive development and testing skills. Contact us today to get started!
Points to Remember While 2-D Array Initialization
The second dimension is mandatory while declaring a 2-D array, whereas the first can be optional. The following examples illustrate the possible mistakes that can be made while initializing a 2-D array in C:
// valid
int my_array[3][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
// valid
int my_array[][3] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
// invalid: second dimension must be specified.
int my_array[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
// invalid: second dimension must be specified.
int my_array[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90}
Examples of 2-D Array in C
The following examples illustrate the basic implementation of a 2-D array, including input and output operations in a 2-D matrix and finding the matrix’s transpose.
Example 1: 2-D Array Declaration, Input, and Output.
#include
int main()
{
// declaring and initializing the 2-D array.
// 2-D array with 5 rows and 2 columns.
int x[5][2] = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}};
int i, j;
// print the value of each array element.
// outer loop- for rows.
for (i = 0; i < 5; i++)
{
// inner loop- for columns.
for (j = 0; j < 2; j++)
{
printf("Element at x[ %d", i);
printf("][ %d", j);
printf("] :");
printf("%d", x[i][j]);
printf("\n");
}
}
return 0;
}
In the following example, a 2-D array of 5 rows and 2 columns has been declared and initialized. For printing, we are using two “for loops.” The outer “for loop” prints the rows, while the inner “for loop” prints columns for every row.
Example 2: Finding Sum and Product of Two 2 Matrices
#include
int main()
{
// declaring arr1 and arr2.
int arr1[2][2], arr2[2][2];
int sum[2][2], product[2][2];
// reading input for arr1 from the user.
printf("Enter the elements of arr1 : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr1[%d][%d] :", i, j);
scanf("%d", &arr1[i][j]);
}
printf("\n");
}
// reading input for arr2 from the user.
printf("Enter the elements of arr2: \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr2[%d][%d] :", i, j);
scanf("%d", &arr2[i][j]);
}
printf("\n");
}
// adding the corresponding array elements.
printf("Sum array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
sum[i][j] = arr1[i][j] + arr2[i][j];
//print the sum array
printf("%d\t", sum[i][j]);
}
printf("\n");
}
// multiplying the corresponding array elements.
printf("Product array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
product[i][j] = arr1[i][j] * arr2[i][j];
// print the product array.
printf("%d\t", product[i][j]);
}
printf("\n");
}
return 0;
}
For finding the addition of two matrices, the number of rows and columns should be the same in both matrices. For finding the product of two matrices, the number of columns in the first matrix should be the same as the number of rows in the second matrix.
A resultant matrix of the same order is declared to get the sum of the two matrices. To get the product of the two matrices, a resultant matrix having rows equal to the first matrix and columns equal to the second matrix is declared.
Example 3: Transpose of a Matrix
Square Matrix
#include
int main()
{
// declaring the matrices.
int arr[10][10], transpose[10][10];
// reading the input from the user.
printf("Enter elements of the arr\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &arr[i][j]);
// copy the array element into another element.
for (int i = 0; i < 2; i++
for (int j = 0; j < 2; j++)
transpose[j][i] = arr[i][j];
printf("Transpose of the arr:\n");
//print the transpose of the arr
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
return 0;
}
In the above example, the transpose of a square matrix is printed. For printing the transpose of the matrix, first, the matrix elements are copied in another matrix and then the rows and the columns of the copied matrix are reversed.
Rectangular Matrix
#include
int main()
{
// declaring the matrices.
int arr[10][10], transpose[10][10];
// reading the input from the user.
printf("Enter elements of the arr\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
scanf("%d", &arr[i][j]);
}
// copy the array element into another element.
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
transpose[j][i] = arr[i][j];
}
printf("Transpose of the arr:\n");
// print the transpose of the array.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
return 0;
}
In the above example, the matrix is a rectangle, which means that the number of rows is not equal to the number of columns. The logic is the same as that in the previous example.
Example 4: Check if the Given Matrix is Sparse or Not
#include
#include
int main()
{
int row, col, a[10][10], count = 0;
// read the number of rows and columns from the user.
printf("Enter the number of rows: \n");
scanf("%d", &row);
printf("Enter the number of columns: \n");
scanf("%d", &col);
// read the elements of the matrix from the user.
printf("Enter the matrix elements: \n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
scanf("%d", &a[i][j]);
}
}
// print the matrix.
printf("Matrix is:\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
// check if the matrix is sparse or not.
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (a[i][j] == 0)
count++;
}
}
if (count > ((row * col) / 2))
printf("Matrix is a sparse matrix \n");
else
printf("Matrix is not sparse matrix\n");
}
In the above example, it is checked whether the matrix is sparse or not. A sparse matrix is one in which 0’s is greater than the non-zero elements. A counter is maintained to count the number of 0’s. Finally, the count of 0’s is compared with half the total number of elements in the matrix.
Arrays vs. Pointers
Arrays can behave like pointers in many circumstances, such as when an array is passed to a function, which treats it as a pointer. Also, pointer arithmetic applies to arrays. However, these two differ from each other in many ways. The following comparison chart summarizes the key differences between a pointer and an array in C.
COMPARISON BASIS |
ARRAY |
POINTER |
DEFINITION |
An array stores one or more values of a similar type. |
A pointer stores the address or memory location of a variable. |
SYNTAX |
type array_name[size]; |
Type *ptr_name; |
MEMORY ALLOCATION |
Contiguous or sequential memory is allocated to the elements of an array. |
A pointer can be allocated to any random available memory. |
MEMORY SPACE |
Arrays are static, so their size cannot be altered. |
A pointer is dynamic, so the memory size can be either altered or even freed. |
NO. OF VALUES STORED |
A single array can store a large number of elements. |
A pointer can point to only one variable’s address. |
TYPE |
The data type of the array is determined by the type of elements stored in it. |
The data type of a pointer is determined by the type of the variable whose memory location it is pointing to. |
Sizeof() Operator |
When an array is passed to the sizeof() operator, the combined size of all the stored elements is returned. |
When a pointer is passed to the sizeof() operator, the size of the pointer is printed (generally 8). This size is the same for any type of pointer. |
COMPILE-TIME/ RUN-TIME |
Memory is allocated to an array during the compilation.
|
Memory is allocated to a pointer during the run time of the program. |
Passing an Array to a Function
When an array in C is passed to a function, only the address of the array’s first element is passed to the function. And being contiguous, the whole array can be accessed by the function using the address of the first element.
Passing an Array Element to a Function
We can pass a single array element to a function as its argument. The following examples illustrate this. Here, we have made a function that prints the element passed to it.
#include
//function having an int type parameter
void func(int a)
{
printf("Array element passed to the function is: %d", a);
}
int main()
{
//initialized 1-D array
int arr[] = { 1, 2, 3, 4, 5 };
//function call
func(arr[2]); //passing arr[2] i.e., 3 to the func.
return 0;
}
Passing a 1-D Array to a Function
In the above section, an array element was passed to a function. In this section, we are going to look at how a 1-D array can be passed to a function through a simple example given below. Here, a function has been made to which we are passing an array and its size, and the function returns the maximum element of that array.
#include
// function find the greatest array elemen
int maximum(int arr[], int size)
{
int i;
int large = arr[0];
for(i = 0; ilarge)
{
large = arr [i];
}
}
return large;
}
int main()
{
int result;
// 1-D array initialization
int arr[] = {100, 2, 1, 120, 55, 41};
int size = sizeof(arr) / sizeof(int);
// function call
result = maximum(arr, size); // 1-D array is passed to the function.
printf("The greatest array element is: %d", result);
return 0;
}
Passing a Multidimensional Array to a Function
We can also pass a matrix or a 2-D array to a matrix. The example below illustrates where a matrix is passed to a function, and the function prints that matrix.
#include
// function to print the matrix elements
void printMatrix(int arr[3][3])
{
int i, j;
printf("The Matrix thus formed is: \n");
for (i = 0; i < 3; ++i)
{
// change the line
printf("\n");
for (j = 0; j < 3; ++j)
{
printf("%d\t", arr[i][j]);
}
}
}
int main()
{
int arr[3][3], i, j;
// reading input from user
printf("Enter the elements: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing 2-D array or a
// Matrix as an argument
printMatrix(arr);
return 0;
}
Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer – MERN Stack Master’s program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!
Pointers to Array
As we discussed in the earlier section, arrays and pointers are related in C. In this section, we will discuss how a pointer can be declared to store an array’s address.
The following advantages are achieved by declaring a pointer to an array:
- The array elements can now be accessed in multiple ways.
- The time and space complexity of the program can be reduced.
- Arrays can be manipulated more efficiently.
#include
int main()
{
int i;
int my_array[8] = {10, 20, 30, 40, 50, 60, 70, 80};
// declare a pointer pointing to the above array.
int *my_ptr = my_array;
my_ptr = my_array;
// access an array element using the pointer.
*(my_ptr + 1) = 100;
// print array elements using the pointer.
printf( "Array elements are: \n");
for ( i = 0; i < 8; i++ ) {
printf("*(my_ptr + %d) = %d\n", i, *(my_ptr + i) );
}
return 0;
}
In the above program, a pointer *my_ptr is pointing to the array my_array. This simply means that the address of the array’s first element (i.e. my_array[0]) is stored in the pointer. The pointer now has access to all elements of the array.
That was all about Array in C.
Final Thoughts!
To sum up, this article taught you the concept of arrays in C. You started with a brief introduction to the array data structure and gradually moved on to discuss their needs, advantages, and disadvantages. Next, you saw the different ways to declare and initialize arrays in C.
Next, you learned to access an array and input or output elements to/from an array. Moving ahead, you saw some examples of 1D and 2D arrays. Finally, you learned how to pass an array to a function, a concept called pointers to an array, and the differences between an array and a pointer.
Why stop here? To learn full-stack web development, you should check out Simplilearn’s Full Stack Developer – MERN Stack‘ course. This comprehensive program will equip you with in-depth knowledge and hands-on experience in building dynamic web applications using MongoDB, Express.js, React, and Node.js. You’ll learn how to create robust server-side applications, develop responsive front-end interfaces, and manage data efficiently with MongoDB. The course also covers essential tools and practices such as version control with Git, deploying applications with Docker, and implementing RESTful APIs. It is an ideal choice for aspiring full-stack developers looking to master the MERN stack and advance their careers in web development. If you have a knack for learning new courses, you should check out Simplilearn’s complete list of free courses.
FAQs
1. What is array in C?
An array in C is a collection of elements of the same data type, stored sequentially in memory. It allows multiple values to be stored in a single variable, accessed using an index.
2. What are the 3 common types of arrays?
The three common types of arrays are:
-
- One-dimensional array
- Two-dimensional array (matrix)
- Multi-dimensional array
3. What is an array in C programming?
In C programming, an array is a data structure used to store a fixed-size sequence of elements of the same data type, accessed using indices starting from 0.
4. What are array properties?
Array properties include fixed size, contiguous memory allocation, homogeneous data type, and zero-based indexing for element access.
5. How to initialize an array in C?
Arrays can be initialized in C by specifying values within curly braces, like:
6. What are array methods?
In C, arrays don’t have built-in methods like higher-level languages. However, sorting, searching, and traversing are common array manipulations done through functions.
7. What is an array function?
An array function either takes an array as an argument or returns an array, enabling various operations like traversing, modifying, or processing array elements.
Source link