Explanation
Declaring and Accessing Single-Dimensional Arrays:
Declaration:
-
To declare a single-dimensional array, you specify the data type and the array name followed by the size in square brackets.
int myArray[5]; // Declares an integer array of size 5
Accessing Values:
-
You can access individual values in the array using square brackets and the index (starting from 0).
int value = myArray[2]; // Accesses the value at index 2
Initialization During Compile Time:
Declaration and Initialization:
-
You can declare and initialize an array during compile time by providing values within curly braces ‘ {} ‘.
int myArray[] = {1, 2, 3, 4, 5}; // Initializes an integer array
Initialization During Compile Time:
Declaration:
-
Declare an array without specifying its size. The size may depend on user input or other dynamic factors.
int myArray[5]; // Declare an integer array with a size of 5
Initialization:
-
Initialize the array during run time, typically using loops or user input.
for (int i = 0; i < 5; i++) {
printf("Enter a value: ");
scanf("%d", &myArray[i]);
}
Declaring and Accessing Double-Dimensional Arrays:
Declaration:
-
To declare a double-dimensional array (a matrix), you specify the data type, array name, and the dimensions in square brackets.
int myMatrix[3][3]; // Declares a 3x3 integer matrix
Accessing Values:
-
You can access individual values in the 2D array using two sets of square brackets.
int value = myMatrix[1][2]; // Accesses the element at row 1, column 2
program that initializes an array during compile time and another that initializes an array during run time:
Compile-Time Initialization:
#include <stdio.h>
int main() {
int myArray[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
Run-Time Initialization:
#include <stdio.h>
int main() {
int myArray[5];
for (int i = 0; i < 5; i++) {
printf("Enter a value: ");
scanf("%d", &myArray[i]);
}
for (int i = 0; i < 5; i++) {
printf("%d ", myArray[i]);
}
return 0;
}
The first program initializes an array with predefined values, while the second program initializes an array during run time using user input.