Unit-2 Array

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

UNIT-2

Array: Representation of Linear Arrays, Types of Arrays : 1D,2D & M-D Concept

Array: Array is a container which can hold fix number of items and these items should be of
same type. Most of the data structure make use of array to implement their algorithms.
Following are important terms to understand the concepts of Array.
Element − Each item stored in an array is called an element.
Index − Each location

Array Representation
Arrays can be declared in various ways in different languages. For illustration, let's take C
array declaration.

The elements in this array are 1, 4, 8, 25, 2, and 17, and they are stored at indexes starting
from 0 to 5 (size-1). However, it is essential to declare the data types of the elements stored
in the array while declaring. The basic syntax for declaring an array in C is given here.

Data_type array_name[ array_size ];

Let us name our array “arr” and declare it using the above syntax. The data type of our array
elements will be integer, and the size is 6.

o dataType specifies the data type of the array. It can be any valid data type in C
programming language, such as int, float, char, double, etc.
o Name of array is the name of the array, which is used to refer to the array in the
program.
o Size of array specifies the number of elements in the array. It must be a positive
integer value.

Why do we need Arrays?

Array stores an extensive collection of similar data types. We have only three variables, and
then we can easily store them using separate names like int var1, int var2, and int var3, but
what if we have an extensive collection of these variables? Then, we cannot assign separate
names to each of them, as it would be tedious and time-consuming.

Here comes the use of arrays in C, where we can store multiple data type values in a
contiguous memory block. Hence, we can use an array in C when we are working with a
large number of similar items.

Basic Operations

Following are the basic operations supported by an array.


Traverse − print all the array elements one by one.
Insertion − add an element at given index.
Deletion − delete an element at given index.
Search − search an element using given index or by value.
Update − update an element at given index.

There are majorly three types of arrays:


1. One-dimensional array (1-D arrays)
2. Two-dimensional (2D) array
3. Three-dimensional array

1. One-dimensional array (1-D arrays):


Array in C Initialization and Declaration

You need to initialise your array with some initial value at the time of declaration. This is
done because when declaring arrays in C, they contain garbage values inside, which can alter
our desired output. However, the easiest way to initialise the array is using the method below.

Array initialization using simplest approach

arr [0] = 1; // initialising array in C

arr [1] = 4;

arr [2] = 8;

arr [3] = 25;

arr [4] = 2;

arr [5] = 17;

Hence, we need to initialise our array with some starting value. There are a few methods for
declaring and initialising our array.

1. Initializing Array In C During Declaration

Let us initialise our array with a proper size and elements inside. This list contains the
elements enclosed within curly braces {}.

Data_type name_of_array [ size ] = { value1, value2,……,valueN};


Array in C

int arr[6] = { 1, 4, 8, 25, 2, 17}

2. Initializing Array In C Without Size

Let us initialise our array without a proper predefined size and elements inside. This list
contains the elements enclosed within curly braces {}. In this method, the compiler
automatically detects the size of the array.

Data_type name_of_array [ ] = { value1, value2,……,valueN};

Array without size

int arr[ ] = { 1, 4, 8, 25, 2, 17}

3. Declaring Array in C with Loops

In this declaration method, we will use the loops to declare our array. We will use the loop to
assign values to each element and insert them in our array.

Array using loops

for( int i=0 ; i<N; i++){


name_of_array[ i ] = value i;}

Accessing Elements in Arrays

You can easily access elements in an Array using their index. Suppose we want to access the
element at the third index of our array. Then, we can easily do it using arr[2], which is size-1.

Access Elements in an array

int arr[6] = {1, 4, 8, 25, 2, 17};

printf (“%d”, arr[2]); // Accessing the third element at index 2, which is 8

Also, you can quickly iterate through arrays with loops and conditional statements. It allows quick
and easy retrieval of data items.

Operations on Arrays in Data Structures

Traversal Operation
Array traversal refers to the process of accessing each element of an array in a sequential order. In
data structures, an array is a collection of similar data items that are stored in contiguous memory
locations. Traversing an array involves visiting each element of the array in a specified order,
typically from the beginning to the end or from the end to the beginning.

Algorithm for Traversing an Array


Traversal (data,LB,UB)

Here data is array name and LB is Lower Bound (start) index of the first element of an array. UB
is Upper Bound (End) is the index of the last element

1. Step 1: Start
2. Step 2: [Initialize variable. ] Set i = LB
3. Step 3: Repeat steps 4 and 5 While i <= UB
4. Step 4: Apply process (Print ) to data[i].
5. Step 5: Increment i=i+1
6. Step 6: End of loop
7. Step 7: Stop

Program in c to perform traversal of array

#include <stdio.h>
#include<conio.h>
void main()
{
// Declare and initialize an array
int data[10], i=0,ub;
print("Enter the Size of Array");
scanf("%d",&ub);
for(i=0;i<ub;i++)
{
scanf("%d",&data[i]);
}

// Traverse the array and print each element


for (int i = 0; i < 5; i++)
{
printf("%d ", data[i]);
}

getch();
}
Insertion Operation
Insertion in an array refers to the process of adding a new element to a specific position within the
array while shifting the existing elements to make room for the new element.

1.inserting the element in the beginning of array

Step 1: Start
Step 2: [Initialize variable ] Set i = size - 1
Step 3: Repeat Step 4 and 5 While i >= 0
Step 4: [Move ith element forward. ] set arr[i+1] = arr[i]
Step 5: [Decrease counter. ] Set i = i - 1
Step 6: [End of step 3 loop. ]
Step 7: [Insert element at the beginning. ] Set arr[0] = item
Step 8: Stop

Program in c to Insert new item in the Beginning of array

#include <stdio.h>

void main()
{
int arr[50], n, item,i;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Input the elements of the array


printf("Enter the elements of the array:");
for ( i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Input the value of the new element to be inserted

printf("Enter the new element to be inserted: ");


scanf("%d", &item);

// Shift the elements after the insertion position to the right


for (i = n - 1; i >= 0; i--)
{
arr[i+1] = arr[i];
}

// Insert the new element


arr[0] = item;

// Increment the size of the array


n++;

// Print the updated array


printf("The updated array is:");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}

}
2.inserting the element at the specific position in an array

Here's a simple algorithm in simple language to perform an insertion in an array:

1.Define the array and the element to be inserted.


2.Determine the position where the element should be inserted.
3.Shift the elements after the insertion position to the right by one index to make room for the
new element.
4.Insert the new element at the desired position.
5. Update the length of the array.
Algorithm to Insert an element in an Array
Here size is the array size. Position (pos) is location where element to be inserted and Item is new
value in the array

Step 1: Start
Step 2: [Initialize variable ] Set i = size - 1
Step 3: Repeat Step 4 and 5 While i >= pos-1
Step 4: [Move ith element forward. ] set arr[i+1] = arr[i]
Step 5: [Decrease counter. ] Set i = i - 1
Step 6: [End of step 3 loop. ]
Step 7: [Insert element. ] Set arr[pos-1] = item
Step 8: Stop

Program in c to Insert new item at specific position in an array

#include <stdio.h>
void main()
{
int arr[50], n, pos, item,i;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Input the elements of the array


printf("Enter the elements of the array:");
for ( i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Input the position and value of the new element to be inserted

printf("Enter the position and value of the new element to be inserted: ");
scanf("%d%d", &pos, &item);

// Shift the elements after the insertion position to the right


for (i = n - 1; i >= pos-1; i--)
{
arr[i+1] = arr[i];
}

// Insert the new element at the desired position


arr[pos-1] = item;

// Increment the size of the array


n++;

// Print the updated array


printf("The updated array is:");
for (i = 0; i < n; i++)
{
printf("%d", arr[i]);
}
}
Time Complexity: O(N), Where N is the number of elements in the array
Auxiliary Space: O(1)

3. Inserting the element at the end of array


Step 1: Start
Step 2: [Insert element at the end. ] Set arr[size] = item
Step 3: Stop

Program in c to Insert new item in the end of array

#include <stdio.h>

void main()
{
int arr[50], n, item,i;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Input the elements of the array


printf("Enter the elements of the array:");
for ( i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

// Input the value of the new element to be inserted

printf("Enter the new element to be inserted: ");


scanf("%d", &item);

// Insert the new element at the end of the array


arr[n] = item;

// Increment the size of the array


n++;

// Print the updated array


printf("The updated array is:");
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}

Deletion Operation
Deletion in an array means removing an element from an array and shifting the remaining elements
to fill the empty space.

1.Deleting the element from the beginning of array

Step 1: Start
Step 2: [Initialize variable] Set i = 0
Step 3: Repeat Step 4 and 5 for i = 0 to i < size - 1
Step 4: [Move (i+1)th element left side] Set a[i] = a[i+1]
Step 5: [Increment] Set i = i + 1
Step 6: [End of Step 03 loop]
Step 7: [Update Array Size] Set size = size - 1
Step 8: Stop

Program to Delete the element from the beginning of array

#include <stdio.h>
void main()
{
int array[100], position, i, n;

printf("Enter the number of elements in array:");


scanf("%d", &n);

printf("Enter %d elements:", n);


for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}

for (i = 0; i < n; i++)


{
array[i] = array[i+1];
}
n--;
printf("Final array is:");

for (i = 0; i < n; i++)


{
printf("%d ", array[i]);
}
}

2. Delete an element from the specific position in an Array

Here is the algorithm to delete an element from an array in C:

1.Initialize the array and the index of the element to be deleted.


2.Traverse the array from the index of the element to be deleted until the end of the array.
3.Shift each element one position to the left.
4.Decrement the size of the array by 1.

Algorithm to Delete an element from the specific position in an Array:


Step 1: Start
Step 2: [Initialize variable] Set i = pos - 1
Step 3: Repeat Step 4 and 5 for i = pos - 1 to i < size
Step 4: [Move ith element left side ] set a[i] = a[i+1]
Step 5: [Incerement ] Set i = i + 1
Step 6: [End of step 03 loop. ]
Step 7: [Update Array Size] set size = size - 1
Step 8: Stop
Program in C to perform deletion in array

#include <stdio.h>
void main()
{
int array[100], position, i, n;

printf("Enter the number of elements in array:");


scanf("%d", &n);

printf("Enter %d elements:", n);


for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the location where you wish to delete element:");
scanf("%d", &position);

if (position >= n+1)


{
printf("Deletion not possible.");
}
else
{
for (i = position-1; i < n-1; i++)
{
array[i] = array[i+1];
}
printf("Final array is:");

for (i = 0; i < n-1; i++)


{
printf("%d ", array[i]);
}
}
}

3. Deleting the element from the End of array

Step 1: Start
Step 2: [Initialize variable] Set i = size - 1
Step 3: Repeat Step 4 and 5 for i = size - 1 to i > 0
Step 4: [Move (i-1)th element right side] Set a[i] = a[i-1]
Step 5: [Decrement] Set i = i - 1
Step 6: [End of Step 03 loop]
Step 7: [Update Array Size] Set size = size - 1
Step 8: Stop

Program to Delete the element from the End of the array

#include <stdio.h>
void main()
{
int array[100], position, i, n;

printf("Enter the number of elements in array:");


scanf("%d", &n);

printf("Enter %d elements:", n);


for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}

if(n>0)
{
n--;
printf("Final array is:");

for (i = 0; i < n; i++)


{
printf("%d ", array[i]);
}
}
else
{
printf(“Array is empty”);
}
}

2D Array in C

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can b
represented as the collection of rows and columns. However, 2D arrays are created to implement a relation
database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to an
number of functions wherever required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.

1. int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at
least the second dimension of the array. The two-dimensional array can be declared and defined in
the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
2D array example: Storing elements in a matrix and printing it.
#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

printing the elements ....

56 10 30
34 21 34
45 56 78

/*Program for addition of Two Matrices

#include <stdio.h>
int main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the elements of matrix A: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of matrix B: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &b[i][j]);
}
}
// add the matrices
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
// print the result
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}

/*Program for multiplication of 2 matrices*/

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

Three-Dimensional Array in C

A Three Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be visualized as


multiple 2D arrays stacked on top of each other.
Graphical Representation of Three-Dimensional Array of Size 3 x 3 x 3

Declaration of Three-Dimensional Array in C

We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.
Syntax:
data_type array_name[x][y][z];
• data_type: Type of data to be stored in each element.
• array_name: name of the array
• x: Number of 2D arrays.
• y: Number of rows in each 2D array.
• z: Number of columns in each 2D array.
Example:
int array[3][3][3];

Initialization of Three-Dimensional Array in C

Initialization in a 3D array is the same as that of 2D arrays. The difference is as the number of dimensions
increases so the number of nested braces will also increase.
A 3D array in C can be initialized by using:
1. Initializer List
2. Loops

Initialization of 3D Array using Initializer List


Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Method 2(Better):
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Initialization of 3D Array using Loops
It is also similar to that of 2D array with one more nested loop for accessing one more dimension.
int x[2][3][4];

for (int i=0; i<2; i++) {


for (int j=0; j<3; j++) {
for (int k=0; k<4; k++) {
x[i][j][k] = (some_value);
}
}
}

Accessing elements in Three-Dimensional Array in C

Accessing elements in 3D Arrays is also similar to that of 3D Arrays. The difference is we have to use
three loops instead of two loops for one additional dimension in 3D Arrays.
Syntax:
array_name[x][y][z]
where,
• x: Index of 2D array.
• y: Index of that 2D array row.
• z: Index of that 2D array column.
• C

// C program to print elements of Three-Dimensional Array

#include <stdio.h>

int main(void)
{
// initializing the 3-dimensional array
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };

// output each element's value


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at x[%i][%i][%i] = %d\n", i,
j, k, x[i][j][k]);
}
}
}
return (0);
}

Output
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11

You might also like