You are on page 1of 11

Data Structure

And
Algorithm
Assignment on array and sparse matrix

SILICON INSTITUTE OF TECHNOLOGY, BHUBANESHWAR

NAME – SONALI SURYA

ROLL No. – 28

SECTION – E(2)

SIC No. – 180410402


Array
What is an array?

 An array is a collection of data items, all of the same type, accessed using a common
name.
 A one-dimensional array is like a list; a two dimensional array is like a matrix. The C
language places no limits on the number of dimensions in an array, though specific
implementations may.
 Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays
as matrices, and use the general term arrays when the number of dimensions is
unspecified or unimportant.

Declaring Arrays

 Array variables are declared identically to variables of their data type, except that the
variable name is followed by one pair of square [ ] brackets for each dimension of the
array.
 Uninitialized arrays must have the dimensions of their rows, columns, etc. listed
within the square brackets.
 Dimensions used when declaring arrays in C must be positive integral constants or
constant expressions.
 Examples:

inti, j, intArray[ 10 ], number;


floatfloatArray[ 1000 ];
inttableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */

constint NROWS = 100;


constint NCOLS = 200;
float matrix[ NROWS ][ NCOLS ];

Initializing Arrays

 Arrays may be initialized when they are declared, just as any other variables.
 Place the initialization data in curly {} braces following the equals sign. Note the use
of commas in the examples below.
 An array may be partially initialized, by providing fewer data items than the size of
the array. The remaining array elements will be automatically initialized to zero.
 If an array is to be completely initialized, the dimension of the array is not required.
The compiler will automatically size the array to fit the initialized data.
 Examples:

inti = 5, intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 };
Using Arrays

 Elements of an array are accessed by specifying the index (offset) of the desired
element within square [ ] brackets after the array name.
 Array subscripts must be of integer type. ( int, long int, char, etc. )
 VERY IMPORTANT: Array indices start at zero in C, and go to one less than the
size of the array. For example, a five element array will have indices zero through
four. This is because the index in C is actually an offset from the beginning of the
array. ( The first element is at the beginning of the array, and hence has zero offset. )
 Arrays are commonly used in conjunction with loops, in order to perform the same
calculations on all ( or some part ) of the data items in the array.

Sample Programs Using 1-D Arrays

 The first sample program uses loops and arrays to calculate the first twenty Fibonacci
numbers. Fibonacci numbers are used to determine the sample points used in certain
optimization methods.

/* Program to calculate the first 20 Fibonacci numbers. */

#include <stdlib.h>
#include <stdio.h>

int main( void )


{

inti, fibonacci[ 20 ];

fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;

for(i = 2; i< 20; i++ )


fibonacci[ i ] = fibonacci[ i - 2 ] +fibonacci[i - 1];

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


printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ]);

 Exercise: What is the output of the following program:

/* Sample Program Using Arrays */

#include <stdlib.h>
#include <stdio.h>

int main( void ) {

int numbers[ 10 ];
inti, index = 2;
for(i = 0; i< 10; i++ )
numbers[ i ] = i * 10;

numbers[ 8 ] = 25;
numbers[ 5 ] = numbers[ 9 ] / 3;
numbers[ 4 ] += numbers[ 2 ] / numbers[ 1 ];
numbers[ index ] = 5;
++numbers[ index ];
numbers[ numbers[ index++ ] ] = 100;
numbers[ index ] = numbers[ numbers[ index + 1 ] / 7 ]--;

for( index = 0; index < 10; index++ )


printf( "numbers[ %d ] = %d\n" index, numbers[ index ] );

} /* End of second sample program */

Multidimensional Arrays

 Multi-dimensional arrays are declared by providing more than one set of square [ ]
brackets after the variable name in the declaration statement.
 One dimensional arrays do not require the dimension to be given if the array is to be
completely initialized. By analogy, multi-dimensional arrays do not require the
first dimension to be given if the array is to be completely initialized. All dimensions
after the first must be given in any case.
 For two dimensional arrays, the first dimension is commonly considered to be the
number of rows, and the second dimension the number of columns.
 A way of looking at this is that C stores two dimensional arrays by rows, with all
elements of a row being stored together as a single unit.
 Multidimensional arrays may be completely initialized by listing all data elements
within a single pair of curly {} braces, as with single dimensional arrays.
 It is better programming practice to enclose each row within a separate subset of curly
{} braces, to make the program more readable. This is required if any row other than
the last is to be partially initialized. When subsets of braces are used, the last item
within braces is not followed by a comma, but the subsets are themselves separated by
commas.
 Multidimensional arrays may be partially initialized by not providing complete
initialization data. Individual rows of a multidimensional array may be partially
initialized, provided that subset braces are used.
 Individual data items in a multidimensional array are accessed by fully qualifying an
array element. Alternatively, a smaller dimensional array may be accessed by
partially qualifying the array name. For example, if "data" has been declared as a
three dimensional array of floats, then data[ 1 ][ 2 ][ 5 ] would refer to a float,
data[ 1 ][ 2 ] would refer to a one-dimensional array of floats, and data[ 1 ] would
refer to a two-dimensional array of floats. The reasons for this and the incentive to do
this relate to memory-management issues that are beyond the scope of these notes.
Sample Program Using 2-D Arrays

/* Sample program Using 2-D Arrays */

#include <stdlib.h>
#include <stdio.h>

int main( void )


{

/* Program to add two multidimensional arrays */

int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };


int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };
int sum[ 2 ][ 3 ], row, column;

/* First the addition */

for( row = 0; row < 2; row++ )


for( column = 0; column < 3; column++ )
sum[ row ][ column ] =
a[ row ][ column ] + b[ row ][ column ];

/* Then print the results */

printf( "The sum is: \n\n" );

for( row = 0; row < 2; row++ ) {


for( column = 0; column < 3; column++ )
printf( "\t%d", sum[ row ][ column ] );
printf( '\n' ); /* at end of each row */
}

return 0;
}

Application of array

(i)Array Can be Used for Sorting Elements

As widely known arrays play an important role in sorting algorithms!

(ii)Array Can Perform Matrix Operation

Matrix multiplication is greatly done using arrays

(iii)Array Can be Used in CPU Scheduling


Arrays can be used in various CPU scheduling algorithms. CPU Scheduling is generally
managed by Queue. Queue can be managed and implemented using the array. Array may be
allocated dynamically i.e at run time.

(iv)Array Can be Used in Recursive Function

When the function calls another function or the same function again then the current values
are stores onto the stack and those values will be retrieve when control comes back. This is
similar operation like stack.

Some programs using array

Question1: WAP to find the largest element in an array

#include <stdio.h>

int main()
{
inti, n;
floatarr[100];

printf("Enter total number of elements(1 to 100): ");


scanf("%d", &n);
printf("\n");

// Stores number entered by the user


for(i = 0; i< n; ++i)
{
printf("Enter Number %d: ", i+1);
scanf("%f", &arr[i]);
}

// Loop to store largest number to arr[0]


for(i = 1; i< n; ++i)
{
// Change <to> if you want to find the smallest element
if(arr[0] <arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);

return 0;
}

Output

Enter total number of elements(1 to 100): 8

Enter Number 1: 23.4


Enter Number 2: -34.5
Enter Number 3: 50
Enter Number 4: 33.5
Enter Number 5: 55.5
Enter Number 6: 43.7
Enter Number 7: 5.7
Enter Number 8: -66.5

Question 2: WAP to find average of given numbers

#include <stdio.h>
int main()
{
intavg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


intnum[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

Output:

Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Question 3: WAP to implement selection sort algorithm

#include <stdio.h>

int main()
{
int array[100], n, c, d, position, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


scanf("%d", &array[c]);

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


{
position = c;

for (d = c + 1; d < n; d++)


{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}

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

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


printf("%d\n", array[c]);

return 0;
}

Output

Enter number of elements


10
Enter 10 integers
12
8
-6
2
4
5
3
7
4
2
Sorted list in ascending order
-6
2
2
3
4
4
5
7
8
12

Question 5: WAP for Matrix multiplication

#include <stdio.h>

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

printf("Enter number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");

for (c = 0; c < m; c++)


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

printf("Enter number of rows and columns of second matrix\n");


scanf("%d%d", &p, &q);

if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of the matrices:\n");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);

printf("\n");
}
}

return 0;
}

Output

Enter the number of rows and columns of first matrix


3
3
Enter the elements of first matrix
120
011
201
Enter the rows and columns of second matrix
3
3
Enter the elements of the second matrix
112
211
121
product of the entered matrices
534
332
345
Sparse Matrix and its 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.

Example:

00304
00570
00000
02600

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).

You might also like