Q)what is an array.
explain decleration and initilization of 1D
array in C
An array is a fundamental data structure that stores a fixed-size sequential
collection of elements of the same data type.
• The elements are stored in contiguous memory locations (right next
to each other).
• Each element can be uniquely identified and accessed using an index
or subscript, which typically starts at 0 for the first element.
Declaring a 1D Array in C
Declaration tells the compiler the name of the array, the type of data it will
hold, and its size
Syntax
The general syntax for declaring a 1D array in C is:
dataType arrayName[arraySize];
dataType:The type of elements the array will store (e.g., int, char,
float).
ArrayName :Array name shoulad be valid identifier.
ArraySize :It specifies the number of elements the array can hold.
Example of Declaration
To declare an array named scores that can hold 5 integer values:
int scores[5];
• This creates an array named scores capable of storing 5 integers.
• The valid indices for this array are 0, 1, 2, 3, and 4.
Initialization of one-dimensional array
Assigning the required values to an array elements before processing is
called initialization.
Syntax:
data type array_name[expression]={v1,v2,v3…,vn};
Where
datatype can be char,int,float,double
array name is the valid identifier
size is the number of elements in array
v1,v2,v3……..vn are values to be assigned.
The various ways of initializing arrays are as follows:
1. Initializing all elements of array(Complete array initialization)
2. Partial array initialization
3. Initialization without size
4. String Initialization
1. Initializing all elements of array:(complete array initialization)
Arrays can be initialized at the time of declaration when their initial
values are known in advance.
Example:
int a[5]={10,20,30,40,50};
Partial array Initialization
If the number of values in the initializer list is less than the specified size,
the remaining elements are automatically initialized to 0 (for numeric
types) or null (for character types).
Example:
int a[5]={10,20};
3. Initialization without size
The compiler will set the size based on the number of initial values
Example:
int a[ ]={10,20,30,40,50};
In the above example the size of an array is set to 5
4. String Initialization
Sequence of characters enclosed within double quotes is called as string.
The string always ends with NULL character(\0)
Example:
char s[5]=”SVIT”;
We can observe that string length is 4,but sizeis 5 because to store NULL
character we need one more location.