Vous êtes sur la page 1sur 78

Array

Objective
Understand what is an array
Learn about types of array
Declaration
Initialization
Ways to access individual elements
Other possible operations

Need for an Array


Each variable can only be used to store a
single value at a time.
E.g. int a;
float b;
The average of two integer numbers given
by the user can easily be computed.
But printing the numbers that are greater
than the average, requires:
Reading the numbers
Calculating the average
Checking the each number with average.

Cont
So there is a need to store large
number of variables of same type
under a single variable.
Easy understanding of the program.
E.g.
To store Marks of 50 students.
Record of sales of 100 salesman.

Definition
An array is a collection of individual
data elements that is
Ordered : one can count off the elements
0,1,2,
Fixed in size
Homogenous : all elements have to be of
the same data type.
E.g. int, float, double, char etc.

It is considered as derived data type.

Array Applications
Given a list of test scores, determine the
maximum and minimum scores.
Read in a list of student names and
rearrange them in alphabetical order
(sorting).
Given the height measurements of
students in a class, output the names of
those students who are taller than
average.

Types of Array
One Dimensional Array
Two Dimensional Array
Multi-Dimensional Array

One Dimensional Array


Array is One Dimensional, there will be a
single subscript or index whose value
refers to the individual array elements
which ranges from 0 to (n-1), where n is
the total number of elements in the array.

Also called as single dimensional array

Declaration One Dimensional


Array
Three things need to be specified:
The type of data it can hold, i.e. int, float, double etc.
The number of values it can hold or size, i.e. maximum
number of elements it can hold
A name of array.

Syntax:
<data type> <arrayName>[<array_size>]
E.g. int A[10];
<array_size> must be an constant or a constant
expression. .

Cont
// array of 10 uninitialized ints
int A[10];
0
A

Cont
Declare an array of 10 integers:
int A[10];

// array of 10 ints

To access an individual element we must apply a


subscript to array named A.
A subscript is a bracketed expression.
The expression in the brackets is known as the index.

First element of array has index 0.


A[0]

Second element of array has index 1, and so on.


A[1], A[2], A[3],

Last element has an index one less than the size of the
array.
A[9]

Incorrect indexing is a common error.

Cont
Invalid Declaration
double x[]
no value assigned to the size.

int N;
double x[N]
Variable of integer data type specified as
size of the array

Cont
Valid Declaration
#define N 100
void main()
{
double x[N];
}
Here array size is defined using symbolic
constant, rather than fixed integer.

Number of array elements can also be


given by an expression.
#define N 10
int A[N+1]

Initializing One Dimensional


Array
// array of 10 uninitialized ints
int A[10];
A[3] = 1;
int x = A[3];
0
A

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

Cont
Array has multiple elements, braces
are used to denote the entire array of
values and commas are used to
separate the individual values
assigned to the elements in the array
initialization
as:
int A[10] statement
= {11,12,5,6,3,2,1,8,9,7};
0
A

11
12
5
6
3
2
1
8
9
7
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]

Cont
While initializing, the size of a onedimensional array can be omitted as:
int A[] = {11,12,5,6,3,2,1,8,9};
0
A

11
12
5
6
3
2
1
8
9
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]

Other Allowed Operations


Consider array as int A[10];
To increment the ith element
A[i]++;
A[i] += 1;
A[i] = A[i] + 1;

To add n to the ith element


A[i] += n;
A[i] = A[i] + n;

Cont
To copy the content of the ith element to
the kth element
A[k] = A[i];

To exchange the values in A[i] and A[k]


int Temp;
Temp = A[i];
A[i] = A[k];
A[k] = Temp;
Note: Variable Temp should be of same data
type as array.

Storing & Printing An Array


For reading(storing)/printing the
different elements of an array, for
loop structures are used along with
input/output statement such as
scanf() and printf()

//To accept 10 element from user and print on the


screen.
#include<stdio.h>
void main()
{
int a[10], i;
//Input Segment
printf("Enter the elements of the array");
for(i=0; i<10; i++)
scanf("%d",&a[i]);
//Output Segment
printf("\n The elements of the array are\n");
for(i=0; i<10; i++)
printf("\t%d",a[i]);
}

Other Way

#include<stdio.h>
void main()
{
int a[25], i, n;
printf("Enter the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Enter the elements of the array");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
//Output Segment
printf("\n The elements of the array are\n");
for(i=0; i<n; i++)
printf("\t%d",a[i]);
}

Example
Biggest among given n integer
number.
As n numbers are to be considered, all these elements are
read into an array (saya) and then
thebiggest/maximumamong all these is found.
To start with the very first element a[ 0 ] is assumed to be the
maximum (max).
Then thismaxiscomparedwith the elements starting from
the 2ndlocation i.e. starting from the elements at the
locationsa[1],a[ 2 ],a[ 3 ],,a[n 1], one by one.
If at any comparison stage themax is found to be smaller
than a[i] then the contents ofa[i] iscopied into maxand the
comparison process is continued till the end.
At the end the value of thebiggestelement will be available
inmax.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25],i,n,max;
clrscr();
printf("Input the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Input the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

//initially a[0] is assumed as maximum


max = a[0];
//Comparison starts with 2nd element of the array
for(i=1;i<n;i++)
{
if(max<a[i])
max = a[i];
}
printf("\nThe maximum is %d among the given elements
of the array", max);
getch();
}

Output
Input the value of n: 5
Input the array elements
12 8 14 6 3
The maximum is 14 among the given elements of the array

Example
To find the average of a given set of
n numbers.
All the given numbers are stored in an array,
saya.
Averageis found out by firstsummingall the
elements and then dividing thesumby total
number of elements n.
This process can be mathematically
represented as

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25],i,n,sum=0;
float average;
clrscr();
printf("Input the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Input the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

///finding the sum of all elements


for(i=0;i<n;i++)
sum = sum + a[i];
average = (float)sum/n;
printf("\nAverage = %.2f", average);
getch();
}
Output
Input the value of n: 5
Input the array elements
12 8 14 6 3
Average = 8.6

Example
Searching
As a set of integer elements are to be handled, it is
taken as an array, saya.
Here the problem is tosearchfor a required
element in the given array. The required element is
generally known as the search key. Let this search
key be represented by a variable calledkey.
The searching process for the key's presence in the
array starts from the beginning of the array and
continue till either thekey isavailableor till
theend of the arrayis reached. Therefore, this
method is known aslinear searchorsequential
search method.

Cont
Search key = 36

Search key = 30

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],key,i,n,flag = 0, pos= 0;
clrscr();
printf("Input the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Input the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter key number: ");
element
scanf("%d",&key);

//Reading the key

for(i=0;i<n;i++)
{
//Whether element is equal to key number or not
if(a[i] == key)
{
flag = 1;
pos = i;
break;
}
}
if(flag == 1)
printf("%d is found in position number %d",key,pos+1);
else
printf("%d is not found in the array",key);
getch();
}

Output
Input the value of n: 5
Input the array elements
12 8 14 6 3
Enter the key number: 6
6 is found in position number 4

Exercise
To find the maximum and minimum
among the given elements in an
array.
To read n integers(zero, +ve, -ve)
into an array & find count of +ve and
ve numbers.
Find mean, variance & standard
deviation of a given set of numbers.

Example
Write an algorithm to sort set of
numbers in ascending order.
Sortingis any process of arranging
elements according to a certain sequence.
Bubble Sort
Elements in consecutive locations are compared
from the beginning to the end of the array.
If they are in the required order, nothing is done
and the comparison of next set of consecutive
elements is made.

Example
One pass has put the largest element
in its place.

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25], i, n, j, temp;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Enter the elements of the array\n");
for(i=0; i<n; i++)
scanf("%d",&a[i]);

Program:
//This loop performs required no. of passes
for(i=0;i<n-1;i++)
{
//This loop performs all comparison in a pass
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1]) //Checks two adjacent
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

Program:
//Output Segment
printf("\n\n Sorted elements are\n");
for(i=0; i<n; i++)
printf("%d\t",a[i]);
getch();
}
Output:
Enter the value of n: 5
Enter the elements of the array
72965

Sorted elements are


2
5
6
7
9

Example
Write a program in c to cyclically
rotate the elements in array. Program
should accept a choice in which
direction to rotate i.e. left to right.
Depending on choice it should
perform cyclic rotation.
Suppose array A contains elements
0
A

2
3

1
2
4
5
A[0] A[1] A[2] A[3] A[4]

Cont
If choice is rotate left then output
should be
0

2
4

2
3
5
1
A[0] A[1] A[2] A[3] A[4]

If choice is0rotate
1
2
4 output
right3then
2
1
3
4
shouldAbe 5
A[0] A[1] A[2] A[3] A[4]

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[25], i, n, r, temp;
printf("Enter the value of n: ");
scanf("%d",&n);
//Input Segment
printf("Enter the elements of the array\n");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
//Choice input
printf("\n1. Left ");
printf("\n2. Right ");
printf("\nEnter rotation choice from above: ");
scanf("%d",&r);

Program:
switch(r)
{
case 1:
temp = a[0]; //Copying 1st element of array to variable.
//Loop for copying other element to proper position
for(i=1;i<n;i++)
a[i-1] = a[i];
a[n-1] = temp
break;
case 2:
temp = a[n-1]; //Copying (n-1)th element of array to variable.
//Loop for copying other element to proper position
for(i=n-1;i>0;i--)
a[i] = a[i-1];
a[0] = temp;
break;
default:
printf("\nInvalid Rotation.");
getch();
exit(0);
}

Program:
//Output Segment
printf("\n\n Sorted elements are\n");
for(i=0; i<n; i++)
printf("%d\t",a[i]);
getch();
}
Output:
Enter the value of n: 5
Enter the elements of the array: 1 2 3 4 5
1. Left to Right
2. Right to Left
Enter rotation choice from above: 1
The elements of after Rotations are:
2
3
4
5
1

Exercise
Write a program to sort list elements
in descending order.

Two Dimensional Array


Array with more than one dimensions
are called multidimensional arrays.
An array of two dimensions called
two dimensional array.
E.g. Chess board.

Two Dimensional Array


It is a collection of data elements of
same data type arranged in rows and
columns (that is, in two dimensions).
E.g.
int sales[3][5];

Declaration of 2D Array
Syntax:
<data type> <arrayName>[<array_size1>][<array_size2>]

E.g. int A[8][8];

<array_size1> & <array_size2> must be


an constant.
<array_size1> & <array_size2> are
the sizes of the arrays first and
second dimension.

Initializing 2D Array
The no. of subscript determines the
dimensionality of an array.
Two dimension can be named as
row(1st dimension) and column(2nd
dimension).
{ 1,1,
E.g.int a[3][2] = 2,4,

int a[3][2] = { {1,1}, {2,4}, {3,9}};

3,9};
int a[3][2] = { 1,1, 2,4, 3,9};
int a[ ][2] = { 1,1, 2,4, 3,9,5,6};

Accessing 2D Array
Two dimensional array is nothing but matrix.
Let A be a given matrix, having m rows and
n columns i.e. a m x n matrix

1st element of matrix is accessed as A[0][0].


Last element of matrix is accessed as A[m1][n-1].

Reading and Printing 2D


Array
The general element of this matrix is aij.
Here the first subscriptirepresents a row and
the second subscriptjrepresents a column.
This matrix could beread in row-wise, i.e. in
the ordera00,a01,a02,a10,a11and so on, or
could beread in column-wise, i.e. in the
ordera00,a10,a01,a11and so on.
But a matrix is always printed row-wise only.

#include<stdio.h>
void main()
{
int a[10][10], i, j, m, n;
printf("Enter the value of m & n: ");
scanf("%d%d",&m,&n);
//Input Segment
printf("Enter the elements of the matrix");
for(i=0; i<m; i++)
for(j=0; j<n;j++)
scanf("%d",&a[i][j]);

//Output Segment
printf("\n The elements of the array are\n");
for(i=0; i<m; i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf(\n);
}

Output:
Enter the value of m & n: 2 2
Enter the elements of the array 1 2 3 4

The elements of the array are


1

Transpose
Transpose of given matrix
LetAbe the given matrix of
sizembyn.
A [1]
Also letBis the transpose of the given
matrix. The transpose of a matrix is
obtainedby interchanging its row
elements
elements.
5 and
2 column
3
5 4 8
E.g.A = 4 7 1
B= 2 7 9
8

By comparing the two representations


ofBgiven above we see that any element
ofBi.e.bijis equal toaji.
Therefore, therelation bij= ajiis
usedrepeatedlyto generate all the elements
of the transposed matrix.
Note if the size of matrix is (mn) then the
size of its transpose will be (nm).

Program:
#include<stdio.h>
void main()
{
int a[10][10], b[10][10],i,j,m, n;
printf("Enter the value of m & n: ");
scanf("%d%d",&m,&n);
//Input Segment
printf("Enter the elements of the array");
for(i=0; i<m; i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

//Transposing
for(i=0;i<n;i++)
for(j=0;j<m;j++)
b[i][j] = a[j][i];
//Output Segment
printf("\n Transpose of Matrix A\n");
for(i=0; i<n; i++)
{
for(j=0;j<m;j++)
printf("\t%d",b[i][j]);
printf("\n");
}
}

Output:
Enter the value of m & n: 2 3
Enter the elements of the array 1 2 3 4 5 6

Transpose of Matrix A
1

Norm
Norm
By definitionnormof a matrix is
thesquare root of the sum of the
squares of all its individual elements.

Cont
Sinceall the elementsare to be considered, one
has to consider the general elementaij, whereais
a given matrix ofm rowsandn columns.
Thesquare of every elementis obtained by simply
multiplying it by itself once, i.e. by using (aij*aij).
The sum of all (aij)2is obtained by the relation:

After finding thesumthe norm is obtained by


finding the square root of thesum. using the
relation

Program:
#include<stdio.h>
void main()
{
int a[10][10], i,j,m, n,sum;
float norm;
printf("Enter the value of m & n: ");
scanf("%d%d",&m,&n);
//Input Segment
printf("Enter the elements of the array");
for(i=0; i<m; i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

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);
//Output Segment
printf("\n Norm of the given matrix is =
%.2f",norm);
}

Output:
Enter the value of m & n: 2 2
Enter the elements of the array 1 2 3 4

Norm of the given matrix is = 2.00

Matrix addition and


subtraction
In order to obtain the sum or difference of
two given matrices,the size of the given
matrices must be same.
The sum of two matrices is obtained by
summing the corresponding elements of the
given matrices.
The difference of two matrices is obtained
by finding out the difference between the
corresponding elements of the given
matrices.

If

sum
Thus every element of the sum matrix C is
obtained using the relation cij=aij+bijfor all
values ofiandj.

Difference
Thus every element of the difference
matrixDis obtained using the
relationdij=aij-bijfor all values ofiandj.

Program:
#include<stdio.h>
void main()
{
int a[10][10], b[10][10],c[10][10], i,j,m, n;
printf("Enter the value of m & n: ");
scanf("%d%d",&m,&n);
//Reading the matrix A
printf("Enter the elements of the matrix A\n");
for(i=0; i<m; i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

//Reading the matrix B


printf("Enter the elements of the matrix B\n");
for(i=0; i<m; i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
//Finding the sum
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];
//Output Segment
printf("\n Resultant Matrix C\n");
for(i=0; i<m; i++)
{
for(j=0;j<n;j++)
printf("\t%d",c[i][j]);
printf("\n");
}
}

Output:
Enter the value of m & n: 2 2
Enter the elements of the matrix A
1234
Enter the elements of the matrix B
5678
Resultant Matrix C
6
10

8
12

Matrix Multiplication/Product
of Given Two Matrix
LetAandBare two given matrices of
dimensions (mn) and (pq)
respectively.
Also letCbe theproduct matrix.
For the multiplication of given two
matrices,number of columns of the first
matrix must beequal tonumber of rows of
the second matrix, i.e.nmust be equal
top. The product matrixCwill be of size
(mq).

Let
Obviously, Ais a (2 * 3) matrix, i.e.m= 2
andn= 3
Bis a (3 3) matrix, i.e.p= 3 andq= 3
Sincen = p, multiplication is possible. The
resultantproduct matrix Cwill be amq,
i.e. 2 3 matrix.
The row elements of C are obtained as
follows:
C00 : A00 * B00 + A01*B10 + A02 * B20
C01 : A00 * B01 + A01*B11 + A02 * B21
C

:A

*B

+ A *B

+A

*B

The first subscript of A will be the first


subscript of C and the second subscript of B
will be the second subscript of C.
Observe that second subscript of A and the
first subscript of B are same and vary from 0
upto n-1. This common subscript be K.(i.e.
varies from 0 to n-1).
Since every element is a summation of certain
product terms, one has to use a variable like
sum in order to have the generated elements
summed up and stored in it.
All the elements of the product matrix C are
generated by repeating the above process for
all the values of i (0 to m-1) and j (0 to q-1).

Program:
#include<stdio.h>
void main()
{
int a[10][10], b[10][10],c[10][10], i,j,k,m, n,p,q;
printf("Enter the order of matrix A ( m & n): ");
scanf("%d%d",&m,&n);
printf("Enter the order of matrix B ( p & q): ");
scanf("%d%d",&p,&q);
if(n != p)
{
printf("\n Matrices are not multipliable");
exit(1);
}

//Reading the matrix A


printf("Enter the elements of the matrix A\n");
for(i=0; i<m; i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
//Reading the matrix B
printf("Enter the elements of the matrix B\n");
for(i=0; i<p; i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);

//Finding the product


for(i=0;i<m;i++) //For each row
{
for(j=0;j<n;j++) //For each column
{
c[i][j] = 0;
for(k=0;k<n;k++) //for each matrix element
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
//Output Segment
printf("\n Resultant Matrix C\n");
for(i=0; i<m; i++)
{
for(j=0;j<q;j++)
printf("\t%d",c[i][j]);
printf("\n");
}
}

Output:
Enter the order of matrix A ( m & n): 2 2
Enter the order of matrix B ( p & q): 2 2
Enter the elements of the matrix A
1234
Enter the elements of the matrix B
5678
Resultant Matrix C
19
43

22
50

Exercise
Write a program which will accept 2
dimensional square matrix and find out
transpose of it. Program should not make
use of another matrix.
Write a program which will accept 2
dimensional square matrix and find out
the trace of it. (traceof a matrix is given
by thesum of all the elements on its
principle diagonal. )

Vous aimerez peut-être aussi