Welcome to the world of C Programming! Today, we're diving into one of the most fundamental data structures - Arrays. By the end of this lesson, you'll have a solid understanding of arrays, their usage, and how they can help you build powerful applications. 💡
In simple terms, an array is a collection of variables of the same type, stored in contiguous memory locations. Each variable in an array is called an element.
To create an array, we need to specify its type and the number of elements. Here's a simple example:
int numbers[5] = {1, 2, 3, 4, 5};In this example, we've created an array named numbers that holds 5 integers (int). The values 1, 2, 3, 4, 5 are the initial values assigned to each element.
To access an array element, we use its index. The first element in an array has an index of 0, the second has an index of 1, and so on.
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d\n", numbers[2]); // Outputs: 3These are the most basic type of arrays. As the name suggests, they have one dimension.
Multi-dimensional arrays allow you to store data in multiple rows and columns, much like a spreadsheet.
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
printf("%d\n", matrix[1][2]); // Outputs: 7In this example, we've created a 3x4 matrix.
In C, array sizes are fixed at the time of declaration. However, we can dynamically allocate memory for arrays using malloc().
int *numbers = (int *)malloc(5 * sizeof(int));
numbers[0] = 1;
numbers[1] = 2;
// ...In this example, we've created an array of 5 integers dynamically.
int numbers[5] = {1, 2, 3, 4, 5};
int max = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
printf("%d\n", max); // Outputs: 5int numbers[5] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("%f\n", (float)sum / 5); // Outputs: 3What is an array in C Programming?
What is the first element's index in a one-dimensional array?