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

C Programming Unit-4 Arrays

The document provides an overview of arrays in C programming, explaining their purpose as a collection of elements of the same data type. It covers one-dimensional arrays, their declaration, initialization, and manipulation techniques, including reading and writing data, performing calculations, and sorting and searching algorithms. Additionally, it discusses the importance of structured data types and provides examples of various operations that can be performed using arrays.

Uploaded by

Mohammed Sadiq
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)
0 views15 pages

C Programming Unit-4 Arrays

The document provides an overview of arrays in C programming, explaining their purpose as a collection of elements of the same data type. It covers one-dimensional arrays, their declaration, initialization, and manipulation techniques, including reading and writing data, performing calculations, and sorting and searching algorithms. Additionally, it discusses the importance of structured data types and provides examples of various operations that can be performed using arrays.

Uploaded by

Mohammed Sadiq
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
You are on page 1/ 15

​ C Programming

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

One/Single-Dimensional Arrays: [Single-Subscripted]


A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted or a one-dimensional array. It can be expressed as
x[0], x[1], x[2], x[3],…x[n-1]. The subscript can begin with number 0.
For example,​ int srno[5]; ​ The computer reserves five consecutive/continues storage
location on memory area of two bytes of each item (2 x 5 = 10 i.e. TYPE x SIZE).
​ ​ ​ srno[0]
​ ​ ​ srno[1]
​ ​ ​ srno[2]​
​ ​ ​ srno[3]
​ ​ ​ srno[4]
These elements may be used in programs just like any other C variable. For example,
​ a = number[0] + 10;
​ number[3] = number[1] + number[2];
​ number[6] = number[0] + 10 * 5;
​ number[0] = a[0] + b[0];
These subscripts of an array can be integer constants, integer variables like I, or
expressions that yield integers. C performs no bounds checking and, therefore care
should be taken to ensure that the array indices are within the declared limits.

Declaration of One-Dimensional Arrays:


The general form of array declaration is ​
​ ​ ​ ​ ​ or

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.

Initialization of One-Dimensional Arrays:


After an array is declared, its elements must be initialized. Otherwise, they will contain
“garbage”. An array can be initialized at following stages:
●​ At compile time
●​ At run time
Compile Time initialization: An array can be declared in the same way as the ordinary
variables. The general form of initialization of array is:

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;
}
.....
.....

Different Ways of Initializing Arrays


​ C Programming

Initializing all specified memory locations:


int number[3] = {1,2,3}; /* during compilation, three contiguous memory locations are reserved */
int contr[3] = {1,2,3,4,5}; /*Compiler will produce an error for more initializers than declared size */
Partial Array Initialization:
char college[5] = {‘J’, ‘C’}; /* The remaining elements are initialized to NULL i.e., ‘\0’ */
char college[5] = {‘J’, ‘C’, ‘\0’, ‘\0’, ‘\0’ };
int counter[5] = {1,2,3}; /* The remaining elements are initialized to ZERO */
int counter[5] = {1,2,3,0,0};
Initializing without Size:
char college[] = {‘S’, ‘J’, ‘C’, ‘E’}; /* size will be set to 4 automatically by the compiler */
int counter[] = {1,2,3,4,5,6}; /* size may be omitted, the compiler allocates automatically
enough space for all initialized elements i.e., size of the array is counter[6] */
String Initialization:
Char college[] = “SJCE CAMPUS”;
Size will be set to 12 not 11, because it is a string not a character. String always ends with
NULL character. So, the array size is 12 i.e., string size + 1 byte for null character.

Reading and Writing Single Dimensional Arrays:


Let us concentrate on how to read the data from the keyboard and how to display data
items stored in the array. Consider the declaration shown below:
int a[5];​ Here, 5 memory locations are reserved accessed by specifying the
index as follows ​ a[0] through a[4]
In general, using a[0] through a[n-1] we can access n data items.
In general, to read the n data items from the keyboard, the following statement can be
used:
for (i = 0 ; i < n-1; n = n + 1)​ ​ i = 0​ 1​ 2​ 3​ …​ n-1
{
​ scanf(“%d”, &a[i]);​ ​ a[0]​ a[1]​ a[2]​ a[3]​ …​ a[n-1]
}
Similarly, to display n data items stored in the array, replace scanf() by printf() statement
as shown below:
for (i = 0 ; i < n-1; n = n + 1)​ ​
{
​ printf(“%d”, &a[i]);​
​ C Programming

Manipulation of One/Single-Dimensional Arrays:


●​ To read N elements from the keyboard and display the same on the monitor.
●​ Addition of N elements in an array and to find the average.
●​ To find sum of +ve , –ve numbers and their average.
●​ Generation of Fibonacci numbers using array.
●​ Largest of N numbers.
●​ Sorting techniques like Bubble, Selection etc.,
●​ Searching techniques like Linear, Binary etc.,
●​ Evaluation of Polynomial Equation [General and Horner’s method].
●​ Etc.,

Logical Program Part of the above problems


/* To read N elements from the keyboard */
​ printf("\nEnter the size of a List : ");
​ scanf("%d",&n);
​ printf("\nEnter the %d elements",n);
​ for(i=0;i<n;i++)​ /* For array index 0 to N-1 elements */
​ {
​ ​ scanf("%d",&a[i]);
​ }

/* To display/print the N elements of array on monitor. */


​ printf("\nEntered List as follows : ");
​ for(i=0;i<n;i++)
​ {
​ ​ printf("%d ",a[i]);
​ }
​ C Programming

/* Addition of N elements in an array and to find the average */


​ sum=0;
​ for(i=0;i<n;i++)
​ {
​ ​ sum = sum + a[i];
​ }​
​ average = sum / n;
​ printf("\Sum of N elements is = %d and Average is = ",sum, average );

/* 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);

/* Sorting Technique: Bubble Sort */


​ for(j=1;j<n && pass==1 ;j++) ​ /* to repeat n-1 passes */
​ C Programming

​ {
​ 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]);
​ }

/* Sorting Technique: Selection Sort */


​ for(i=0 ; i<n-1 ; i++)​ ​ /* to repeat n-1 times */
​ {
​ pos = i ;
​ ​ for(j=i+1 ; j<n ; j++)
​ ​ {​
​ ​ ​ if( a[j] < a[pos] )
​ ​ ​ {
​ ​ ​ pos = j ;
​ ​ ​ }
​ ​ }
​ ​ temp = a[pos] ;
​ ​ a[pos] = a[i] ;
​ ​ a[i] = temp ;
​ }

/*Searching Technique: Linear Search */


​ for(i=0 ; i<n ; i++) ​ ​ /* to repeat n-1 times */
​ {
​ ​ if( a[i] == key )
​ ​ ​ {
​ ​ ​ printf(“\n Search Successful”) ;
​ ​ ​ exit(0);
​ ​ ​ }
​ }
​ printf(“\n Search Unsuccessful / Failure”) ;
​ C Programming

/*Searching Technique: Binary Search */


begin = 0;
end = n-1;
while( begin <= end )
{
​ mid = ( begin + end ) / 2 ;
​ if(item == a[mid])
​ {
​ printf(“\n Search Successful”) ;
​ exit(0);
​ }
​ if(item < a[mid])
​ end = mid – 1;
​ else
​ begin = mid + 1;
}
printf(“\n Search Unsuccessful / Failure ”) ;

/* Evaluation of Polynomial Equation [General and Horner’s method] */


General Equation: a0 x0 + a1 x1 + a2 x2 + a3 x3 + . . . . . + an-1 xn-1 + an xn , the general term is
given by ai xi​ for i = 1,2,3,…,n

sum=0;
​ for(i=0;i<n;i++)
​ {
​ ​ sum= sum + a[i] * pow(x, i);
​ }​

Horner’s method: a0 x0 + a1 x1 + a2 x2 + a3 x3 + . . . . . + an-1 xn-1 + an xn can be rearranged as


a0 + x(a1 + x(a2 + x(a3 + x(a4 + . . . . . x(an-4+ x(an-3 + x(an-2 + x(an-1 + xan )))) . . . . . ))))
​ Initial ​ ​ :​ sum = an x
​ General ​ :​ sum = ( sum + ai ) x​ for i = n-1, n-2, . . . ,3, 2, 1
​ Final​ ​ :​ sum = sum + a0

​ sum=a[n] * x ;​
​ for(i=n-1 ; i>0 ; i--)
​ {
​ ​ sum= (sum + a[i]) * x ;
​ }​
​ sum = sum + a[0];
​ C Programming

/* To find MEAN, VARIANCE and STANDARD DEVIATION */


Mean: ​ m = ( x0 + x1 + x2 + x3 + . . . xn-1 ) / n

​ sum = 0 ;
​ for ( i = 0 ; i < n ; i++ )
​ {
​ ​ sum = sum + X[i];
​ }
​ m = sum / n ;

Variance: v = ( ( x0 – mean)2 + ( x1 – mean)2 + ( x2 – mean)2 + . . . ( xn-1 – mean)2 ) / n


and Deviation:​d = sqrt ( variance )

​ 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]​

Two-Dimensional Arrays are declared as follows:

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.

Column 0​ Column 1​ Column 2

[0][0]​ [0][1] ​ [0][2]


Row 0

​ ​ [1][0]​ [1][1] ​ [1][2]


Row 1

​ ​ [2][0]​ [2][1] ​ [2][2]


Row 2

​ ​ [3][0]​ [3][1] ​ [3][2]


Row 3

Figure : Representation of a two-dimensional array in memory ( 4 x 3 ).

Initialization of Two-Dimensional Arrays:


​ C Programming

Like the one-dimensional arrays, two-dimensional arrays may be initialized by following


their declaration with a list of initial values enclosed in braces. For example,
int table[2][3] = { 1,2,3,4,5,6 } ;
The initialization is done row by row. The above statement can be written as
int table[2][3] = { {1,2,3}, {4,5,6} } ; by surrounding the elements of the each row by braces.

The above statement can be written in the form of a matrix as


​ int table[2][3] = {
​ ​ ​ {1,2,3},
​ ​ ​ {4,5,6}
​ ​ ​ };
When the array is completely initialized with all values, explicitly, we need not specify
the size of the first dimension.
​ int table[ ][3] = {
​ ​ ​ {1,2,3},
​ ​ ​ {4,5,6}
​ ​ ​ } ;​ ​ is permitted.
If the values are missing in an initializer, they automatically set to zero as in
1-dimensional array.
​ int table[2][3] = {
​ ​ ​ {1,2},
​ ​ ​ {3}
​ ​ ​ };
​ C Programming

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​

​ row 0 ​​ row 1​ row 2

1 2 3 4 5 6 7 8 9

Initializing all specified memory locations:


int a[3][4] = ​ {
​ ​ ​ {1,2,3,4},
​ ​ ​ {5,6,7,8},
​ ​ ​ {9,10,11,12}
​ ​ };
Note that a[0][0] = 1, a[1][1] = 6, a[2][2] = 11, a[2][3] = 12

Partial Array Initialization:


int a[4][3] = ​ {
​ ​ ​ {1,2},
​ ​ ​ {5,6},
​ ​ ​ {3,4},
​ ​ ​ {7,8}
​ ​ };
Note that first two columns of each row are initialized and the third column of each row
will be initialized with zeros automatically. That is a[0][2], a[1][2], a[2][2], a[3][2] all
are initialized with zeros.
​ C Programming

Reading-Writing 2-Dimensional Arrays:


To access each item row wise in 2-dimensional array, the row index i should be in the
outer loop and column index j should be in the inner loop. The C statements to access any
element a[i][j] can be written as:
​ for( i = 0 ; i < m ; i++ )​ ​ /* m-rows */
​ {
​ ​ for( j = 0 ; j < n ; j++ ) ​ /* n-columns */
​ ​ {
​ ​ ​ a[i][j]; ​ ​ /* M x N accesses */
​ ​ }
​ }
To Read 2-Dimensional Array of Size M x N: By including scanf() just before a[i][j].
​ for( i = 0 ; i < m ; i++ ) ​ ​ ​ /* m-rows */
​ {
​ ​ for( j = 0 ; j < n ; j++ )​ ​ /* n-columns */
​ ​ {
​ ​ ​ scanf(“%d”,& a[i][j]); /* Read M x N items */
​ ​ }
​ }
To Print 2-Dimensional Array of Size M x N: By including printf() just before a[i][j].
​ for( i = 0 ; i < m ; i++ ) ​ ​ ​ /* m-rows */
​ {
​ ​ for( j = 0 ; j < n ; j++ )​ ​ /* n-columns */
​ ​ {
​ ​ ​ printf(“%d”, a[i][j]); /* Print M x N items */
​ ​ }
​ ​ printf(“\n”);​ ​ ​ /* move to new/next line */
​ }
Manipulation of Two/2-Dimensional Arrays:
●​ Addition of two matrices [A & B] and store the result in C.
●​ Subtraction of two matrices [A & B] and store the result in C.
●​ Product of two matrices [A & B] and store the result in C.
●​ Sum of elements of a given matrix.
●​ Average of all the elements of a given matrix.
●​ Largest/Smallest element in a given matrix.
●​ Transpose of a matrix.
●​ Trace o a matrix.
●​ Etc.,

Logical Program Part of the above problems


​ C Programming

/* 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++ )​ ​
​ ​ {

​ ​ c[i][j]) = c[i][j]) + a[i][k]) * b[k][j]);


​ ​ }
​ }
​ }
/* Sum and Average of elements of a given matrix */
sum = 0;
for( i = 0 ; i < m ; i++ ) ​
​ for( j = 0 ; j < n ; j++ )
​ sum = sum + a[i][j])
average = sum / (m*n) ;
/* Largest/Smallest element in a given matrix */
big = a[0][0];​ ​ /* for Smallest -> small = a[0][0] */
for( i = 0 ; i < m ; i++ ) ​
​ for( j = 1 ; j < n ; j++ )
​ if( a[i][j] > big)​ /* for Smallest -> if( a[i][j] < small) */
​ ​ ​ big = a[i][j]; /* for Smallest -> small = a[i][j]; */
printf("%d is the Largest in the given Matrix ", big);
​ C Programming

/* 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 )

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy