Array Initialization in C
Syntax of Array Initialization
Arrays in C can be initialized at the time of declaration or later using assignment
statements.
1. Initializing Arrays at Declaration
datatype array_name[size] = {value1, value2, ..., valueN};
datatype → Data type of array elements (e.g., int, float, char).
array_name → Name of the array.
size → Number of elements (optional if values are provided).
{value1, value2, ...} → List of values assigned to the array.
Examples of Array Initialization
1. Integer Array Initialization
#include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; // Array
initialization // Accessing and printing elements printf("First element: %d\n",
numbers[0]); printf("Second element: %d\n", numbers[1]); return 0; }
Output:
First element: 10 Second element: 20
2. Character Array (String) Initialization
#include <stdio.h> int main() { char name[] = "Hello"; // String initialization
printf("String: %s\n", name); return 0; }
Output:
String: Hello
(Note: The compiler automatically adds the null character \0 at the end.)
3. Floating-Point Array Initialization
#include <stdio.h> int main() { float prices[3] = {12.5, 15.75, 20.99};
printf("First price: %.2f\n", prices[0]); return 0; }
Output:
First price: 12.50
Other Ways to Initialize Arrays
1. Partial Initialization
int arr[5] = {1, 2}; // Remaining elements are initialized to 0
Equivalent to:
int arr[5] = {1, 2, 0, 0, 0};
2. Omission of Size
int arr[] = {5, 10, 15, 20}; // Size is determined automatically
3. Using a Loop for Initialization
#include <stdio.h> int main() { int arr[5]; // Initialize array using loop for (int
i = 0; i < 5; i++) { arr[i] = i * 2; } // Print array elements for (int i = 0; i <
5; i++) { printf("%d ", arr[i]); } return 0; }
Output:
0 2 4 6 8
Conclusion
Arrays in C can be initialized in multiple ways, including direct assignment,
automatic size detection, and loops. Choosing the right method depends on the use
case, whether it's known values at compile time or dynamic values at runtime.