0% found this document useful (0 votes)
22 views15 pages

C Arrays: Structure and Operations Guide

Uploaded by

jayanth sdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views15 pages

C Arrays: Structure and Operations Guide

Uploaded by

jayanth sdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

CHAPTER 2
ARRAYS
Array
Array is collection of homogeneous elements
Or
Collection of elements of same data type.
Or
Array is non-primitive linear Data Structure

 Its elements are stored in a contiguous memory location.


 The size of array should be mentioned while declaring it.
 Array index always starts from Zero (0).
 Array elements can be accessed using the position of the element in the array.
 Array can have one or more dimensions.
Example
<---------- Length 5------------->
10 20 30 40 50
<------ Array Indices
0 1 2 3 4
Here, Array Length is 5
First Index is 0
Last index is 4

Array Declaration
Array declaration means, the process of allocating memory to the array.
To declare an array, define the data type (like int) and specify the name of the array followed by square
brackets [], within square bracket mention the size of the array;
Syntax: data_type array_name[size];
Example: int arr[10]; or double arr[10]; or char ch[20];

Array Initialization
Initialization means assigning elements to array.
There are many ways to declare array

Way 1: Declaration Time


We can initialize the c array at the time of declaration by using { } brackets and each element separated by
comma ( , )
Example
int marks[5]={20,30,40,50,60}; // Declaration and initialization

Way 2: Using index


The simplest way to initialize an array is by using the index of each element. We can initialize each element of
the array by using the index.
Example. int marks[3]; // Declaration of an array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
Way 3: Array Initialization Using a Loop
An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the
array starting from 0. The following syntax uses a “for loop” to initialize the array elements.

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |1


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

Example: int arr[5]; // Declration


for(int i=0; i<5; i++)
{
arr[i]=i+10;// Initialization
}
Types of Array
1. Single Dimension Array
2. Multi-Dimensional Array

1. Single Dimension Array


 Single dimensional arrays used to store list of values of same datatype in linear form.
 Single dimensional arrays also called as one-Dimensional arrays, Scalar array, Linear Arrays or
simply 1-D Arrays.
 It contains only one subscript (row value).

Declaration of Single Dimensional Array


We use the following general syntax for declaring a single dimensional array
Syntax: datatype arrayName [ size ];
Example: int rollNumbers [60];

Initialization of Single Dimensional Array


Initialization con be done at two time
 Compile Time initialization
 Run-Time Initialization

Compile Time initialization: Initialization of array takes place at the time of compiling the program.
Syntax : datatype arrayName [ size ] = {value1, value2, ...value n} ;
Example : int marks [6] = { 89, 90, 76, 78, 98, 86 } ;

Run - Time initialization: Memory allocation and initialization takes place at runtime.
Syntax : datatype *arrayName;
arranName=(data_type)malloc(sizeof(data_type)*n);
arr[0]=value 1;
arr[2]=value 2;
Example : int *arr;
arre=(int)malloc(sizeof(int)*5);
arr[0]=10;
arr[0]=20;

2. Multi-Dimensional Array
 A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular
form. Data in multidimensional arrays are stored in row-column.
 If row size is 2 and column size is 2 it is termed as Two-Dimensional array.
 If row size is 3 and column size is 3 it is termed as Three-Dimensional array.

Declaration of Multi-Dimensional Array


We use the following general syntax for declaring a multi-dimensional array
Syntax: datatype arrayName [ row_size ][ column_size ];
Example: int matrix[2][2];
0,0 0,1
[ ]
1,0 1,1
Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |2
Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

Abstract Data Types


An abstract data type (ADT) separates the interface of a data type from its implementation, and it encompasses
both the data itself as well as functionality on the data.

ADT is combination of data + Operation


Example: Array as abstract data type, Stack as abstract type, structure as abstract data type.

Operations on array
1. Creating
2. Traversing
3. Inserting
4. Deleting
5. Sorting
6. Searching

1. Create
Process of creating environment to store element
Or
It is a process allocating memory to store array elements.
Example: int arr[20];

2. Traverse
Process of visiting each element in the array.
Example: int a [5] = {10, 20, 30, 40, 50};
for(i=0; i<5; i++)
{
printf(“%d ”,a[i]);// Prints all the elements of the array
}
3. Insert
It is the process of adding element to an array based on the position.
Example:

Program
void main()
{
int arr[20] = {1, 2, 3, 4, 5, 6, 7 ,8, 9, 10};
int i, x, pos, n = 10;
clrscr();
// print the original array
for (i = 0; i < n; i++)
printf("%d ", arr[i]);

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |3


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

printf("\n");

// element to be inserted
x = 50;

// position at which element is to be inserted


pos = 5;

// increase the size by 1


n++;

// shift elements forward


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

// insert x at pos
arr[pos - 1] = x;

// print the updated array


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

getch();
}

4. Delete
Process of removing an element from the array, based on position.
Example:

//Program to implement Delete operation from the array


#include<stdio.h>
#include<conio.h>
void main()
{
int arr[20] = {1, 2, 3, 4, 5, 6, 7 ,8, 9, 10};
int i, pos, n = 10;
clrscr();
// print the original array
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

// element to be removed from the index 2


Pos=2;
// shift elements backward
for (i = pos - 1; i<n; i++)
arr[i] = arr[i +1];

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |4


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

// decrease the size by 1


n--;

// print the updated array


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

getch();
}

5. Sorting
Sorting is the process of arranging the element either ascending or descending order.
Types of sorting technique are
1. Selection Sort
2. Bubble Sort
3. Insertion Sort
4. Quick Sort

1. Selection Sort
 The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering
ascending order) from unsorted part and putting it at the beginning.
 The algorithm maintains two subarrays in a given array.
 The left sub array, which is sorted.
 The right sub array, which is unsorted.

Algorithm
begin selectionSort(list)
for i = 0 to sizeof(list) - 1

minIndex = i;

for j = i + 1 to sizeof(list)

if list[j] < list[mid_index] then


minIndex = j;
end if

swap(list[minIndex], list[i])

end for

end for
end selectionSort

//Program to implement Selection Sort


#include<stdio.h>
#include<conio.h>
int *arr, i, j, n;// Global Declaration

//Functions Declaration in global section


void allocateMemory()
{
arr=(int*)calloc(n,sizeof(int));
}

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |5


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

void readArray()
{
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d",&arr[i]);
}
void displayArray()
{
printf("Array elements are\n");
for(i=0; i<n; i++)
printf("%d ",arr[i]);
printf("\n");
}
//Selection sort function
void selectionSort()
{
int min;
for(i=0; i<n-1; i++)
{
min=i;
for(j=i+1; j<n; j++)
{
if(arr[j]<arr[min])
min=j;
}
if(i!=min)
{
swap(&arr[min],&arr[i]);
}
}
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void main()
{
clrscr();
printf("Enter the size of the array\n");
scanf("%d",&n);

//Dynamic allocation of memory


allocateMemory();

//to check whether memory is allocated or not


if(arr==NULL)
{
printf("Error in memory allocation\n");
}

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |6


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

else
{
readArray(); // Function Call
printf("Before sorting ");
displayArray();
selectionSort();// Call Selection sort function
printf("After sorting ");
displayArray();
}
getch();
}

2. Bubble Sort
 Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in
the intended order.
 In this algorithm, the highest element is sorted first.
 The left sub array, which is unsorted.
 The right sub array, which is sorted.

Algorithm
bubbleSort(array)
for i <- 1 to indexOfLastUnsortedElement-1
for j <- 1 to indexOfLastUnsortedElement-i-1
if array[j] > array[j+1] then
swap (a[j] ,a[j+1])
end if
end for
end for
end bubbleSort

Program
void bubbleSort()
{
for(i=0; i<n-1; i++)
{
for(j=0; j<n-i-1; j++)
{
if(arr[j]> arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
}

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |7


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

3. Insertion Sort
 Insertion Sort is a sorting algorithm where the array is sorted by taking one element at a time.
 The principle behind insertion sort is to take one element, iterate through the sorted array & find its correct
position in the sorted array.
 Once position is found insert the element to its position

Algorithm

begin insertionSort(array)
int key=0;
for i = 1 to sizeof(list)-1
key=a[i];
j=i-1;
while(j>=0 && a[j]>key)
array[j+1]=array[j];
j--;
end while
array[j+1]=key;
end for
end insertionSort

Program

void insertionSort()
{
key=0;
for(i=1; i<n-1; i++)
{
key=a[i];
j=i-1;
while(j>=0 && a[j]>key)
{
a[j+1]=a[j];
j--;
}
a[j+1]=key;
}
}

4. Quick Sort
 Quick sort works based on divide and conquer technique, that means, we divide a problem into sub-
problems and then solve them accordingly.
 This sorting algorithm includes selecting a pivot point and finding its appropriate place in the array by
putting elements smaller to it on its left side, and the elements greater than it to its right side.
 We then create a partition around this correct position of pivot.
 This process of creating a partition is the backbone of the Quick Sort algorithm.

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |8


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

Algorithm
Step 1: Start quickSort (arr, low, high)
Step 2: consider first element as pivot
Step 3: initialize i to low index j to high index
Step 4: Repeat the following steps while i<j
Keep on incrementing i while arr[j] <=pivot
end while
Keep on decrementing j while arr[j]>pivot
end while
if i<j then
Swap(arr[i],a[j])
end if
end while
Step 5: if i>j then
Swap (arr[j],pivot)
end if
Step 6: end

Program
#include <stdio.h>
#include <conio.h>

int array[100];
int i,j,n;

int partition(int low, int high)


{
int pivot = array[low];
int i = low, j= high, temp;

while (i < j)
{
while (array[i] <= pivot)
{
i++;
}
while (array[j] > pivot)
{
j--;
}
//swapping
if (i < j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}

}
array[low] = array[j];
array[j] = pivot;
return j;
}

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru Page |9


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

void quickSort(int low, int high)


{
int pi;
if (low < high)
{
pi = partition(low, high);
quickSort(low, pi - 1);
quickSort(pi + 1, high);
}
}
void readArray()
{
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d",&array[i]);
}
void printArray()
{
for (i = 0; i < n; ++i)
printf("%d ", array[i]);
printf("\n");
}
void main()
{
clrscr();
printf("Enter the size of the array\n");
scanf("%d",&n);

readArray();
printf("Unsorted Array\n");
printArray();

quickSort(0, n - 1);

printf("Sorted array in ascending order: \n");


printArray();
getch();
}

6. Searching
 Searching is the process of finding the location of the given element from the array.
 Once the element found it returns the position of the element.

Most popular searching technique are


 Linear search
 Binary search

1. Linear search
 Linear search is also called as sequential search algorithm.
 In Linear search, we simply traverse the list completely and match each element of the list with the
item whose location is to be found.
 If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL.

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 10


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

Algorithm
Step 1:Begin linearSearch(arr,n,element)
Step 2:set pos = -1
for i=0 to n
if arr[i]==element then
return i+1
else
return -1;

end if
end for
Step 3:end linearSearch

Program on linear search


#include <stdio.h>
#include <conio.h>
int linearSearch(int a[], int n, int element)
{
int i;
for (i = 0; i < n; i++)
{
if (a[i] == element)
return i+1;
}
return -1;
}
void main()
{
int a[100]; // given array
int element, result, n, i; // size of array
clrscr();
printf("Enter the size of the array\n");
scanf("%d",&n);

printf("Enter the array elements\n");


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

printf("The elements of the array are \n");


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

printf("Enter the element to be searched\n");


scanf("%d",&element);

result = linearSearch(a, n, element);


if (result == -1)
printf("\nElement is not present in the array\n");
else
printf("\nElement is present at %d position of array\n", result);
getch();

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 11


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

}
2. Binary Search
 Binary search follows the divide and conquer approach.
 In which the list is divided into two halves, and the item is compared with the middle element of the list.
 If the match is found then, the location of the middle element is returned. Otherwise, we search into either
of the halves depending upon the result produced through the match.

There are two methods to implement the binary search algorithm -


 Recursive Binary Search
 Iterative Binary Search

1. Iterative Binary Search


 In this method, binary search is carried based on the mid value and the key element.
 If the element is less than the middle element lower bound remains as it is, only upper bound value is
changed to mid-1.
 If the element is greater than the middle element upper bound remains as it is, only lower bound value
is changed to mid+1.

Algorithm iterative binary search


Binary_Search(a, lower_bound, upper_bound, val) //
Step 1: Start
Step 2: set beg = lower_bound, end = upper_bound, pos = - 1
Step 3: repeat steps 3 and 4 while beg <=end
Step 4: set mid = (beg + end)/2
Step 5: if a[mid] = val
set pos = mid
print pos
go to step 7
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
end of if
end of While
Step 6: if pos = -1
print "value is not present in the array"
end of if
Step 7: Stop

Program Iterative Binary Search


#include <stdio.h>
#include <conio.h>

int arr[20],element, position, n,i;

int binarySearch(int low, int high, int element)


{
int mid;
while(high >= low)
{
mid = (low + high)/2;

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 12


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

if( element == arr[mid])


return mid+1;
else if(element < arr[mid])
high=mid-1;
else if(element>arr[mid])
low=mid+1;
}
return -1;
}
void main()
{
clrscr();
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0; i<n; i++)
scanf("%d",&arr[i]);

printf("The elements of the array are\n");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

printf("Enter the element to be searched\n");


scanf("%d",&element);
printf("\nElement to be searched is - %d", element);

position= binarySearch(0, n-1,element);

if (position == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", position);
getch();
}
Recursive Binary Search
 In this method, binary search is carried based on the mid value and the key element.
 If the element is less than the middle element call binarySearch(low, mid-1)
 If the element is greater than the middle call binarySearch(mid+1, high)

Algorithm Recursive binary search


binarySearch(a, low, high, val) //
Step 1: Start
Step 2: calculate mid value mid= (low+high)/2
Step 3: if a[mid]==val
return mid+1
else if val<a[mid]
return binarySearch(a, low, mid-1)
else if val>a[mid]
retuen binarySearch(a,mid+1,high)
else
return -1
end of if

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 13


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

Step 4: if pos==-1
print “value not found”
else
print “Value found at position pos”

Program Recursive Binary Search


int binarySearch(int low, int high, int element)
{
int mid;
if(high >= low)
{
mid = (low + high)/2;

if( element == arr[mid])


return mid+1;
else if(element < arr[mid])
return binarySearch(low,mid-1);
else if(element > arr[mid])
return binarySearch(mid+1, high);
}
return -1;
}

Sparse Matrix
Sparse matrices are those matrices that have the majority of their elements equal to zero. In other words, the
sparse matrix can be defined as the matrix that has a greater number of zero elements than the non-zero
elements.
Example:

Program construction of sparse matrix


#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,compact_Matrix[3][size], k=0;
// Sparse matrix having size 4*5
int sparse_matrix[4][5] =
{
{0 , 0 , 6 , 0 , 9 },
{0 , 0 , 4 , 6 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 1 , 2 , 0 , 0 }
};
// size of matrix
int size = 0;
clrscr();

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 14


Data Structure Using C, BCA 2nd SEM 2022-23 Chapter 2 : Arrays

for(int i=0; i<4; i++)


{
for(int j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
size++;
}
}
}
// Defining final matrix

// Computing final matrix


for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
{
if(sparse_matrix[i][j]!=0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparse_matrix[i][j];
k++;
}
}
}
// Displaying the final matrix
for(i=0 ;i<3; i++)
{
for(j=0; j<size; j++)
{
printf("%d ", compactMatrix[i][j]);
}
printf("\n");
}
getch();
}

Rajesh R.M. Dept. of Computer Science, Seshadripuram College, Tumakuru P a g e | 15

You might also like