How to Initialize an Array in C Programming
Introduction to 1D Array Initialization in C
In this tutorial, you will learn how to initialize a one dimensional (1D) array
in C programming. Array initialization is a fundamental concept that every C
programmer must understand.
What is an Array?
An array is a collection of elements of the same data type stored in
contiguous memory locations. Arrays allow efficient storage and access
of multiple values using a single variable name.
What is Array Initialization?
Array initialization in C is the process of assigning initial values
to array elements. If an array is declared without initialization,
its elements contain garbage values.
To avoid unpredictable results, programmers should always initialize
arrays with meaningful values before using them in a program.
How to Initialize an Array in C
In C programming, arrays are initialized using curly braces { }
containing comma-separated values. A one dimensional array is declared
using the following syntax:
type array_name[array_size];
The array_size must be a constant value greater than zero.
Programmers can use any valid variable name for array_name
as long as it follows the naming rules of the C language.
The type specifies the data type of the array elements.
It can be int, char, float, or any
other valid C data type.
Ways to Initialize an Array in C
In C programming, arrays can be initialized in the following two ways:
-
Compile-Time Initialization:
In this method, array values are provided directly in the program
at the time of array declaration. This type of initialization is
similar to normal variable initialization.
-
Runtime Initialization:
In this method, array values are assigned during program execution.
The user can decide the size and values of the array while the program
is running. Runtime initialization is commonly done using loops or
the scanf() function.
Methods to Initialize Arrays in C Programming
There are several standard methods to initialize arrays in C programming, depending on whether you know the size or data at compile time.
- Array initialization with Declaration.
- Array initialization with Declaration without Size.
- Array initialization after Declaration (Using Loops).
- Array initialization by specifying size.
- Getting input from the user.
- Initialization from brace-enclosed lists.
- Using Designated Initializers (for GCC/Clang compilers).
Array Initialization Methods in C Programming
The diagram below illustrates the different array initialization methods used in C programming.
Let's explore each method in detail.
1. Array Initialization with Declaration
This is the method of filling an array with values at the time of array creation.
Users can provide values enclosed in curly braces {}.
This method allows the user to initialize the array at the moment of declaration using an
initializer list. An initializer list is a collection of values enclosed
within curly braces {} and separated by commas.
Syntax for array initialization:
data_type array_name[size] = {value1, value2, ... valueN};
Example:
// C Program to demonstrate array initialization
#include <stdio.h>
int main() {
// Array initialization using initializer list
int no[5] = { 110, 200, 130, 400, 50 };
printf("\n Value of array at third place=%d", no[2]);
return 0;
}
2. Array Initialization with Declaration without Size
This method is similar to the previous one, but you omit the array size during declaration.
The compiler automatically calculates the size based on the number of elements provided in the initializer list.
Syntax:
data_type array_name[] = {v1, v2, v3, v4, v5};
In the syntax above, the size of the array is 5, which is automatically calculated by the compiler.
The compiler allocates memory exactly equal to the number of values specified inside the curly braces {}.
The following example demonstrates how to declare and initialize an integer array emp_salary without specifying the size:
// Array initialization with Declaration without size
#include <stdio.h>
int main() {
// Size is determined by the number of elements: 5
int emp_salary[] = {8000, 12000, 13000, 4000, 5000};
printf("\nThird salary = %d", emp_salary[2]);
return 0;
}
Output:
Third salary = 13000
3. Array Initialization After Declaration (Using Loops)
You can initialize an array using a for loop.
This method iterates from index 0 to (size - 1), filling the array dynamically.
This approach is particularly useful when you need to calculate values at runtime rather than hard-coding them.
#include <stdio.h>
int main() {
// Declare an array
int salary[5];
int i;
// Initialize array using a "for" loop
for(int i = 0; i < 5; i++) {
salary[i] = 1300 * i;
}
return 0;
}
Explanation:
In the program above, the array salary of size 5 is declared first.
The for loop then iterates from 0 to 4, calculating the value for each index.
After execution, the array salary will contain the following values:
salary = {0, 1300, 2600, 3900, 5200}
4. Array Initialization by Specifying Size
In C programming, you can create an array by specifying its size and assigning elements at the time of declaration.
This method differs from the previous ones because if you initialize fewer values than the declared size,
the compiler automatically initializes the remaining elements to 0.
Syntax:
// Declare an array by specifying size and initializing at declaration
int salary[4] = {100, 200, 300, 400};
// Array with fewer values than size
int salary2[4] = {100, 200, 300};
In the example above, salary is an array of size 4 where all four elements are explicitly initialized.
However, salary2 is also size 4 but has only three values provided.
The compiler automatically sets the fourth element to 0.
5. Getting Input from the User
In C programming, you can populate an array at runtime by taking input from the user.
This is typically done using a for loop combined with the scanf() function.
The loop iterates through each index of the array, storing the user's input sequentially.
#include <stdio.h>
int main() {
int salary[5];
int i;
printf("\nEnter five different salaries:\n");
// Loop 1: Get input from user and store in array
for(i = 0; i < 5; i++) {
scanf("%d", &salary[i]);
}
printf("\nThe Salaries Are:\n");
// Loop 2: Display the stored values
for(i = 0; i < 5; i++) {
printf("%d\n", salary[i]);
}
return 0;
}
In the example above, the first for loop runs 5 times, asking the user for input and storing it in salary[i].
The second loop iterates through the array to print the values back to the screen to verify the input.
6. Initialization with Specific Indices (Mixed)
In C, you can mix designated initialization with sequential assignment. This allows you to set specific indices explicitly and let the compiler fill the subsequent indices automatically.
// Example: Designating specific indices and filling the rest sequentially
int salary[5] = { [4] = 5000, [0] = 1200, 2560, 3200, 4500 };
In the example above, index 4 is explicitly set to 5000. Then, index 0 is set to 1200.
Because the list continues after [0], the compiler automatically assigns the next values (2560, 3200, 4500)
to indices 1, 2, and 3 respectively.
7. Using Designated Initializers (C99 Standard)
This method allows you to initialize specific array elements by explicitly stating their indices. This is the clearest way to initialize an array non-sequentially, ensuring you don't accidentally mix up the order of values.
int salary[4] = { [0] = 1500, [1] = 2000, [2] = 5400, [3] = 6500 };
This initializes the salary array elements directly by specifying their index and corresponding value.
Any indices not specified (if the array size is larger than the list) are automatically initialized to 0.