C Programming Unit-4 Arrays
C Programming Unit-4 Arrays
ARRAYS
INTRODUCTION
So far we used only the fundamental data types, namely char, int, float, double and
variations of int and double. These types are very useful, can store only one value at any
given time, can be used only to handle limited amounts of data. In many applications, we
need to handle a large volume of data in terms of reading, processing and printing. To
process such large amounts of data C supports a derived data types know as array.
An array is a fixed-size sequenced collection of elements of the same data type. It is
simply a grouping of like-type data used to represent a list of numbers or a list of names.
The concept of array can be used in:
● Internal Assessment marks of a class of students.
● Table of daily rainfall data.
● List of employees in an organization, and so on.
Since an array provides a convenient structure for representing data, it is classified as one
of the data structure in C like Structures, Lists, Stack, Queues and Trees.
An array is sequenced collection of related data items that are shares a common name.
We can refer to the individual items by writing a number called index or subscript in
square brackets after the array name. For example: sum[10], name[25], etc.
The complete set of values are referred to as an array, individual values are called
elements. The ability to use a single name to represent a collection of items and to refer to
an item by specifying the item number enables us to develop concise and efficient
programs. We can use arrays to represent list of values, table of data in two or three or
more dimensions.
● One-dimensional Arrays
● Two-dimensional Arrays
● Multi-dimensional Arrays
Arrays and structures are referred to as structured data types because they can be used to
represent data values that have a structure of some sort. C supports creation and
manipulation of the following data structures: Linked Lists, Stacks, Queues and Trees which
shows the relationships among the individual elements and facilitate efficient data manipulations.
C Programming
The type specifies the type of element that will be contained in the array, such as int, float
or char and the size indicates the maximum number of elements that can be stored inside
the array. For example,
int srno[6]; /* an array containing 6 integer elements, any subscript 0 to 5 are valid */
float height[10]; /* an array containing 10 real elements, any subscript 0 to 9 are valid */
char remarks[25]; /* an array containing 24 + ‘\0’ characters (string) */
C Programming
When the complier sees a character string, it terminates it with an additional null
character. Thus, the element at remarks[25] position holds the null character ‘\0’. When
declaring character arrays, we must allow one extra element space for the null
terminator.
The values in the list are separated by commas. For example, the statement
int number[3] = {1,2,3};
float avg[3] = {55.75, 67.25, 92.66};
char college[5] = {‘S’, ‘J’, ‘C’, ‘E’, ‘\0’}; /* ASCII values are stored in the memory */
int counter[] = {1,2,3,4,5,6}; /* size may be omitted, the compiler allocates enough space
for all initialized elements i.e., size of the array is counter[6] */
Run Time initialization: An array can be explicitly initialized at run time; it is usually
applied for initializing large arrays. This can be achieved using assignment statement or
using a read function such as scanf to initialize an array. For example,
.....
.....
for(i=0 ; i<100; i=i+1)
{
if (i<50)
sum[i] = 0.0;
else
sum[i] = 1.0;
}
.....
.....
/* To find and sum of +ve , –ve numbers along with their average */
psum = nsum = 0;
for(i=0;i<n;i++)
{
if(a[i] < 0)
{
printf("\n%d\t-> - ve",a[i]);
nsum = nsum + a[i];
}
else
{
printf("\n%d\t-> + ve",a[i]);
psum = psum + a[i];
}
}
average = (psum + nsum) / 2 ;
/* Generation of Fibonacci numbers using array */
printf("\nThe Fibinacci Numbers : ");
a[0]=0;
a[1]=1;
for(i=2;i<n;i++)
a[i] = a[i-1] + a[i-2]; /* to store the Fibonacci Numbers */
for(i=0;i<n;i++)
printf("\n%d ",a[i]); /* to print the Fibonacci Numbers */
/* Largest of N numbers. */
big = a[0]; pos = 0;
for(i=1;i<n;i++)
{
if(a[i] > big)
{
big = a[i];
pos = i;
}
}
printf("%d at position %d",big,pos+1);
{
pass=0; /* to avoid unnecessary passé(s) */
for(i=0;i<n-j;i++)
{
if(a[i] > a[i+1])
{
ex = a[i];
a[i] = a[i+1];
a[i+1] = ex;
pass=1;
}
printf("\nThe elements after %d pass : ",j); /* to print every pass list */
for(k=0;k<n;k++)
printf("%d ",a[k]);
}
sum=0;
for(i=0;i<n;i++)
{
sum= sum + a[i] * pow(x, i);
}
sum=a[n] * x ;
for(i=n-1 ; i>0 ; i--)
{
sum= (sum + a[i]) * x ;
}
sum = sum + a[0];
C Programming
sum = 0 ;
for ( i = 0 ; i < n ; i++ )
{
sum = sum + X[i];
}
m = sum / n ;
sum = 0 ;
for ( i = 0 ; i < n ; i++ )
{
sum = sum + ( X[i] – mean ) * ( X[i] – mean ) ;
}
v = sum / n ;
d = sqrt ( v ) ;
C Programming
Two-Dimensional Arrays:
There could be situations where a table of values will have to be stored. We can think of a
table as a matrix consisting of rows and columns. We represent a matrix by using two
subscripts. C allows us to define such tables of items by using two-dimensional arrays.
This can be defined in C as a[3][4]
Note that unlike other languages, which use one pair of parenthesis with commas to
separate array size, C places each size in its own set of brackets.
As with the single-dimensional arrays, each dimension of the array is indexed from zero
X(0) to its maximum size minus one X(N-1); the first index selects the row and the
second index selects the column with in that row.
Memory Layout
The subscripts in the definition in the 2-dimensional array represent rows and columns.
The elements of all arrays are stored contiguously in increasing memory locations,
essentially in a single list. A 2-dimensional array is stored “row-wise”, starting from the
first row and ending with the last row, treating each row like a simple array. This is
Illustrated below.
Column
0 1 2
0
Row 1 3 x 3 array
2
1 2 3 4 5 6 7 8 9
/* Addition of two matrices [A & B] and store the result in C (possible only when order of
the Mat-A(MxN) is equal to Mat-b(MxN) )*/
for( i = 0 ; i < m ; i++ ) /* m-rows */
{
for( j = 0 ; j < n ; j++ ) /* n-columns */
{
c[i][j]) = a[i][j]) + b[i][j]); /* adds Mat-A with Mat-B */
}
}
/* Subtraction of two matrices [A & B] and store the result in C (possible only when
order of the Mat-A(MxN) is equal to Mat-b(MxN) ) */
for( i = 0 ; i < m ; i++ ) /* m-rows */
{
for( j = 0 ; j < n ; j++ ) /* n-columns */
{
c[i][j]) = a[i][j]) - b[i][j]); /* Subtract Mat-B from Mat-A */
}
}
/* Product of two matrices [A & B] and store the result in C (possible only when order of
the row of Mat-A is equal to order of the column of Mat-B i.e., A(M x N) = B(N x M)*/
for( i = 0 ; i < m ; i++ ) /* m-rows */
{
for( j = 0 ; j < q ; j++ ) /* n-columns */
{
c[i][j]) = 0;
for( k = 0 ; k < n ; k++ )
{
/* Transpose of a matrix */
for( i = 0 ; i < m ; i++ ) /* m-rows */
{
for( j = 0 ; j < n ; j++ ) /* n-columns */
{
printf(“%d”, a[j][i]); /* Transpose row into column */
}
printf(“\n”); /* move to new/next line */
}
/*Trace of a matrix (possible only when the order of row is equal to column i.e., M=N)*/
sum = 0 ;
for( i = 0 ; i < m ; i++ )
sum = sum + a[i][i];
printf(“Trace of the Matrix (Sum all diagonal elements of the Matrix ) = %d”, sum);
/* Norm of a Matrix is the square root of sum of squares of all the elements in a given
matrix */
sum = 0;
for( i = 0 ; i < m ; i++ )
for( j = 0 ; j < n ; j++ )
sum = sum + a[i][j]) * a[i][j]) ;
norm = sqrt(sum) ;
printf(“Norm of Matrix = %f”, norm);
Points to be Remembered
● We need to specify three things, Type, Name and Size, when we declare an array.
● Always remember that subscripts begin at 0 (not 1) and end at SIZE-1.
● Define the size of an array as a symbolic constant, Initialize the elements and
avoid “garbage” contents.
● When using expressions for subscripts, make sure that their result do not go
outside the permissible range of 0 to size-1. Referring to an element outside the
array bounds is an error.
● When initializing character arrays (strings), provide enough space for the
terminating null character.
● Make sure that the subscript variables have been properly initialized before they
are used.
● Leaving out the subscript reference operator [] in an assignment operator is
compile time error.( use of a = 5 instead of a[3] = 5 )