Chapter 8: Arrays
Arrays in C allow you to store multiple values of
the same data type in a contiguous memory block. They provide an efficient way
to work with collections of data. Let's explore how to declare, initialize, and
access elements in arrays:
8.1
Array Declaration:
To declare an array in C, you need to specify the
data type of the elements and the size of the array.
data_type
array_name[size];
Example:
#include
<stdio.h>
int
main() {
int numbers[5]; // Declaration of an integer
array
return 0;
}
The program declares an integer array `numbers` with
a size of 5 elements. Remember that arrays are zero-indexed, so the indexes
range from 0 to size-1.
8.2
Array Initialization:
Arrays can be initialized at the time of declaration
using an initializer list.
data_type
array_name[size] = {value1, value2, ...};
Example:
#include
<stdio.h>
int
main() {
int numbers[5] = {2, 4, 6, 8, 10}; //
Initialization of an integer array
return 0;
}
The program declares and initializes an integer
array `numbers` with the values 2, 4, 6, 8, and 10.
8.3
Accessing Array Elements:
You can access individual elements in an array using
the array name followed by the index in square brackets.
array_name[index]
Example:
#include
<stdio.h>
int
main() {
int numbers[5] = {2, 4, 6, 8, 10};
printf("First element: %d\n",
numbers[0]);
printf("Third element: %d\n",
numbers[2]);
return 0;
}
The program accesses and prints the first and third
elements of the `numbers` array. Compile and run the program to see the output.
8.4
Modifying Array Elements:
You can modify the value of an array element by
assigning a new value to it.
array_name[index]
= new_value;
Example:
#include
<stdio.h>
int
main() {
int numbers[5] = {2, 4, 6, 8, 10};
numbers[1] = 3; // Modifying the second
element
printf("Modified second element:
%d\n", numbers[1]);
return 0;
}
The program modifies the value of the second element
in the `numbers` array and prints the modified value. Compile and run the
program to see the output.
8.5
Looping through Arrays:
You can use loops to iterate over the elements of an
array and perform operations on them.
Example:
#include
<stdio.h>
int
main() {
int numbers[5] = {2, 4, 6, 8, 10};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
The program uses a for loop to iterate over the
elements of the `numbers` array and prints them. Compile and run the program to
see the output.
8.6
Multidimensional Arrays:
C supports multidimensional arrays, which are arrays
of arrays. They can be used to represent matrices, tables, and other structured
data.
Example:
#include
<stdio.h>
int
main() {
int matrix[3][3] = {
{1,
2, 3},
{4, 5, 6},
{7, 8, 9}
};
printf("Element at (1, 2): %d\n",
matrix[1][2]);
return 0;
}
The program declares and initializes a 2-dimensional
integer array `matrix`. It accesses and prints the element at index (1, 2).
Compile and run the program to see the output.
0 Comments