CC102 Array Declaration and Initialization
CC102 Array Declaration and Initialization
Initialization
Computer Programming 1
BSCS – 1B
C Array Declaration
We can declare an array by specifying its name, the type of its elements, and the size of its dimensions.
When we declare an array in C, the compiler allocates the memory block of the specified size to the
array name.
Syntax for Array Declaration
data_type: The type of data the array will store (e.g., int, float, char).
array_name: The name used to reference the array.
array_size: The number of elements the array can hold (must be a constant or a macro in standard C).
Example of Array Declaration
Here, memory is allocated for 5 integers, but the values are uninitialized (contain garbage values).
Data Type
Specifies the type of data (e.g., int, float, char) the array will hold.
Example: int arr[5];
This declares an array of integers named arr with 5 elements.
Size
The size of an array refers to the number of elements it can hold. It is specified when declaring the array
and must be a constant value. The size determines the array's memory allocation.
Example: int arr[10];
This array can store up to 10 integer values.
Index
The index is the position of an element within an array. It is used to access or modify elements.
C arrays are zero-indexed, meaning:
The first element is at index 0.
The last element is at index size - 1.
C Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is declared or
allocated memory, the elements of the array contain some garbage value. So, we need to initialize the array
to some meaningful value. There are multiple ways in which we can initialize an array in C.
Syntax for Array Initialization
Output
2. Float Array
Output
Full Code Examples of Array Declaration and Initialization
3. Array for Calculating Average
Output
Advantages of Arrays in C
1. Efficient Memory Usage: Arrays provide a way to store data sequentially, reducing memory
wastage.
2. Easy Data Access: Elements can be accessed directly using their indices.
3. Compact Code: Using loops, operations can be performed on multiple elements, reducing
repetitive code.
4. Static Storage: Data is allocated contiguously, enabling faster access and manipulation.
5. Ideal for Fixed-Size Data: Arrays are perfect when the number of elements is known in
Disadvantages
advance.
of Arrays in C
1. Fixed Size: The size of an array must be defined at the time of declaration, limiting flexibility.
2. Homogeneous Data: Arrays can only store elements of the same data type.
3. No Built-in Bounds Checking: Accessing indices outside the declared range can lead to
undefined behavior.
4. Insertion and Deletion: These operations are time-consuming as they require shifting elements.
5. Memory Allocation: If improperly handled, large arrays can lead to excessive memory usage.
Write a C program to calculate the sum of all elements
in the array.