0% found this document useful (0 votes)
1 views

Arrays

The document provides a comprehensive overview of arrays, including their definitions, types, and operations. It covers one-dimensional and two-dimensional arrays, their declaration, initialization, and various operations like searching, sorting, and matrix addition. Additionally, it discusses the advantages and disadvantages of arrays, as well as their applications in data structures.

Uploaded by

adityavarpe69
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Arrays

The document provides a comprehensive overview of arrays, including their definitions, types, and operations. It covers one-dimensional and two-dimensional arrays, their declaration, initialization, and various operations like searching, sorting, and matrix addition. Additionally, it discusses the advantages and disadvantages of arrays, as well as their applications in data structures.

Uploaded by

adityavarpe69
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Unit IV

Arrays
-by
Ujwala Wanaskar
Contents:
• Arrays: One Dimensional Arrays, Declaration of One-dimensional
Arrays, Initialization of One- dimensional Arrays, Two –dimensional
Arrays, Initialization of Two- dimensional Arrays.

• Character Arrays and Strings: Declaration and Initialization String


Variables, Reading Strings from Terminal, Writing Strings to Screen,
Putting Strings Together, Comparison of Two Strings, Introduction to
String handling Functions
Arrays:
• Definition:
• An array is a linear data structure that collects elements of the same
data type and stores them in contiguous and adjacent memory
locations.
Basic terminologies of Array
• Array Index: In an array, elements are identified by their indexes.
Array index starts from 0.

• Array element: Elements are items stored in an array and can be


accessed by their index.

• Array Length: The length of an array is determined by the number of


elements it can contain.
Memory representation of Array
• In an array, all the elements are stored in contiguous memory
locations. So, if we initialize an array, the elements will be allocated
sequentially in memory. This allows for efficient access and
manipulation of elements.
Declaration of Array
• Arrays can be declared in various ways in different languages.
• Syntax: datatype array_name[size];
• // This array will store integer type element
• int arr[5];

• // This array will store char type element


• char arr[10];

• // This array will store float type element


• float arr[20];
Initialization of Array
• int arr[] = { 1, 2, 3, 4, 5 }; • arr[0]=1;
arr[2]=2;
• char arr[5] = { 'a', 'b', 'c', 'd', 'e' }; arr[3]=3;
arr[4]=4;
• float arr[10] = { 1.4, 2.0, 24, 5.0, arr[5]=5;
0.0 };
• OR
For(i=0;i<=n-1;i++)
Scanf(“%d”,&arr[i]);
Importance of Array
• Assume there is a class of five students and if we have to keep
records of their marks in examination then, we can do this by
declaring five variables individual and keeping track of records but
what if the number of students becomes very large, it would be
challenging to manipulate and maintain the data.
• What it means is that, we can use normal variables (v1, v2, v3, ..)
when we have a small number of objects. But if we want to store a
large number of instances, it becomes difficult to manage them with
normal variables. The idea of an array is to represent many instances
in one variable.
Need or Applications of Array Data Structures
• Array is a fundamental data structure and many other data structure
are implemented using this. Implementing data structures such as
stacks and queues
• Representing data in tables and matrices
• Creating dynamic data structures such as Hash Tables and Graph.
• When compared to other data structures, arrays have the advantages
like random access (we can quickly access i-th item) and all items are
stored at contiguous location
Types of Arrays
• Arrays can be classified in two ways:
• On the basis of Size
• On the basis of Dimensions
Types of Arrays on the basis of Size:
• 1. Fixed Sized Arrays:
• We cannot alter or update the size of this array. Here only a fixed size
(i.e.. the size that is mentioned in square brackets []) of memory will
be allocated for storage.
• In case, we don’t know the size of the array then if we declare a larger
size and store a lesser number of elements will result in a wastage of
memory or we declare a lesser size than the number of elements
then we won’t get enough memory to store all the elements.
• In such cases, static memory allocation is not preferred.
Declaration of array:
• // Method 1 to create a fixed sized array.
• // Here the memory is allocated at compile time.
• int arr1[5];
• // Another way (creation and initialization both)
• int arr2[5] = {1, 2, 3, 4, 5};
2. Dynamic Sized Arrays:
• The size of the array changes as per user requirements during
execution of code so the coders do not have to worry about sizes.
• They can add and removed the elements as per the need.
• The memory is mostly dynamically allocated and de-allocated in these
arrays.

• // C does not seem to support dynamic sized arrays


Types of Arrays on the basis of Dimensions:
• 1. One-dimensional Array(1-D Array): You can imagine a 1d array as a
row, where elements are stored one after another.
2. Multi-dimensional Array:
• A multi-dimensional array is an array with more than one dimension.
We can use multidimensional array to store complex data in the form
of tables, etc. We can have 2-D arrays, 3-D arrays, 4-D arrays and so
on.
• Two-Dimensional Array(2-D Array or Matrix): 2-D Multidimensional
arrays can be considered as an array of arrays or as a matrix consisting
of rows and columns.
Three-Dimensional Array(3-D Array):
• A 3-D Multidimensional array contains three dimensions, so it can be
considered an array of two-dimensional arrays.
Operations on Array

• Reading the elements in an array


• Displaying the elements in an array/array traversing
• Searching in Array:
• Finding min and max element
• Finding sum and average of elements in an array
• Finding frequency of an element in an array
Reading the elements in an array

Int arr[10], n, i;
//read the number of elements in array as n

For(i=0;i<=n-1;i++)
{
Printf(“Enter array element:”);
Scanf(“%d”,&arr[i]);
}
Display Array Elements or Array Traversal:
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr)
// Traversing over arr[]
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
Searching in Array:
Int arr[10],n,I,ele,flag=0;
//read the number of elemets in array as n
//read the elemets to be stored in an array
Printf(“Enter the element to be searched in an array”);
Scanf(“%d”,&ele);
For(i=0;i<=n-1;i++)
{
if(a[i]==ele)
{
printf(“Element is found at %d position”,i+1);
flag=1;
}
}
If(flag==0)
Printf(‘Element is not found in an array”);
Finding min and max element
int arr[10],n, min,max;
//read the number of elements in array as n
//read the elements in an array
Min=max=a[0];
For(i=1;i<=n-1;i++)
{
if(a[i]<min)
min=a[i];
if(a[i]>max
max=a[i];
}
Printf(“Max elements=%d”,max);
Printf(“Min elements=%d”,min);
Finding sum and average of elements in an array
int arr[10],n, sum=0,avg;
//read the number of elements in array as n
//read the elements in an array
For(i=0;i<=n-1;i++)
{
sum=sum+a[i];
}
Avg=sum/n;
Printf(“Average of array elements=%d”,avg);
Finding frequency of an element in an array
int arr[10],n, ele,count=0;
//read the number of elements in array as n
//read the elements in an array
Printf(‘Enter the element to count the frequency”);
Scanf(“%d”,&ele);
For(i=0;i<=n-1;i++)
{
if(a[i]==ele)
count++;
}
If(count==0)
printf(“Elelment is not present”);
Else
printf(“Element is present %d times in array”,count);
Sorting array element in ascending order(Selection Sort)
int arr[10],n, i,j;
//read the number of elements in array as n
//read the elements in an array
for (i = 0; i < n; ++i)
{

for (j = i + 1; j < n; ++j)


{

if (number[i] > number[j])


{

a = number[i];
number[i] = number[j];
number[j] = a;

}
Inserting an element in an array
• Insert the element at the end.
Deleting an element from an array
• Delete the last element in an array
Advantages of Array
• Arrays allow random access to elements. This makes
accessing elements by position faster.
• Arrays represent multiple data items of the same
type using a single name.
• Arrays are used to implement the other data
structures like linked lists, stacks, queues, trees,
graphs, etc.
Disadvantages of Array
• As arrays have a fixed size, once the memory is allocated to
them, it cannot be increased or decreased, making it impossible
to store extra data if required. An array of fixed size is referred to
as a static array.
• Allocating less memory than required to an array leads to loss of
data.
• An array is homogeneous in nature so, a single array cannot
store values of different data types.
• Arrays store data in contiguous memory locations, which makes
deletion and insertion very difficult to implement. This problem
is overcome by implementing linked lists, which allow elements
to be accessed sequentially.
Applications of Array
• Storing and accessing data: Arrays store elements in a
specific order and allow constant-time O(1) access to any
element.
• Searching: If data in array is sorted, we can search an item in
O(log n) time. We can also find floor(), ceiling(), kth smallest,
kth largest, etc. efficiently.
• Matrices: Two-dimensional arrays are used for matrices in
computations like graph algorithms and image processing.
• Implementing other data structures: Arrays are used as the
underlying data structure for implementing stacks and
queues.
2-D Arrays:
• Declaration of 2D array:

• Datatype arrayName[row][columns];

• Ex. int arr[4][5];

• Arrays are 0-indexed, so the row number ranges from 0 to (m-1) and
the column number ranges from 0 to (n-1).
2-D array initialization:
• int arr[2][3]={1,2,3,4,5,6};
• or
• int arr[2][3] = { {1, 4, 2}, {3, 6, 8} };
• The first dimension represents the number of rows [0], while the
second dimension represents the number of columns [1]. The values
are placed in row-order, and can be visualized like this:
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.
• This statement accesses the value of the element in the first row
(0) and third column (2) of the matrix array.

• Example
• int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2


2D Array Traversal
// C Program to illustrate the 2D array
#include <stdio.h>
int main() {
// Create and initialize an array with 3 rows
// and 2 columns
int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
// Print each array element's value
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
}
printf("\n");
}
return 0;
}
Output
arr[0][0]: 0 arr[0][1]: 1
arr[1][0]: 2 arr[1][1]: 3
arr[2][0]: 4 arr[2][1]: 5
2D array example: Storing elements in a matrix and printing
it.
#include <stdio.h> • O/P:
void main () • Enter a[0][0]: 56
{
int arr[3][3],i,j; • Enter a[0][1]: 10
for (i=0;i<3;i++) • Enter a[0][2]: 30
{
for (j=0;j<3;j++) • Enter a[1][0]: 34
{ • Enter a[1][1]: 21
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]); • Enter a[1][2]: 34
} • Enter a[2][0]: 45
}
printf("\n printing the elements ....\n"); • Enter a[2][1]: 56
for(i=0;i<3;i++) • Enter a[2][2]: 78
{
printf("\n");
for (j=0;j<3;j++) • printing the elements ....
{
printf("%d\t",arr[i][j]);
} • 56 10 30
}
}
• 34 21 34
• 45 56 78
Adding two matrices:
#include <stdio.h> // adding two matrices
int main() { for (i = 0; i < r; ++i)
int r, c, a[100][100], b[100][100], sum[100][100], i, j; for (j = 0; j < c; ++j) {
printf("Enter the number of rows (between 1 and 100): "); sum[i][j] = a[i][j] + b[i][j];
scanf("%d", &r); }
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c); // printing the result
printf("\nSum of two matrices: \n");
printf("\nEnter elements of 1st matrix:\n"); for (i = 0; i < r; ++i)
for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) {
for (j = 0; j < c; ++j) { printf("%d ", sum[i][j]);
printf("Enter element a%d%d: ", i + 1, j + 1); if (j == c - 1) {
scanf("%d", &a[i][j]); printf("\n\n");
} }
}
printf("Enter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i) return 0;
for (j = 0; j < c; ++j) { }
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]); //can add the condition to check rows and
} column of both matrices are equal.
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

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

Matrix Multiplication
#include<stdio.h>
for(i=0;i<r;i++)
{
#include<stdlib.h> for(j=0;j<c;j++)
int main(){
{
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls"); mul[i][j]=0;
printf("enter the number of row="); for(k=0;k<c;k++)
scanf("%d",&r);
{
printf("enter the number of column=");
scanf("%d",&c);
mul[i][j]+=a[i][k]*b[k][j];
printf("enter the first matrix element=\n"); }
for(i=0;i<r;i++)
}
{
}
for(j=0;j<c;j++)
{ //for printing result
scanf("%d",&a[i][j]); for(i=0;i<r;i++)
}
{
}
printf("enter the second matrix element=\n"); for(j=0;j<c;j++)
for(i=0;i<r;i++) {
{
printf("%d\t",mul[i][j]);
for(j=0;j<c;j++)
{ }
scanf("%d",&b[i][j]); printf("\n");
}
}
}
return 0;
}
• enter the number of row=3
• enter the number of column=3
• enter the first matrix element=
• 111
• 222
• 333
• enter the second matrix element=
• 111
• 222
• 333
• multiply of the matrix=
• 666
• 12 12 12
• 18 18 18
Matrix Transpose: // computing the transpose
#include <stdio.h>
for (int i = 0; i < r; ++i)
int main() {
int a[10][10], transpose[10][10], r, c; for (int j = 0; j < c; ++j) {
printf("Enter rows and columns: "); transpose[j][i] = a[i][j];
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
}
printf("\nEnter matrix elements:\n"); // printing the transpose
for (int i = 0; i < r; ++i)
printf("\nTranspose of the matrix:\n");
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1); for (int i = 0; i < c; ++i)
scanf("%d", &a[i][j]); for (int j = 0; j < r; ++j) {
}
// printing the matrix a[][]
printf("%d ", transpose[i][j]);
printf("\nEntered matrix: \n"); // if (j == r - 1)
for (int i = 0; i < r; ++i)
printf("\n");
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]); }
if (j == c - 1) return 0;
printf("\n");
}
}
Output
Enter rows and columns: 2
3

Enter matrix elements:


Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1 4 0
-5 2 7

Transpose of the matrix:


1 -5
4 2
0 7
Sum of diagonal elements in a matrix
• //check for column and row i.e. i and j values, if they are equal
element is a diagonal element.

You might also like