An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays provide a convenient way to work with a group of related variables. Each element in an array is identified by an index, starting from zero.
Declaring and Initializing an Array:
int numbers[5] = {1, 2, 3, 4, 5};
In this example, numbers is an array of integers with a size of 5. The elements are initialized with values 1, 2, 3, 4, and 5.
Types of Arrays in C ( One-Dimensional Array,Multidimensional Array and Character Array (String) ):
One-Dimensional Array:
An array with a single row or a single column.
Declared and accessed using a single index.
int marks[5] = {85, 90, 75, 92, 88};
Multidimensional Array:
An array with more than one dimension (rows and columns).
Commonly used for representing matrices.
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Access elements using two indices (row and column).
Character Array (String):
An array of characters used to represent strings.
Strings in C are terminated by a null character '\0'.
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Strings can also be initialized using string literals:
char greeting[] = "Hello";
Dynamic Array:
Created at runtime using dynamic memory allocation functions (malloc, calloc, realloc).
Allows flexibility in changing the size during program execution.
int* dynamicArray = (int*)malloc(5 * sizeof(int));
Must be freed using free() when no longer needed.
Common Operations on Arrays
Accessing Elements:
Elements are accessed using their indices.
Indexing starts from 0.
int value = numbers[2]; // Access the third element
Modifying Elements:
Elements can be modified using their indices.
numbers[2] = 10; // Modify the third element
Traversal:
Loop through the array elements for various operations.
for (int i = 0; i < 5; i++)
{
printf("%d ", numbers[i]);
}
Finding Length:
The length of an array is determined by its size.
int length = sizeof(numbers) / sizeof(numbers[0]);
For strings, you can use the strlen function from the <string.h> library.
One-Dimensional Array:
Multidimensional Array:
Character Array (String):
0 Comments
If you have any doubts, Please let me know