Array
Array
10 23 5 7 68 1 4 87 9
10 23 5 7 68 1 4 87 9
Array:
An array is a collection of similar data elements. These data elements
have the same data type. The elements of the array are stored in
consecutive memory locations and are referenced by an index, also
known as the subscript.
Index is an ordinal number which is used to identify an element of the
array.
Declaration of Array:
To create an array, define the data type (like int) and specify the name
of the array followed by square brackets [].
Syntax of Array-
data_type array_name[array_size];
Example:
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
Array Initialization:
e.g.-
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]; //declaration of array
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Array Initialization with Declaration:
Initialize the array along with its declaration. We use an initializer list
to initialize multiple elements of the array. An initializer list is the list
of values enclosed within braces { } separated by a comma.
Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60}; //declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Array Initialization after Declaration (Using Loops):
Initialize the array after the declaration by assigning the initial value
to each element individually. We can use for loop, while loop, or do-
while loop to assign the value to each element of the array.
Example:
int main()
{
// array initialization using initializer list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++)
{
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access the Elements of an Array:
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
array_name [index];
One thing to note is that the indexing in the array always starts with 0,
i.e., the first element is at index 0 and the last element is at N – 1
where N is the number of elements in the array.
// Outputs 25
This statement accesses the value of the first element [0] in
myNumbers.
Example:
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Update Array Element:
We can update the value of an element at the given index i in a similar
way to accessing an element by using the array subscript operator [ ]
and assignment operator =.
array_name[i] = new_value;
Example:
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
Array Traversal:
Traversal is the process in which we visit every element of the data
structure. For C array traversal, we use loops to iterate through each
element of the array.
Similarly, array elements can also be displayed in the output using the
printf() method. The index is specified indicating the position of the
element to be printed.
e.g.- // print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);
Example:
#include <stdio.h>
int main()
{
// declare an array.
int my_array[20], n;
printf("Enter the number of array elements:\n");
scanf(“%d”, &n);
// input array elements.
printf("Enter array elements:\n");
int i;
for (i = 0; i < n; i++)
{
Printf(“\n my_array [%d] = ”, i);
scanf("%d", &my_array[i]);
}
printf("\n The array elements are:\n");
// print array elements.
for (i = 0; i <= n; i++)
{
printf("my_array[%d] = %d\t ", i, my_array[i]);
}
return 0;
}
int marks [5] = {90, 45, 67, 85, 78 };
90 45 67 85 78
[0] [1] [2] [3] [4]
int marks [] = {91, 54, 67, 95, 87 };
91 54 67 95 87
[0] [1] [2] [3] [4]
int marks [5] = {90, 45 }; **Rest of the elements are filled with 0s
90 45 0 0 0
[0] [1] [2] [3] [4]
int marks [5] = {0};
0 0 0 0 0
[0] [1] [2] [3] [4]
Array Size & Address of element:
To get the size of an array, you can use the sizeof operator.
e.g.-
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
printf("%d", length);
Find out how many elements an array has, you can use the formula
(which divides the size of the array by the size of one array element).
10 25 50 75 100
myNumbers [0] [1] [2] [3] [4]
1000 1002 1004 1006 1008
Example of use of size of the array:
#include <stdio.h>
int main()
{
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a 'lowest age' variable and assign the first array element of
ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (i = 0; i < length; i++)
{
// Check if the current age is smaller than current the 'lowest age'
if (lowestAge > ages[i])
{
// If the smaller age is found, update 'lowest age' with that
element
lowestAge = ages[i];
}
}
// Output the value of the lowest age
printf("The lowest age in the array is: %d", lowestAge);
return 0;
}
Types of Array:
A list of items can be given one variable name using only one subscript
and such a variable is called one-dimensional array or single-
dimensional variable.
The data-type specifies the type of elements such as int, float or char.
And the size indicates the maximum number of elements that can be
stored in that array.
#include <stdio.h>
int main()
{
// creating array of character
char arr[8] = { 'A', 's', 'a', 'n', 's', 'o', 'l', '\0' };
// printing string
int i = 0;
while (arr[i])
{
printf("%c", arr[i++]);
}
return 0;
}
Sorting an array:
An array of size 10 is initialized. The array elements are sorted in
descending order using the bubble sort algorithm.
Example:
#include <stdio.h>
int main()
{
int i, j, temp;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
// print unsorted array.
printf("Original array is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
// sort the array elements in descending order.
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (my_array[j] > my_array[i])
{
temp = my_array[i];
my_array[i] = my_array[j];
my_array[j] = temp;
}
}
}
// print the sorted elements.
printf("\n\nSorted array in descending order is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
return 0;}
Inserting an element in an array:
Inserting an element in array means adding a new data element to an
existing array.
If the element has to be inserted at the end of the existing array, then
the task of inserting is quite simple.We just have to add 1 to the
upper_bound and assing the value.
Then,
Calculate the length of the array.
Find the upper bound and lower bound
12 23 45 65 75 84 98 100
#include <stdio.h>
int main()
{
int i, n, element, pos, arr[10];
// initialize an array.
printf("\n Enter the number of elements in the array: ");
scanf(“%d”, &n);
//arr[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf(“\n Enter the values”);
for( i=0; i<n; i++)
{
scanf(“%d”, &arr[i]);
}
// input index where the element is to be inserted.
printf("Enter the position at which the number has to be added: ");
scanf("%d", &pos);
// input the element to be inserted.
printf("Enter the element to be inserted: ");
scanf("%d", &element);
if (pos > 10)
{
printf("Input is invalid !");
}
else
{
// right shifting array elements.
for (i = n-1; i >= pos; i--)
arr[i + 1] = arr[i];
// insert the element at "pos".
arr[pos] = element;
n++;
printf("\n The array after insertion of %d is: ", element);
// print array elements.
for (i = 0; i <n; i++)
printf("\t % d ", arr[i]);
}
return 0;
}
Deleting an element from an array:
Deleting an element from array means removing a data element from
an already existing array.
If the element has to be deleted from the end of the existing array,
then the task of deletion is quite simple.We just have to subtract 1
from the upper_bound.
#include <stdio.h>
int main()
{
int i, n, pos, arr[10];
// initialize an array.
printf("\n Enter the number of elements in the array: ");
scanf(“%d”, &n);
//arr[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf(“\n Enter the element of the array: ”);
for( i=0; i<n; i++)
{
scanf(“%d”, &arr[i]);
}
// input index where the element is to be deleted.
printf("Enter the position from which the number has to be deleted: ");
scanf("%d", &pos);
// element to be deleted.
if (pos > 10)
{
printf("Input is invalid !");
}
else
{
// left shifting array elements.
for (i = pos; i < n-1; i++)
arr[i] = arr[i+1];
n--;
printf("\n The array after deletion is: ");
// print array elements.
for (i = 0; i <n; i++)
printf("\t Array[%d] = % d ",i, arr[i]);
}
return 0;
}
Merging two arrays:
Merging two arrays in a third array means first copying the contents
of the first array into the third array and then copying the contents of
the second array into the third array.
Hence the merge array contains contents of the first array followed by
the contents of the second array.
E. g. Unsorted array…
Array 1 90 56 89 77 69
Array 2 45 88 76 99 12 58
Array 3
90 56 89 77 69 45 88 76 99 12 58
Logic is
index = 0;
for (i = 0 ; i < n1; i++)
{
arr3 [index] = arr1 [ i ];
index++;
}
for (i = 0 ; i < n2; i++)
{
arr3 [index] = arr2 [ i ];
index++;
}
There are two popular method for searching the array elements.
One is linear search and the second is binary search.
A [0] != VAL
10 8 2 7 3 4 9 1 6 5
A [1] != VAL
10 8 2 7 3 4 9 1 6 5
A [2] != VAL
10 8 2 7 3 4 9 1 6 5
A [3] = VAL
10 8 2 7 3 4 9 1 6 5
ALGORITHM:
LINEAR_SEARCH (A, N, VAL)
#include <stdio.h>
int main()
{
int i, element;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf("Enter element to be searched:\n");
// input element to be searched.
scanf("%d", &element);
// traverse the array to search the element.
for (i = 0; i <= 9; i++)
{
if (my_array[i] == element)
{
// print the index at which the element is found.
printf("Element found at index %d", i);
break();
}
}
// if the element is not found.
if (i == 10)
{
printf("\nElement not found!");
}
return 0;
}
Print the largest and second largest element of the array
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);
}
Multidimensional Array
So, if you want to store data as a tabular form, like a table with rows
and columns, you need to get familiar with multidimensional arrays.
A multidimensional array is basically an array of arrays.
dataType arrayName[no_of_rows][no_of_columns];
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
int my_array[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90};
int my_array[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90};
// invalid: second dimension must be specified.
int matrix[2][3] = { 1, 4, 2, 3, 6, 8 };
The first dimension represents the number of rows [2], while the
second dimension represents the number of columns [3]. The values
are placed in row-order, and can be visualized like this:
Memory Map of a 2-Dimensional Array
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
or
main( )
{
int s[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ;
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;
}
Access the Elements of a 2D Array
To access an element of a two-dimensional array, you must specify the
index number of both the row and column.
Example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
change the value of the element in the first row (0) and first column
(0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\n", matrix[i][j]);
}
}
Two-dimensional array example
#include <stdio.h>
int main () {
return 0;
}
OUTPUT:
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
2. Example of Printing Two-dimensional Array as Matrix in
Row and Columns.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
OUTPUT: Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
3. Example of finding Sum and Product of Two 2 Matrices
#include <stdio.h>
int main()
{
// declaring arr1 and arr2.
int arr1[2][2], arr2[2][2];
int sum[2][2], product[2][2];
// reading input for arr1 from the user.
printf("Enter the elements of arr1 : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr1[%d][%d] :", i, j);
scanf("%d", &arr1[i][j]);
}
printf("\n");
}
// reading input for arr2 from the user.
printf("Enter the elements of arr2: \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr2[%d][%d] :", i, j);
scanf("%d", &arr2[i][j]);
}
printf("\n");
}
// adding the corresponding array elements.
printf("Sum array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
sum[i][j] = arr1[i][j] + arr2[i][j];
//print the sum array
printf("%d\t", sum[i][j]);
}
printf("\n");
}
// multiplying the corresponding array elements.
printf("Product array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
product[i][j] = arr1[i][j] * arr2[i][j];
// print the product array.
printf("%d\t", product[i][j]);
}
printf("\n");
}
return 0;
}
OUTPUT:
Enter the elements of arr1 :
arr1[0][0] : 2
arr1[0][1] : 4
arr1[1][0] : 2
arr1[1][1] : 3
arr2[1][0] : 3
arr2[1][1] : 6
Sum array is :
3 6
5 9
Product array is :
2 8
6 18
4. Example of Multiplication of Two-dimensional Array Matrix
#include<stdio.h>
int main(){
int mat1[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int mat2[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
int mat3[3][3], sum=0, i, j, k;
12
34
1 3
2 4
Three-Dimensional Array
Students[hall][row][column]
Eg.-
int arr[3][4][2] = {
{
{ 2, 4 },
{ 7, 8 },
{ 3, 4 },
{ 5, 6 }
},
{
{ 7, 6 },
{ 3, 4 },
{ 5, 3 },
{ 2, 3 }
},
{
{ 8, 9 },
{ 7, 2 },
{ 3, 4 },
{ 5, 1 },
}
};
Example:
#include<stdio.h>
void main()
{
int a[5][5][5];
inti,j,k,x,y,z;
printf("\n Enter the size of a 3D array ");
scanf("%d%d%d",&x,&y,&z);
printf("\n Enter values into a 3D array of size %dx%dx%d \n",x,y,z);
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
scanf("%d",&a[i][j][k]);
}
}
}
printf("\n A three dimensional array is :\n");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
printf(" %d",a[i][j][k]);
}
printf("\n");
}
printf("\n\n");
}
return 0;
}