CPPS Unit 3
CPPS Unit 3
An array is defined as the collection of similar type of data items stored at contiguous memory
locations.
Arrays are the derived data type in C programming language which can store the primitive type of
data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types, such as pointers, structure,
etc.
The array is the simplest data structure where each data element can be randomly accessed by
using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks in
the different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
2. TWO DIMENSIONAL ARRAY IN C:
Two dimensional array is nothing but array of array.
syntax : data_type array_name[num_of_rows][num_of_column];
int main()
{
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
}
OUTPUT:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
C – String