[T-4]
Introduction: Basic Terminology, Elementary Data Organization
• A good program is defined as a program that runs correctly, easy to read and understand, easy to debug and easy
to modify.
• A program is said to be efficient when it executes in minimum time and with minimum memory space.
• In order to write efficient programs, we need to apply certain data management concepts.
• Data structure is a crucial part of data management.
• A data structure is basically a group of data elements that are put together under one name, and which defines a
particular way of storing and organizing data in a computer so that it can be used efficiently.
• Data: Data are simply values or sets of values.
• Data items: Data items refers to a single unit of values. Data items that are divided into sub-items are called
Group items. Ex: An Employee Name may be divided into three subitems- first name, middle name, and last
name.
• Data items that are not able to divide into sub-items are called Elementary items. Ex: SSN
• Entity: An entity is something that has certain attributes or properties which may be assigned values. The values
may be either numeric or non-numeric. Ex: Attributes- Names, Age, Sex, SSN Values- Rohland Gail, 34, F, 134-
34-5533 Entities with similar attributes form an entity set. Each attribute of an entity set has a range of values, the
set of all possible values that could be assigned to the particular attribute.
• The term “information” is sometimes used for data with given attributes, of, in other words meaningful or
processed data.
• Field is a single elementary unit of information representing an attribute of an entity.
• Record is the collection of field values of a given entity.
• File is the collection of records of the entities in a given entity set.
• Each record in a file may contain many field items but the value in a certain field may uniquely determine the
record in the file. Such a field K is called a primary key.
• Records may also be classified according to length. A file can have fixed-length records or variable-length records.
• In fixed-length records, all the records contain the same data items with the same amount of space assigned to
each data item.
• In variable-length records file records may contain different lengths. Example: Student records have variable lengths,
since different students take different numbers of courses. Variable-length records have a minimum and a maximum
length.
What do you mean by the term “Data Structure”?
• Organizing the data in memory.
• A data structure is a way of organizing the data so that it can be used efficiently. Here, we have used the word
efficiently, which in terms of both the space and time.
• It is a set of algorithms that we can use in any programming language to structure the data in the memory.
Classification of Data Structure:
• Linear data structure:
Data structure in which data elements are arranged sequentially or linearly, where each element is attached to its previous
and next adjacent elements, is called a linear data structure. Examples of linear data structures are array, stack, queue,
linked list, etc.
Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a static data
structure. An example of this data structure is an array.
Dynamic data structure: In dynamic data structure, the size is not fixed. It can be randomly updated during the runtime
which may be considered efficient concerning the memory (space) complexity of the code. Examples of this data
structure are queue, stack, etc.
• Non-linear data structure:
Data structures where data elements are not placed sequentially or linearly are called non-linear data structures. In a non-
linear data structure, we can’t traverse all the elements in a single run only. Examples of non-linear data structures are
trees and graphs.
• The major or the common operations that can be performed on the data structures are:
• Searching: We can search for any element in a data structure.
• Sorting: We can sort the elements of a data structure either in an ascending or descending order.
• Insertion: We can also insert the new element in a data structure.
• Updation: We can also update the element, i.e., we can replace the element with another element.
• Deletion: We can also perform the delete operation to remove the element from the data structure.
• Advantages of Data structures
The following are the advantages of a data structure:
• Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the program
very efficient in terms of time and space.
• Reusability: The data structure provides reusability means that multiple client programs can use the data
structure.
• Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot see
the internal working of the data structure, so it does not have to worry about the implementation part. The client
can only see the interface.
• An abstract data type (ADT) is the way we look at a data structure, focusing on what it does and ignoring how it
does its job. For example, stacks and queues are perfect examples of an ADT. We can implement both these ADTs
using an array or a linked list. This demonstrates the ‘abstract’ nature of stacks and queues. They are not concerned
about how they work.
[T-5]
Arrays: Definition, Declaration, Initialization & Processing of Single and Multidimensional Arrays
Array Data Structure
Definition
• An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the
same type together.
• They exist in both single dimension and multiple dimensions.
Basic terminologies of the 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.
Syntax
Creating an array in C language –Arrays are declared using the following syntax:
type name[size];
For example, if we write, int marks[10];
Types of arrays:
There are following types of arrays:
• One-dimensional array (1-D arrays): You can imagine a 1d array as a row, where elements are stored one after
another.
1D array
• Two-dimensional array: 2-D Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.
2D array
• Three-dimensional array: A 3-D Multidimensional array contains three dimensions, so it can be considered an
array of two-dimensional arrays.
3D array
Declaration, Initialization & Processing of Single and Multidimensional Arrays
One Dimensional Array
Declaration:
Syntax: data_type array_name[size];
data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:int age[100]; float sal[15]; char grade[20];
Here age is an integer type array, which can store 100 elements of integer type. The array sal is floating type array of
size 15, can hold float values. Grade is a character type array which holds 20 characters.
Initialization:
Syntax:
data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements one
after another.
Example: int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23,
marks[4]=4
Note-:
In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the compiler
assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here the size of array
marks is initialized to 5.
We can’t copy the elements of one array to another array by simply assigning it. Example:
int a[5]={9,8,7,6,5}; int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++) b[i]=a[i];
Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements present in the array
and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{ printf(“%d”,a[i]);
printf(“\n”);
}}
Two Dimensional Arrays-
Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come naturally
in the form of a table, e.g. spreadsheet, which need a two-dimensional array.
Declaration:
Syntax: data_type array_name[rowsize][columnsize];
Rowsize specifies the [Link] rows ,Columnsize specifies the [Link] columns.
Example: int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the array
is a[3][4] and total [Link] elements is 4*5=20.
Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example: int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
Note:
In 2-D arrays it is optional to specify the first dimension but the second dimension should always be present.
Example: int m[][3]={
{1,10},
{2,20,200},
{3}, {4,40,400} };
Here the first dimension is taken 4 since there are 4 rows in the initialization list. A 2-D array is known as matrix.
Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop indicates
the columns.
Example:
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
This program reads and displays 3 elements of integer type.
Declaration of Three-Dimensional Array:
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.
Representation of Arrays: Row Major Order, and Column Major Order
• When it comes to organizing and accessing elements in a multi-dimensional array, two prevalent methods
are Row Major Order and Column Major Order.
These approaches define how elements are stored in memory and impact the efficiency of data access in computing.
Row Major Order
Row major ordering assigns successive elements, moving across the rows and then down the next row, to successive
memory locations. In simple language, the elements of an array are stored in a Row-Wise fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.
How to find address using Row Major Order?
Q-Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory.
Find the address of arr[8][6] with the help of row-major order.
Solution:Given: Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of columns given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
Column Major Order
If elements of an array are stored in a column-major fashion means moving across the column and then to the next
column then it’s in column-major order.
To find the address of the element using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.
How to find address using Column Major Order?
Q-Given an array arr[1………10][1………15] with a base value of 100 and the size of each element is 1 Byte in
memory find the address of arr[8][6] with the help of column-major order.
Solution:Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
Operations supported by an array.
1. Traverse and display
Write a program to read and display n numbers using an array.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, arr[20];
clrscr();
printf("\n Enter the no of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5
2. Insertion
Write a program to insert a number at a given location in an array.
#include <stdio.h>
int main()
{
int i, n, num, pos, arr[10];
clrscr();
printf("\n Enter the no of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n Enter the number to be inserted : ");
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added : ");
scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
printf("\n The array after insertion of %d is : ", num);
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5
[Link]
Write a program to delete a number from a given location in an array.
#include <stdio.h>
int main()
{
int i, n, pos, arr[10];
clrscr();
printf("\n Enter the no of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\nEnter the position from which the number has to be deleted : ");
scanf("%d", &pos);
for(i=pos; i<n–1;i++)
arr[i] = arr[i+1];
n– –;
printf("\n The array after deletion is : ");
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the position from which the number has to be deleted : 3
The array after deletion is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 5
[Link] &Update
#include<stdio.h>
int main()
{ int i,t,a[10],n,m,s,j=0,b[10];
printf("\nEnter the Limit:");
scanf("%d",&n);
printf("\nEnter the Values:");
for(i=0i<n;i++)
{ scanf("%d",&a[i]);
}
printf("\nGiven values are:");
for(i=0;i<n;i++)
{ printf("a[%d]=%d",i,a[i]);
}
printf("\nEnter the position to be update:");
scanf("%d",&t);
printf("\nEnter the value to be update:");
scanf("%d",&s);
for(i=0;i<n;i++)
{
if(i==t)
{ a[i]=s;
}
}
printf("\nUpdated value is:");
for(i=0;i<n;i++)
{ printf("\na[%d]=%d",i,a[i]);
}
return 0;
}
Output
Enter the limit:5
Enter the values:1 2 3 4 5
Given values are:
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
Enter the position to be update:3
Enter the value to be update:5
Inserted value is:
a[0]=1
a[1]=2
a[2]=3
a[3]=5
a[4]=4
a[5]=5
Basic Operations on 2D array:
[Link] a program to transpose a 3 x 3 matrix.
#include <stdio.h>
int main()
{
int i, j, mat[3][3], transposed_mat[3][3];
clrscr();
printf("\n Enter the elements of the matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("\n The elements of the matrix are ");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("\t %d", mat[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
transposed_mat[i][j] = mat[j][i];
}
printf("\n The elements of the transposed matrix are ");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("\t %d",transposed_ mat[i][j]);}
return 0;
}
Output
Enter the elements of the matrix
123456789
The elements of the matrix are
123
456
789
The elements of the transposed matrix are
147
258
369
2. Write a program to input two m x n matrices and then calculate the sum of their corresponding elements and
store it in a third m x n matrix.
#include <stdio.h>
int main()
{
int i, j;
int rows1, cols1, rows2, cols2, rows_sum, cols_sum;
int mat1[5][5], mat2[5][5], sum[5][5];
clrscr();
printf("\n Enter the number of rows in the first matrix : ");
scanf("%d",&rows1);
printf("\n Enter the number of columns in the first matrix : ");
scanf("%d",&cols1);
printf("\n Enter the number of rows in the second matrix : ");
scanf("%d",&rows2);
printf("\n Enter the number of columns in the second matrix : ");
scanf("%d",&cols2);
if(rows1 != rows2 || cols1 != cols2)
{
printf("\n Number of rows and columns of both matrices must be equal");
exit(0);
}
rows_sum = rows1;
cols_sum = cols1;
printf("\n Enter the elements of the first matrix ");
for(i=0;i<rows1;i++)
{
for(j=0;j<cols1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("\n Enter the elements of the second matrix ");
for(i=0;i<rows2;i++)
{
for(j=0;j<cols2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<rows_sum;i++)
{
for(j=0;j<cols_sum;j++)
sum[i][j] = mat1[i][j] + mat2[i][j];
}
printf("\n The elements of the resultant matrix are ");
for(i=0;i<rows_sum;i++)
{
printf("\n");
for(j=0;j<cols_sum;j++)
printf("\t %d", sum[i][j]);
}
return 0;
}
Output
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
Enter the number of rows in the second matrix: 2
Enter the number of columns in the second matrix: 2
Enter the elements of the first matrix
1234
Enter the elements of the second matrix
5678
The elements of the resultant matrix are
68
10 12
[Link] a program to multiply two m x n matrices.
#include <stdio.h>
int main()
{
int i, j, k;
int rows1, cols1, rows2, cols2, res_rows, res_cols;
int mat1[5][5], mat2[5][5], res[5][5];
clrscr();
printf("\n Enter the number of rows in the first matrix : ");
scanf("%d",&rows1);
printf("\n Enter the number of columns in the first matrix : ");
scanf("%d",&cols1);
printf("\n Enter the number of rows in the second matrix : ");
scanf("%d",&rows2);
printf("\n Enter the number of columns in the second matrix : ");
scanf("%d",&cols2);
if(cols1 != rows2)
{
printf("\n The number of columns in the first matrix must be equal
to the number of rows in the second matrix");
exit();
}
res_rows = rows1;
res_cols = cols2;
printf("\n Enter the elements of the first matrix ");
for(i=0;i<rows1;i++)
{
for(j=0;j<cols1;j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("\n Enter the elements of the second matrix ");
for(i=0;i<rows2;i++)
{
for(j=0;j<cols2;j++)
{
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<res_rows;i++)
{
for(j=0;j<res_cols;j++)
Arrays 103
{
res[i][j]=0;
for(k=0; k<res_cols;k++)
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
printf("\n The elements of the product matrix are ");
for(i=0;i<res_rows;i++)
{
printf("\n");
for(j=0;j<res_cols;j++)
printf("\t %d",res[i][j]);
}
return 0;
}
Output
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
Enter the number of rows in the second matrix: 2
Enter the number of columns in the second matrix: 2
Enter the elements of the first matrix
1234
Enter the elements of the second matrix
5678
The elements of the product matrix are
19 22
43 50
Pointer and 2D Array:
Write a program to read and display a 3 x 3 matrix.
#include <stdio.h>
#include <conio.h>
void display(int (*)[3]);
int main()
{
int i, j, mat[3][3];
clrscr();
printf("\n Enter the elements of the matrix");
for(i=0;i<3;i++)
{
for(j = 0; j < 3; j++)
{
scanf("%d", &mat[i][j]);
}
}
display(mat);
return 0;
}
void display(int (*mat)[3])
{
int i, j;
printf("\n The elements of the matrix are");
for(i = 0; i < 3; i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("\t %d",*(*(mat + i)+j));
}
}
Output
Enter the elements of the matrix
123456789
The elements of the matrix are
123
456
789
Pointer and 3D Array
Write a program which illustrates the use of a pointer to a three-dimensional array.
#include <stdio.h>
int main()
{
int i,j,k;
int arr[2][2][2];
int (*parr)[2][2]= arr;
clrscr();
printf("\n Enter the elements of a 2 \ 2 \ 2 array: ");
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
for(k = 0; k < 2; k++)
scanf("%d", &arr[i][j][k]);
}
}
printf("\n The elements of the 2 \ 2 \ 2 array are: ");
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
for(k = 0; k < 2; k++)
printf("%d", *(*(*(parr+i)+j)+k));
}
}
return 0;
}
Output
Enter the elements of a 2 \ 2 \ 2 array: 1 2 3 4 5 6 7 8
The elements of the 2 \ 2 \ 2 array are: 1 2 3 4 5 6 7 8
Note In the printf statement, you could also have used * ( * ( * ( a r + i ) + j + ) + k ) instead of
*(*(*(parr+i)+j)+k)).
Advantages of using Arrays:
• Arrays allow random access to elements. This makes accessing elements by position faster.
• Arrays have better cache locality which makes a pretty big difference in performance.
• Arrays represent multiple data items of the same type using a single name.
• Arrays store multiple data of similar types with the same name.
• Array data structures 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.
Application of arrays
• They are used in the implementation of other data structures such as array lists, heaps, hash tables, vectors, and
matrices.
• Database records are usually implemented as arrays.
• It is used for different sorting algorithms such as bubble sort insertion sort, merge sort, and quick sort.
• It is used for implementing matrices.
• Graphs are also implemented as arrays in the form of an adjacency matrix.
[T-6]
Sparse Matrices and their representations
• A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values.
• If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix?
• Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those
elements.
• Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero
elements.
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in
most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means
storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common representations:
• Array representation
• Linked list representation*
Method 1: Using Arrays:
2D array is used to represent a sparse matrix in which there are three rows named as
• Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is located
• Value: Value of the non-zero element located at index – (row, column)
Implementation in C
// C program for Sparse Matrix Representation // using Array
#include<stdio.h>
int main()
{ // Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
// number of columns in compactMatrix (size) must be equal to number of non - zero elements in sparseMatrix
int compactMatrix[3][size];
// Making of new matrix
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
for (int i=0; i<3; i++)
{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);
printf("\n");
}
return 0;
}
Output
001133
242312
345726