Declaring and Initializing an Array in C programming
Declaring and Initializing an Array in C
An array in C is a collection of elements of the same type stored in contiguous memory locations. To use arrays in C, you need to declare and initialize them properly. Here's how you can do it:
Declaring an Array
To declare an array, specify the type of its elements, followed by the array name and size in square brackets.
data_type array_name[size];
Explanation:
data_type
: The type of data the array will hold (e.g.,int
,float
).array_name
: The name you choose for the array.size
: The number of elements the array can hold. This must be a constant integer value.
Initializing an Array
You can initialize an array at the time of declaration by providing a list of values in curly braces.
data_type array_name[size] = {value1, value2, value3, ...};
Explanation:
value1, value2, ...
: The initial values for the array elements. The number of values should not exceed the specified size of the array.
Examples
1. Declaring and Initializing an Integer Array:
#include <stdio.h>
int main() {
// Declare and initialize an integer array
int numbers[5] = {1, 2, 3, 4, 5};
// Print array elements
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\\n", i, numbers[i]);
}
return 0;
}
2. Declaring an Array Without Initializing:
#include <stdio.h>
int main() {
// Declare an array without initialization
int numbers[5];
// Assign values to the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Print array elements
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\\n", i, numbers[i]);
}
return 0;
}
In these examples:
- The first example demonstrates how to declare and initialize an array with specific values.
- The second example shows how to declare an array and then assign values to its elements.
Note:
Arrays in C are zero-indexed, meaning the first element is at index 0. Ensure that the array size is sufficient to hold all the elements you intend to store.
Arrays in C are zero-indexed, meaning the first element is at index 0. Ensure that the array size is sufficient to hold all the elements you intend to store.
Comments
Post a Comment