Arrays in C
Arrays in C
An array in C is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow efficient data storage and retrieval.
Declaring and Initializing Arrays
Declaration
Arrays are declared by specifying the data type and size:
int numbers[5]; // Declares an array of size 5
Initialization
Arrays can be initialized at the time of declaration:
int numbers[5] = {10, 20, 30, 40, 50}; // Initialization
If fewer values are provided, remaining elements are initialized to zero:
int arr[5] = {1, 2}; // {1, 2, 0, 0, 0}
Accessing Elements in an Array
Elements in an array are accessed using their index, starting from 0.
printf("%d", numbers[2]); // Access third element (index 2)
Array Input and Output
Elements of an array can be read using loops.
Example: Taking Input and Printing an Array
#include <stdio.h>
int main() {
int arr[5], i;
// Input array elements
printf("Enter 5 numbers: ");
for(i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
// Output array elements
printf("Array elements: ");
for(i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Types of Arrays
1. One-Dimensional Arrays
A linear list of elements:
int numbers[5] = {1, 2, 3, 4, 5};
2. Two-Dimensional Arrays (2D Arrays)
Used for matrices or tables.
Declaration:
int matrix[3][3]; // Declares a 3x3 matrix
Initialization:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing 2D Array Elements:
printf("%d", matrix[1][2]); // Access element at row 1, column 2
3. Multi-Dimensional Arrays
Arrays with more than two dimensions, used in complex data structures.
Example: 2D Array Input and Output
#include <stdio.h>
int main() {
int matrix[2][2], i, j;
printf("Enter elements of 2x2 matrix:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("Matrix:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Arrays and Pointers
An array name acts as a pointer to its first element.
int arr[] = {10, 20, 30};
printf("%d", *(arr + 1)); // Access second element using pointer
Array and Functions
Arrays can be passed to functions as arguments.
Passing Array to Function
Example of passing an array to a function:
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
printArray(numbers, 5);
return 0;
}
Arrays are an essential part of C programming, allowing efficient storage and manipulation of data.
If you have any questions, feel free to ask. Thank you for reading!