0% found this document useful (0 votes)
23 views72 pages

Lecture 6-10

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)
23 views72 pages

Lecture 6-10

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/ 72

Arrays

Dr Lavika Goel
MNIT Jaipur
Arrays
• Arrays are data structure consisting of related data items of
the same type.
• Arrays are “static” entities in that they remain the same size
throughout program execution and can be initialised only
during the declaration time.
• Array name is a pointer to the base address of the array.
• An array is a group of contiguous memory locations
that all have the same type.
Arrays
• Any array element can be referred by giving
the array’s name followed by the position
number of the element in square brackets
([]), which is called index or subscript.
• An index must be an integer
• The first element in every array is the zeroth
element.
• An array name is like any other identifiers
• The brackets used to enclose the index of an
array are actually an operator in C.
Arrays
Arrays
Arrays
Defining Arrays
• Arrays occupy space in memory.
• The type of each element and the number of
elements each array requires are to be
specified so that the computer can reserve
the appropriate amount of memory.
• The definition int b[100] reserves 100
elements for integer array b with indices in
the ranges 0–99
• Arrays may contain other data types like char,
float, double etc.
Initializing an Array
• The elements of an array can also be initialized when
the array is defined by following the definition with an
equals sign and braces, {}, containing a comma-
separated list of array initializers
• If there are fewer initializers than elements in the
array, the remaining elements are initialized to 0
• If number of initializers assigned are more than the
size of the array, a syntax error is generated
• If the array size is omitted from a definition with an
initializer list, the size of array will be the number of
elements in the initializer list
Example 1
Example 2: Initialization using a loop
Calculating the MemoryLocation
For n+1 th element
& a[n] = a + (n x sizeof(datatype)]

For 6 th element with base address 4568


& a[5] = 4568 + (5 x sizeof(int))
4568 + 5 x 4 = 4588
Array index out ofbounds
• C has no array bounds checking to prevent the program
from referring to an element that does not exist
• An executing program can “walk off” either end of an
array without warning
• Programmer should ensure that all array references
remain within the bounds of the array
• When looping through an array, the array index should
never go below 0 and always be less than the array size
• Loop continuation condition must prevent accessing
elements outside this range
ARRAYS AND FUNCTIONS
• Possible to pass the values of an array to a function.
• To pass an array to a called function, it is sufficient to list
the name of the array without any subscripts, and the
size of the array as arguments.
• The call:
largest(a,n);
• will pass all the elements contained in the array 'a' of
size 'n'.
• The called function expecting this call must be
appropriately defined.
• The 'largest' function header is
float largest(float array[], int size)
FUNCTIONS WITH 1D ARRAYS

• The function header(largest) is defined to take two


arguments, the array name and the size of the array to
specify the number of elements in the array.
• The declaration of formal argument array is
float array[];
• The pair of brackets informs the compiler that the
arguments array is an array of numbers.
• It is not necessary to specify the size of the array
here.
FUNCTIONSWITH 1DARRAYS
• Here an array is transferred as parameter to a
function.
void main() void fun(int b[], intn)
{ {
void fun(int[],int); int x;
int a[5],n; ………….
………… ………….

fun(a,n); }
……………
}
EXAMPLE
#include<stdio.h> void add(int b[],int x)
#include<conio.h> {
int sum=0,i;
void add(int[],int);
for(i=0;i<x;i++)
void main()
sum=sum+b[i];
{
int a[5],i,n; printf("\nThe sum is: %d",sum);
}
clrscr();
OUTPUT:
printf("\n Enter theNumber: ");
Enter the Number: 5
scanf("%d",&n);
Enter the Values: 1
printf("\n Enter the Values:");
2
for(i=0;i<n;i++)
scanf("%d",&a[i]); 3
4
add(a,n);
5
}
The sum is: 15
Insertion in an array
Deleting from an array
Multi Dimensional Arrays
• Arrays in C can have multiple indices.
• A common use of multidimensional arrays is to
represent tables of values consisting of information
arranged in rows and columns.
• To identify a particular table element, we must
specify two indices: The first identifies the
element’s row and the second identifies its column
• Tables or arrays that require two indices to identify
a particular element are called two-dimensional
arrays.
Rows and Columns
Indexes in 2D arrays
Assume that the two dimensional array called val is
declared and looks like the following:
val Col 0 Col 1 Col 2 Col 3

Row 0 8 16 9 52

Row 1 3 15 27 6

Row 2 14 25 2 10

To access the cell containing 6, we reference val[1]


[3], that is, row 1, column 3.
DECLARATION
How to declare a multidimensional array?
int b[2][3];

the name of the array to be b


the type of the array elements to be int
the dimension to be 2 (two pairs of brackets [])
the number of elements or size to be 2*3 = 6
Multi Dimensional Arrays
• Every element in array a is identified by an
element name of the form a[i][j]
• a is the name of the array
• i and j are the indices that uniquely identify
each element in a
• A two-dimensional array int b[2][2] could be
defined and initialized as
int b[2][2] = {{1, 2}, {3, 4}};
• If there are not enough initializers for a given
row, the remaining elements of that row are
initialized to 0
Multi Dimensional Arrays
• The first index of a multidimensional array is
not required either, but all subsequent indices
are required.
• The compiler uses these indices to determine
the locations in memory of elements in
multidimensional arrays.
INITIALIZATION
How to initialize a Two-Dimensional array?
Initialized directly in the declaration statement
int b[2][3] = {51, 52, 53, 54, 55, 56};
b[0][0] = 51; b[0][1] = 52; b[0][2] = 53;
Use braces to separate rows in 2-D arrays.
int c[4][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
int c[ ][3] = {{1, 2, 3}, {4, 5, 6},{7, 8,9},{10, 11, 12}};
Implicitly declares the number of rows to be 4.
Multi Dimensional Arrays
• All array elements are stored consecutively
in memory regardless of the number of
indices.
• In a two-dimensional array, the first row is
stored in memory followed by the second
row. In a two-dimensional array, each row is
basically a one-dimensional array.
• To locate an element in a particular row, the
compiler must know how many elements are
in each row so that it can skip the proper
number of memory locations when accessing
the array
Memory Location
Calculating the MemoryLocation
For m x n matrix
& a[i][j] =
a + [(i x n + j) x size of(datatype)]

For 3 x 3 int matrix, a with base address 4568


& a[2][1] =
4568 + [(2 x 3 + 1) x sizeof(int)]
4568 + 7 x 4 = 4596
Declaration Statement
Multi Dimensional Arrays
• Many common array manipulations use for
iteration statements

for (int col = 0; col < 3; ++col)


a[2][col] = 0;

total = 0;
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 3; ++col)
total += a[row][col];
Multidimensional Array
C programming language allows multidimensional
arrays. Here is the general form of a multidimensional
array declaration −

type name[size1][size2]...[sizeN];

For example, the following declaration creates a


three dimensional integer array −

int threedim[5][10][4];
Two dimensional Array
Matrix Addition
Matrix Multiplication
Matrix Addition in C
Matrix Multiplication

Matrix multiplication
Matrix Multiplication
If matrix 1 =
123
456
789
And matrix 2 =
987
654
321
Product of both matrices =
30 24 18
84 69 54
138 114 90
FUNCTIONS WITH 2D ARRAYS

• Can also pass multi-dimensional arrays to functions.


The rules are:
– The function must be called by passing only the
array name.
– In the function definition, we must indicate that the
array has two-dimensions by including two sets of
brackets.
– The size of the second dimension must be specified.
– The prototype declaration should be similar
to the function header.
PROGRAM
main() float average(int x[][N], int M,int N)
{ {
int M=3,N=2; int i, j;
float average(int [][N],int, int); float sum = 0.0;
float mean; for(i=0; i<M; i++)
int matrix[M][N] = {{1,2}, for(j=0; j<N; j++)
{3,4}, {5,6} }; sum+=x[i][j];
mean = average(matrix, M, N); return(sum/(M*N));
} }
Pointers and Arrays
• When an array is declared, compiler
allocates a base address and sufficient
amount of storage.
• The base address is the location of the first
element (index 0) of the array
• For int x[5], *p; p = x;
x = &x[0]
• *(p+3) = x[3]
Example
• Consider the declaration:
int x[5] = {1, 2, 3, 4, 5} ;
• Suppose that the base address of x is 2500, and
each integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
Contd.
x &x[0] 2500 ;

• p = x; and p = &x[0]; are equivalent.


• We can access successive values of x by using
p++ or p- - to move from one element to
another.
• Relationship between p and x:
p = &x[0] = 2500
p+1 = &x[1] = 2504
*(p+i) gives the
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512 value of x[i]

p+4 = &x[4] = 2516


Example: function to find average
int *p
#include <stdio.h> float avg (int array[ ],int size)
main() {
{ int *p, i , sum = 0;
int x[100], k, n ;
p = array ;
scanf (“%d”, &n) ; array[i]
for (i=0; i<size; i++)
for (k=0; k<n; k++) sum = sum + *(p+i);
scanf (“%d”, &x[k]) ;
return ((float) sum / size);
printf (“\nAverage is %f”, }
avg (x, n));
}
Pointers and Arrays
• int (*p)[10];
p is a pointer that points to an array of 10
integers
• int *p[10];
p is an array of 10 integer pointers
Pointer to integer v/s pointer to array of
integers
Explanation
Size of pointer to an array
Explanation
Pointers and 2 DArray
Pointers and 2 DArray
Pointers and 2 DArray
Pointers and 2 DArray
• arr is an array of 3 elements each of which is
a 1D array of 4 integers.
Pointers and 2 D Array
Pointers and 2D arrays
Pointers and 2D arrays
Pointers and 2 DArray
• int a[3][3]; //a = &a[0][0];

• a[i] *(a+i)
• a[i][j] *(*(a+i)+j)
Example
Output
Array of pointers
Example
Array of structures
Initialising array of structures

You might also like