0
0
Cprogramming~5 mins

Array initialization in C

Choose your learning style9 modes available
Introduction
Arrays hold many values of the same type together. Initializing an array means giving it starting values so it is ready to use.
When you want to store a list of numbers or characters to use later.
When you know the values in advance and want to set them at the start.
When you want to create an empty array with default values before filling it.
When you want to avoid garbage or random values in your array.
When you want to quickly set all elements to zero or another value.
Syntax
C
/* Define and initialize an array with values */
int numbers[5] = {1, 2, 3, 4, 5};

/* Define an array and initialize all elements to zero */
int zeros[5] = {0};

/* Define an array without initialization (values are garbage) */
int uninitialized[5];
You must specify the array size or provide enough values to infer it.
If you provide fewer values than the size, remaining elements are set to zero.
Examples
Array of size 3 initialized with three values.
C
int scores[3] = {10, 20, 30};
Array of size 4 initialized with all zeros.
C
int empty[4] = {0};
Array of size 5, first two elements set, rest are zero.
C
int partial[5] = {1, 2};
Array declared without initialization, contains garbage values.
C
int no_init[3];
Sample Program
This program shows four arrays: fully initialized, zero initialized, partially initialized, and uninitialized. It prints their contents to see the difference.
C
#include <stdio.h>

int main() {
    int numbers[5] = {5, 10, 15, 20, 25};
    int zeros[5] = {0};
    int partial[5] = {1, 2};
    int uninitialized[5];

    printf("numbers array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    printf("zeros array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", zeros[i]);
    }
    printf("\n");

    printf("partial array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", partial[i]);
    }
    printf("\n");

    printf("uninitialized array (values may vary): ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", uninitialized[i]);
    }
    printf("\n");

    return 0;
}
OutputSuccess
Important Notes
Time complexity to initialize is O(n) where n is array size.
Space complexity is O(n) for the array storage.
Uninitialized arrays contain garbage values and can cause bugs if used before setting.
Use zero initialization to avoid unpredictable values.
Partial initialization sets remaining elements to zero automatically.
Summary
Arrays store multiple values of the same type in a fixed size.
Initialization sets starting values to avoid garbage data.
You can fully, partially, or zero initialize arrays in C.