Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Basic Operations of Array

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

Array

Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used
to identify the element.

Array Representation

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

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

As per the above illustration, following are the important points to be considered.
 Index starts with 0.
 Array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.

Basic Operations of Array

Following are the basic operations supported by an array.


 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.
In C, when an array is initialized with size, then it assigns defaults values to its elements in
following order.

Data Type Default Value

bool false

char 0

int 0

float 0.0

double 0.0f

void

Traverse Operation

This operation is to traverse through the elements of an array.

Example

Following program traverses and prints the elements of an array:


#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n)";
for(i = 0; i<n; i++) {
printf"LA[%d] = %d \n"<< i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result −

Output

The original array elements are :


LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8

Insertion Operation

Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index of array.
Here, we see a practical implementation of insertion operation, where we add data at the end
of the array −

Example

Following is the implementation of the above algorithm −


#include < stdio.h >

main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;

printf(“The original array elements are :\n");

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


print(“fLA[%d] = %d \n",i, LA[i]);
}

n = n + 1;

while( j >= k) {
LA[j+1] = LA[j];
j = j - 1;
}

LA[k] = item;

cout<<"The array elements after insertion :\n";

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


printf(“LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result −

Output

The original array elements are :


LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after insertion :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 10
LA[4] = 7
LA[5] = 8
For other variations of array insertion operation click here

Deletion Operation

Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.


Following is the algorithm to delete an element available at the Kth position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop

Example

Following is the implementation of the above algorithm −


#include < stdio.h >

void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;

printf("The original array elements are :\n");

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


printf("LA[%d] = %d \n", i, LA[i]);
}

j = k;

while( j < n) {
LA[j-1] = LA[j];
j = j + 1;
}

n = n -1;

printf("The array elements after deletion :\n");


for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result −

Output

The original array elements are :


LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after deletion :
LA[0] = 1
LA[1] = 3
LA[2] = 7
LA[3] = 8

Search Operation

You can perform a search for an array element based on its value or its index.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.


Following is the algorithm to find an element with a value of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop

Example

Following is the implementation of the above algorithm −


#include <stdio.h>

void main() {
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;

printf("The original array elements are :\n");


for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}

while( j < n){


if( LA[j] == item ) {
break;
}

j = j + 1;
}

printf("Found element %d at position %d\n", item, j+1);


}
When we compile and execute the above program, it produces the following result −

Output

The original array elements are :


LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Found element 5 at position 3

Update Operation

Update operation refers to updating an existing element from the array at a given index.

Algorithm

Consider LA is a linear array with N elements and K is a positive integer such that K<=N.


Following is the algorithm to update an element available at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop

Example

Following is the implementation of the above algorithm −


#include <stdio.h>

void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");

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


printf("LA[%d] = %d \n", i, LA[i]);
}

LA[k-1] = item;

printf("The array elements after updation :\n");

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


printf("LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result −

Output

The original array elements are :


LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
LA[3] = 7
LA[4] = 8
Bubble Sort Algorithm
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based
algorithm in which each pair of adjacent elements is compared and the elements are
swapped if they are not in order. This algorithm is not suitable for large data sets as its
average and worst case complexity are of Ο(n2) where n is the number of items.

How Bubble Sort Works?

We take an unsorted array for our example. Bubble sort takes Ο(n 2) time so we're
keeping it short and precise.

Bubble sort starts with very first two elements, comparing them to check which one
is greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.


We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After
one iteration, the array should look like this −

To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that an array is completely
sorted.

Now we should look into some practical aspects of bubble sort.

Algorithm
We assume list is an array of n elements. We further assume that swap function
swaps the values of the given array elements.
Algorithm BubbleSort(list)
{
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list
}

Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the
whole array is completely sorted in an ascending order. This may cause a few complexity
issues like what if the array needs no more swapping as all the elements are already
ascending.
To ease-out the issue, we use one flag variable swapped which will help us see if any swap
has happened or not. If no swap has occurred, i.e. the array requires no more processing to
be sorted, it will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as follows −
Algorithm bubbleSort( list : array of items )
{
loop = list.count;

for i = 0 to loop-1 do:


swapped = false

for j = 0 to loop-1 do:

/* compare the adjacent elements */


if list[j] > list[j+1] then
/* swap them */
swap( list[j], list[j+1] )
swapped = true
end if

end for

/*if no number was swapped that means


array is sorted now, break the loop.*/

if(not swapped) then


break
end if

end for

return list
}

Implementation
One more issue we did not address in our original algorithm and its improvised
pseudocode, is that, after every iteration the highest values settles down at the end
of the array. Hence, the next iteration need not include already sorted elements.

// below we have a simple C++ program for bubble sort


#include <iostream.h>
void bubbleSort(int arr[], int n)
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// print the sorted array


printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}

int main()
{
int arr[100], i, n, step, temp;
// ask user for number of elements to be sorted
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);
return 0;
}
Linear Search

What is Search?
Search is a process of finding a value in a list of values. In other words,
searching is the process of locating given value position in a list of values.

Linear Search Algorithm (Sequential Search Algorithm)


Linear search algorithm finds a given element in a list of elements
with O(n) time complexity where n is total number of elements in the list. This
search process starts comparing search element with the first element in the list.
If both are matched then result is element found otherwise search element is
compared with the next element in the list. Repeat the same until search element
is compared with the last element in the list, if that last element also doesn't
match, then the result is "Element not found in the list". That means, the search
element is compared with element by element in the list.

Linear search is implemented using following steps...


Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and
terminate the function
Step 4 - If both are not matched, then compare search element with the
next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last
element in the list.
Step 6 - If last element in the list also doesn't match, then display
"Element is not found!!!" and terminate the function.
Algorithm:
//Let array a[n] stores n elements. Determine whether element ‘x’ is present or
not.
linsrch(a[n], x)
{
index = 0;
flag = 0;
while (index < n) do
{
if (x == a[index])
{
flag = 1;
break;
} index ++;
}
if(flag == 1)
write(“Data found at %d position“, index);
else
write(“data not found”);
}

Example
Consider the following list of elements and the element to be searched...
Implementation of Linear Search Algorithm using C++ Programming Language
#include<iostream.h>
#include<conio.h>
void main()
{
int list[20],size, i, sElement;
cout<<”Enter size of the list: ";
cin>>size;
cout<<”Enter any”<<size<<” integer values: ";
for(i = 0; i < size; i++)
cin>>list[i];
cout<<"Enter the element to be Search: ";
cin>>sElement;
// Linear Search Logic
for(i = 0; i < size; i++)
{
if(sElement == list[i])
{
Cout<<"Element is found at”<<i<< “ index” ;
break;
}
}
if(i == size)
cout<<"Given element is not found in the list!!!";
getch();
}

Binary Search
Binary search algorithm falls under the category of interval search algorithms. This
algorithm is much more efficient compared to linear search algorithm. Binary
search only works on sorted data structures. This algorithm repeatedly target the
center of the sorted data structure & divide the search space into half till the match
is found.
The time complexity of binary search algorithm is O(Log n).
Binary search is implemented using following steps...
BSEARCH(ARR, LB, UB, ITEM, LOC)
{
/*Here, ARR is a sorted list of elements, with LB and UB are lower and upper
bounds for the array. ITEM needs to be searched in the array and algorithm
returns location LOC, index at which ITEM is present else return -1.*/

Step1: Set BEG = LB, END = UB and MID = INT([BEG+END]/2)


Step 2: Repeat step 3 and 4 while BEG <= END and ARR[MID] != ITEM
Step 3: IF ITEM< ARR[MID] then:
Set END = MID-1
Else:
Set BEG = MID+1
Step 4: Set MID = INT(BEG+END)/2
Step 5: IF ARR[MID] = ITEM then:
Set LOC = MID
Else:
Set LOC = NULL
Step 6. Exit.
}

Algorithm
//Let array a[n] of elements in increasing order, n ≥0, determine whether ‘x’ is
present, and if so, set j, such that x = a[j] else return 0.
binsrch(a[], n, x)
{
low = 1; high = n;
while (low < high) do
{
mid = (low + high)/2
if (x < a[mid])
high = mid – 1;
else if (x > a[mid])
low = mid + 1;
else return mid;
} return 0;

}
Example:
Let’s say here, ITEM = 62

ARR[1] 2 3 4 5 6 7 8 9
BEG = 1 and END =9 Hence MID = (1+9)/2 = 5

ARR[MID]=ARR[5] = 52

Step 1: ARR[MID] < ITEM : thus END =9 and BEG = MID +1 = 6.


52<62
Thus our new sub-array is,

6 7 8 9
Step 2: Now BEG =6 and END =9 thus MID = INT([6+9]/2)= 6
NOW ARR[6] =ITEM. Thus LOC = MID
ARR[6]=62 = ITEM =62,
Thus LOC = 6
BEG=MID+1=6+1=7
MID=7+9/2=16/2=8
ARR[8]==71
BEG 7, END =MID-1=7
ARR[7]= ITEM
71=71
The complexity of Binary Search
Here are the complexities of the binary search given below.
 Worst Case: O(nlogn)
 Best Case: O(1)
 Average Case: O(nlogn)

//C++ Program to Implement Binary Search –


#include < iostream >
using namespace std;
int binarySearch(int arr[], int left, int right, int x)
{
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == x)
{
return mid;
} else if (arr[mid] < x)
{
left = mid + 1;
} else
{
right = mid - 1;
}
}
return -1;
}
int main()
{
int myarr[10];
int num;
int output;
cout << "Please enter 10 elements ASCENDING order" << endl;
for (int i = 0; i < 10; i++)
{
cin >> myarr[i];
}
cout << "Please enter an element to search" << endl;
cin >> num;
output = binarySearch(myarr, 0, 9, num);
if (output == -1)
{
cout << "No Match Found" << endl;
} else
{
cout << "Match found at position: " << output+1 << endl;
}
return 0;
}

Example 2
 
Consider-
 We are given the following sorted linear array.
 Element 15 has to be searched in it using Binary Search Algorithm.
 

 
Binary Search Algorithm works in the following steps-
 
Step-01:
 
To begin with, we take beg=0 and end=6.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 6) / 2
=3
Here, a[mid] = a[3] = 20 ≠ 15 and beg < end.
So, we start next iteration.
 
Step-02:
 
Since a[mid] = 20 > 15, so we take end = mid – 1 = 3 – 1 = 2 whereas beg remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (0 + 2) / 2
=1
Here, a[mid] = a[1] = 10 ≠ 15 and beg < end.
So, we start next iteration.
 
Step-03:
 
Since a[mid] = 10 < 15, so we take beg = mid + 1 = 1 + 1 = 2 whereas end remains
unchanged.
We compute location of the middle element as-
mid
= (beg + end) / 2
= (2 + 2) / 2
=2
Here, a[mid] = a[2] = 15 which matches to the element being searched.
So, our search terminates in success and index 2 is returned.

Binary Search Algorithm Advantages-


 
The advantages of binary search algorithm are-
 It eliminates half of the list from further searching by using the result of
each comparison.
 It indicates whether the element being searched is before or after the
current position in the list.
 This information is used to narrow the search.
 For large lists of data, it works significantly better than linear search.
 
Binary Search Algorithm Disadvantages-
 
The disadvantages of binary search algorithm are-
 It employs recursive approach which requires more stack space.
 Programming binary search algorithm is error prone and difficult.
 The interaction of binary search with memory hierarchy i.e. caching is
poor.
(because of its random access nature)

Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y, you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of rows
and y number of columns. A 2-dimensional array a, which contains three rows and
four columns can be shown as below −

Thus, every element in array a is identified by an element name of the form a[ i ]


[ j ], where a is the name of the array, and i and j are the subscripts that uniquely
identify each element in a.

Initializing Two-Dimensional Arrays


Multidimensioned arrays may be initialized by specifying bracketed values for each
row. Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{100, 1, 2, 3} , /* initializers for row indexed by 0 */
{654, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array. For example −
int val = a[2][3];
The above statement will take 4 th element from the 3rd row of the array. You can
verify it in the above digram.
Live Demo

#include <iostream.h>

int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {7,4}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


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

cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

When the above code is compiled and executed, it produces the following result −
a[0][0]: 7
a[0][1]: 4
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
As explained above, you can have arrays with any number of dimensions, although
it is likely that most of the arrays you create will be of one or two dimensions.

Multi-dimensional array
A multi-dimensional array is an array of arrays. 2-dimensional arrays are
the most commonly used. They are used to store data in a tabular manner.
Consider following 2D array, which is of the size 3×5. For an array of
size N×M, the rows and columns are numbered from 0 to N−1 and columns are
numbered from 0 to M−1, respectively. Any element of the array can be
accessed by arr[i][j] where 0≤i<N and 0≤j<M. For example, in the following
array, the value stored at arr[1][3] is 14.

Multidimensional arrays use additional subscripts for indexing. A three-


dimensional array, for example, uses three subscripts:

 The first references array dimension 1, the row.


 The second references dimension 2, the column.
 The third references dimension 3. This illustration uses the concept of
a page to represent dimensions 3 and higher.
To access the element in the second row, third column of page 2, for example,
you use the subscripts (2,3,2).

As you add dimensions to an array, you also add subscripts. A four-dimensional


array, for example, has four subscripts. The first two reference a row-column
pair; the second two access the third and fourth dimensions of data.

Pointers

1. Pointers and two dimensional Arrays: In a two dimensional array,


we can access each element by using two subscripts, where first
subscript represents the row number and second subscript represents the
column number. The elements of 2-D array can be accessed with the help
of pointer notation also. Suppose arr is a 2-D array, we can access any
element arr[i][j] of the array using the pointer expression *(*(arr + i) + j).
Now we’ll see how this expression can be derived.
Let us take a two dimensional array arr[3][4]:
int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

Since memory in a computer is organized linearly it is not possible to


store the 2-D array in rows and columns. The concept of rows and
columns is only theoretical, actually, a 2-D array is stored in row-major
order i.e rows are placed next to each other. The following figure shows
how the above 2-D array will be stored in memory.
Each row can be considered as a 1-D array, so a two-dimensional array
can be considered as a collection of one-dimensional arrays that are
placed one after another. In other words, we can say that 2-D dimensional
arrays that are placed one after another. So here arr is an array of 3
elements where each element is a 1-D array of 4 integers.
We know that the name of an array is a constant pointer that points to
0th 1-D array and contains address 5000. Since arr is a ‘pointer to an array
of 4 integers’, according to pointer arithmetic the expression arr + 1 will
represent the address 5016 and expression arr + 2 will represent address
5032.
So we can say that arr points to the 0th 1-D array, arr + 1 points to the
1st 1-D array and arr + 2 points to the 2nd 1-D array.

In general we can write:


arr + i Points to i th element of arr ->
Points to ith 1-D array
 Since arr + i points to i th element of arr, on dereferencing it will
get i  element of arr which is of course a 1-D array. Thus the
th

expression *(arr + i) gives us the base address of ith 1-D array.


 We know, the pointer expression *(arr + i) is equivalent to the
subscript expression arr[i]. So *(arr + i) which is same as arr[i] gives us
the base address of ith 1-D array.

In general we can write:


*(arr + i) - arr[i] - Base address of i th 1-D array -> Points
to 0th element of ith 1-D array
Note: Both the expressions (arr + i) and *(arr + i) are pointers, but their
base type are different. The base type of (arr + i) is ‘an array of 4 units’
while the base type of *(arr + i) or arr[i] is int.
 To access an individual element of our 2-D array, we should be
able to access any jth element of ith 1-D array.
 Since the base type of *(arr + i) is int and it contains the address
of 0  element of ith 1-D array, we can get the addresses of subsequent
th

elements in the ith 1-D array by adding integer values to *(arr + i).


 For example *(arr + i) + 1 will represent the address of
1  element of 1stelement of ith 1-D array and *(arr+i)+2 will represent the
st

address of 2nd element of ith 1-D array.


 Similarly *(arr + i) + j will represent the address of j th element of
ith 1-D array. On dereferencing this expression we can get the
jth element of the ith 1-D array.

// C program to print the values and 


// address of elements of a 2-D array
#include<stdio.h>
  
int main()
{
  int arr[3][4] = {
                    { 10, 11, 12, 13 },
                    { 20, 21, 22, 23 },
                    { 30, 31, 32, 33 }
                  };
  int i, j;
  for (i = 0; i < 3; i++)
  {
    printf("Address of %dth array = %p %p\n", 
                    i, arr[i], *(arr + i));
      
    for (j = 0; j < 4; j++)
      printf("%d %d ", arr[i][j], *(*(arr + i) + j));
    printf("\n");
  }
  
  return 0;
}
Output:
Address of 0th array = 0x7ffe50edd580 0x7ffe50edd580
10 10 11 11 12 12 13 13
Address of 1th array = 0x7ffe50edd590 0x7ffe50edd590
20 20 21 21 22 22 23 23
Address of 2th array = 0x7ffe50edd5a0 0x7ffe50edd5a0
30 30 31 31 32 32 33 33

Pointers and Three Dimensional Arrays


In a three dimensional array we can access each element by using three
subscripts. Let us take a 3-D array-
int arr[2][3][2] = { {{5, 10}, {6, 11}, {7, 12}}, {{20, 30},
{21, 31}, {22, 32}} };
We can consider a three dimensional array to be an array of 2-D array i.e
each element of a 3-D array is considered to be a 2-D array. The 3-D
array arr can be considered as an array consisting of two elements where
each element is a 2-D array. The name of the array arr is a pointer to the
0th 2-D array.
Thus the pointer expression *(*(*(arr + i ) + j ) + k) is equivalent to the
subscript expression arr[i][j][k].

We know the expression *(arr + i) is equivalent to arr[i] and the


expression *(*(arr + i) + j) is equivalent arr[i][j]. So we can say that arr[i]
represents the base address of i th 2-D array and arr[i][j] represents the
base address of the jth 1-D array.

// C program to print the elements of 3-D


// array using pointer notation
#include<stdio.h>
int main()
{
  int arr[2][3][2] = {
                       {
                         {5, 10},
                         {6, 11},
                         {7, 12},
                       },
                       {
                         {20, 30},
                         {21, 31},
                         {22, 32},
                       }
                     };
  int i, j, k;
  for (i = 0; i < 2; i++)
  {
    for (j = 0; j < 3; j++)
    {
       for (k = 0; k < 2; k++)
         printf("%d\t", *(*(*(arr + i) + j) +k));
       printf("\n");
    }
  }
  
  return 0;
}
Output:
5 10
6 11
7 12
20 30
21 31
22 32
The following figure shows how the 3-D array used in the above program is
stored in memory.

Subscripting Pointer to an Array


Suppose arr is a 2-D array with 3 rows and 4 columns and ptr is a pointer to
an array of 4 integers, and ptr contains the base address of array arr.
int arr[3][4] = {{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}};
int (*ptr)[4];
ptr = arr;
Since ptr is a pointer to an array of 4 integers, ptr + i will point to ith row. On
dereferencing ptr + i, we get base address of i th row. To access the address of
jth element of ith row we can add j to the pointer expression *(ptr + i). So the
pointer expression *(ptr + i) + j gives the address of jth element of ith row and
the pointer expression *(*(ptr + i)+j) gives the value of the j th element of
ith row.
We know that the pointer expression *(*(ptr + i) + j) is equivalent to subscript
expression ptr[i][j]. So if we have a pointer variable containing the base
address of 2-D array, then we can access the elements of array by double
subscripting that pointer variable.

// C program to print elements of a 2-D array 

// by scripting a pointer to an array 

#include<stdio.h>

  

int main()

  int arr[3][4] = { 

                    {10, 11, 12, 13}, 

                    {20, 21, 22, 23}, 

                    {30, 31, 32, 33} 


                  };

  int (*ptr)[4];

  ptr = arr;

  printf("%p %p %p\n", ptr, ptr + 1, ptr + 2);

  printf("%p %p %p\n", *ptr, *(ptr + 1), *(ptr + 2));

  printf("%d %d %d\n", **ptr, *(*(ptr + 1) + 2), *(*(ptr + 2) + 3));

  printf("%d %d %d\n", ptr[0][0], ptr[1][2], ptr[2][3]);

  return 0;

Output:
0x7ffead967560 0x7ffead967570 0x7ffead967580
0x7ffead967560 0x7ffead967570 0x7ffead967580
10 22 33
10 22 33
Record Structures
A record structure is an aggregate entity containing one or more elements.
(Record elements are also called fields or components.) You can use records
when you need to declare and operate on multi-field data structures in your
programs.

Creating a record is a two-step process:

You must define the form of the record with a multistatement structure


declaration.

1. You must use a RECORD statement to declare the record as an entity


with a name. (More than one RECORD statement can refer to a given
structure.)

Examples
Intel Fortran record structures, using only intrinsic types, easily convert to
Fortran 95/90 derived types. The conversion can be as simple as replacing the
keyword STRUCTURE with TYPE and removing slash ( / ) marks. The
following shows an example conversion:

Record Structure

STRUCTURE /employee_name/
CHARACTER*25 last_name
CHARACTER*15 first_name
END STRUCTURE
STRUCTURE /employee_addr/
CHARACTER*20 street_name
INTEGER(2) street_number
INTEGER(2) apt_number
CHARACTER*20 city
CHARACTER*2 state
INTEGER(4) zip
END STRUCTURE
The record structures can be used as subordinate record variables within another
record, such as the employee_data record. The equivalent Fortran 90 derived
type would use the derived-type objects as components in a similar manner, as
shown below:

Record Structure

STRUCTURE /employee_data/
RECORD /employee_name/ name
RECORD /employee_addr/ addr
INTEGER(4) telephone
INTEGER(2) date_of_birth
INTEGER(2) date_of_hire
INTEGER(2) social_security(3)
LOGICAL(2) married
INTEGER(2) dependents
END STRUCTURE

C/C++ arrays allow you to define variables that combine several data items of
the same kind, but structure is another user defined data type which allows
you to combine data items of different kinds.
Structures are used to represent a record, suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book −

 Title
 Author
 Subject
 Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member, for your program. The
format of the struct statement is this −
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the structure's definition, before the final semicolon, you can specify
one or more structure variables but it is optional. Here is the way you would
declare the Book structure −
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.).
The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access. You would
use struct keyword to define variables of structure type. Following is the example to
explain usage of structure −
#include <iostream.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700

Structures as Function Arguments


You can pass a structure as a function argument in very similar way as you pass
any other variable or pointer. You would access structure variables in the similar
way as you have accessed in the above example −
#include <iostream.h>
#include <string.h>
void printBook( struct Books book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );

return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}

When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to
any other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the & operator before the
structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the -> operator as follows −
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you
to understand the concept −
#include <iostream.h>
#include <string.h>

using namespace std;


void printBook( struct Books *book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}

When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
Record - a linear, direct-access data structure with heterogeneous components.
See taxonomy.

Field or member - component of the record; each field has its own type

FieldName - the identifier used to refer to the field. The identifier only need to be
unique within the struct.  It will not be in conflict with names  used elsewhere or in
other structs.

Records have been implemented as classes in C++.

Example:
Student (idnumber, name, status, credits, gpa)
enum StatusType {FULLTIME, PARTTIME, NONDEGREE, GRAD}

struct StudentType {
   int idNumber;
   char name[30];
   StatusType status;
   float credits;
   float gpa;
};

StudentType student1;
StudentType student2;

Dot operator
The dot (.) operator is used to select members from a record (struct).

So that student1.idNumber accesses the member idNumber from the


object student1.

student2.name refers to the name of object student2.


if(student1.status == FULLTIME) 

Variations on the struct statement:


1. Combined struct and instance declarations
struct StudentType {
....
}student1,student2; //not recommended
 

2. Unnamed struct types

struct {
.....
} student1, student2; //no way to later make a new instance

Features about structs


Structs can be assigned as as aggregate

This is an important feature. Compare to the fact that you cannot assign whole
arrays or strings by themselves. You must copy an array element by element, a
string using the strcpy( ) function. 

student1 = student2; //OK

Arrays cannot be assigned as an aggregate 

student1.name = student2.name; //NOT OK  

Structs can be passed as parameters either by value or by reference

Fieldname Issues
The fieldnames are local to the struct.
The same member name can be used in other structs.

Every member name reference is always associated with the record or instance
name.

struct type1{ struct type2{


    int a;     int a;
    int b;     float b;
}; };
type1 x,y; type2 b,a;
Note the various references to identifier "a" and "b" x.a y.a a.a a.b int a  

Membership
Any structure can be a member of a struct

struct NameType {
   char first[15];
   char middleInit;
   char last[15];
};
struct StudentType {
   NameType name;
   int      idNum;
   float    credits;
   float    gpa;
};
StudentType student1,student2;
student1.name.last;
student2.name.first[0];

Type compatibility
Two struct instances are compatible only if their types are identical or are
renamings of the same type.

struct TypeA{  struct TypeA{  typedef int Counter; 


   int a,b;     int a,b;  Counter i,j,k; 
};  };  int n; 
struct TypeB { 
   int a,b;  typedef TypeA TypeB;  i = n; //OK
}; 
r = s; //OK
TypeA r; 
TypeB s; 
r = s; //NOT OK

You might also like