0% found this document useful (0 votes)
34 views53 pages

Arrays

all about Arrays program

Uploaded by

Ankit Nobi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views53 pages

Arrays

all about Arrays program

Uploaded by

Ankit Nobi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 53

ARRAYS

1
ARRAY
Many applications require processing of multiple data 
items that have common characteristics
In mathematics, we often express such groups of data items 
in indexed form:
x1, x2, x3, …, xn
Array  is  a  data  structure  which  can  represent  a 
collection of  data items which  have the same data type 
(float/int/char/…) 

2
EXAMPLE: PRINTING NUMBERS IN 
REVERSE 
4 numbers
3 numbers
int a, b, c, d;
int a, b, c; scanf(“%d”, &a);
scanf(“%d”, &a); scanf(“%d”, &b);
scanf(“%d”, &b); scanf(“%d”, &c);
scanf(“%d”, &c); scanf(“%d”, &d);
printf(“%d ”, c); printf(“%d ”, d);
printf(“%d ”, b); printf(“%d ”, c);
printf(“%d \n”, a); printf(“%d ”, b);
printf(“%d \n”, a);
3
THE PROBLEM
Suppose we have 10 numbers to handle
Or 20
Or 100
Where do we store the numbers ?  Use 100 variables ?? 
How to tackle this problem?
Solution:
Use arrays

4
PRINTING IN REVERSE USING ARRAYS

int main()
{
     int n, A[100], i;
 printf(“How many numbers to read?” );
     scanf(“%d”, &n); Expected value of n is between 1 to 100
Execute the loop starting from 0 to n-1 with
     for (i = 0; i < n; ++i) step size 1
scanf(“%d”, &A[i]); Store n numbers in A[0]…A[n-1]
     for (i = n ­1; i >= 0; ­­i) Execute the loop starting from n-1 to 0 with
step size 1
printf(“%d  ”, A[i]);
     printf(“\n”);
     return 0;
}
5
USING ARRAYS
All the data items constituting the group 
share the same name
int  x[10];
Individual elements are accessed by 
specifying the index

x[0] x[1] x[2] x[9]

X is a 10-element one 6
dimensional array
A FIRST EXAMPLE
int main()
{ “data refers to a block of 10
int i; integer variables, data[0], data[1],
int data[10]; …, data[9]
for (i=0; i<10; i++)
data[i]= i;
i=0;
while (i<10)
{
printf("Data[%d] = %d\n", i, data[i]);
i++;
}
return 0;
} 7
THE RESULT
Array size should be a constant

int main()
Output
{
int i; Data[0] = 0
int data[10]; Data[1] = 1
for (i=0; i<10; i++) Data[2] = 2
data[i]= i; Data[3] = 3
i=0;
Data[4] = 4
while (i<10)
{ Data[5] = 5

printf("Data[%d] = %d\n", i, data[i]); Data[6] = 6


i++; Data[7] = 7
} Data[8] = 8 8
return 0;
Data[9] = 9
}
DEFINING AN ARRAY

Like variables, the arrays used in a program must be 
declared before they are used
General syntax:
     storage­class type   array­name [size];
storage­class refers to the storage class of the array.
type specifies the type of element that will be 
contained in the array (int, float, char, etc.)
size is an integer constant which indicates the 
maximum number of elements that can be stored 
inside the array
Examples: marks is an array that can store a 
maximum of 5 integers

int marks[5], char text [80], static char message [25], 9


static float n[12].
Examples:
    int  x[10];
    char  line[80];
    float  points[150];
    char  name[35];
If we are not sure of the exact size of the 
array, we can define an array of a large size
    int   marks[50];
    though in a particular run we may only be 
using, say, 10 elements

10
ACCESSING ARRAY ELEMENTS
A particular element of the array can be 
accessed by specifying two things:
Name of the array
Index (relative position) of the element in the array
In C, the index of an array starts from zero
Example:
An array is defined as    int  x[10];
The first element of the array x can be accessed as x[0], 
fourth element as x[3], tenth element as x[9], etc.

11
CONTD.
 The array index must evaluate to an integer between 0 and 
n­1 where n is the maximum number of elements possible in 
the array
    a[x+2] = 25;
    b[3*x­y] = a[10­x] + 5;
 Remember that each array element is a variable in itself, and 
can be used anywhere a variable can be used (in expressions, 
assignments, conditions,…)

12
HOW IS AN ARRAY STORED IN 
MEMORY?

Starting from a given memory location, the 
successive array elements are allocated space 
in consecutive memory locations

Array a
x: starting address of the array in memory
k: number of bytes allocated per array element
a[i]  is allocated memory location at address  x + i*k

13
STORAGE Output
&Data[0] = 3221224480
&Data[1] = 3221224484

int main() &Data[2] = 3221224488


{ &Data[3] = 3221224492
int i;
&Data[4] = 3221224496
int data[10];
for(i=0; i<10; i++) &Data[5] = 3221224500
printf("&Data[%d] = %u\n", i, &data[i]); &Data[6] = 3221224504
return 0; &Data[7] = 3221224508
}
&Data[8] = 3221224512
&Data[9] = 3221224516
14
INITIALIZATION OF ARRAYS
General form:
   type   array_name[size]  =  { list of values };
Examples:
   int  marks[5] = {72, 83, 65, 80, 76};
The size may be omitted. In such cases the 
compiler automatically allocates enough space 
for all initialized elements
         int   flag[ ] = {1, 1, 1, 0};

15
HOW TO READ THE ELEMENTS OF 
AN ARRAY?
By reading them one element at a time
    for  (j=0; j<25; j++)
        scanf  (“%f”, &a[j]);

The ampersand (&) is necessary
The elements can be entered all in one 
line or in different lines

16
A WARNING
In C, while accessing array elements, 
array bounds are not checked
Example:
int   marks[5];
:
:
marks[8] = 75;
The above assignment would not necessarily cause an 
error
Rather, it may result in unpredictable program 
results

17
READING INTO AN ARRAY
#define MAX_SIZE 100
int main()
{
int i, size; Output
float marks[MAX_SIZE];
float total; 4
scanf("%d",&size); 2.5
for (i=0, total=0; i<size; i++)
{ 3.5
scanf("%f",&marks[i]);
4.5
total = total + marks[i];
} 5
printf("Total = %f \n Avg = %f\n", total, total/size);
return 0;
Total = 15.500000
} Avg = 3.875000
18
HOW TO PRINT THE ELEMENTS OF 
AN ARRAY?
By printing them one element at a time
           for  (j=0; j<25; j++)
               printf  (“\n %f”, a[j]);
The elements are printed one per line
           printf  (“\n”);
           for  (j=0; j<25; j++)
               printf (“ %f”, a[j]);
The elements are printed all in one line (starting with 
a new line)

19
HOW TO COPY THE ELEMENTS OF ONE 
ARRAY TO ANOTHER?
 By copying individual elements
    for  (j=0; j<25; j++)
        a[j] = b[j];
 The element assignments will follow the rules of assignment 
expressions
 Destination array must have sufficient size

20
EXAMPLE 1:  FIND THE MINIMUM OF A SET OF 10 
NUMBERS

#define size 10

int main()
{
int a[size], i, min;

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


scanf (“%d”, &a[i]);

min = a[0];
for (i=1; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min); 21

return 0;
}
EXAMPLE 2: COMPUTING GPA 

SubjectNo gradePt credit


1 75 6
2 60 8
3 87 8
4 80 3
n
gradeSum= ∑ gradePt [i ]×credit [i ]
i=1
n
creditSum= ∑ credit [ i]
i= 1
gradeSum
gpa= 22
creditSum
#define nsub 6;

EXAMPLE 2: int main()


COMPUTING  {
GPA  int grade_pt[nsub], cred[nsub], i,
gp_sum=0, cred_sum=0;
double gpa;

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


scanf (“%d %d”, &grade_pt[i], &cred[i]);
Handling two arrays
at the same time
for (i=0; i<nsub; i++)
{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa = ((float) gp_sum) / cred_sum;
printf (“\n Grade point average: is %.2lf”, gpa);
23
return 0;
}
EXAMPLE: BINARY SEARCH
Searching for an element k in a sorted array A with 
n elements
Idea:
Choose the middle element A[n/2]
If k == A[n/2], we are done
If k < A[n/2], search for k between A[0] and A[n/2 ­1]
If k > A[n/2], search for k between A[n/2 + 1] and A[n­1]
Repeat until either k is found, or no more elements to 
search
Requires less number of comparisons than linear 
search

24
int main() {
    int A[100], n, k, i, mid, low, high;
    scanf(“%d %d”, &n, &k);
    for (i=0; i<n; ++i) scanf(“%d”, &A[i]);
    low = 0; high = n – 1; mid = low + (high – low)/2;
    while (high >= low) {
          printf(“low = %d, high = %d, mid = %d, A[%d] = %d\n”, low, high, 
mid, mid, A[mid]);
      if (A[mid] == k) {
  printf(“%d is found\n”, k);
          break;
           }
           if (k < A[mid]) high = mid – 1;
           else low = mid + 1;
           mid = low + (high – low)/2;
    }
   if (high < low) printf(“%d is not found\n”, k);
   return 0; 25

}
Sample Input Output
n
k
A[]
8  21
9  11  14  17  19  20  23  27
low = 0, high = 7, mid = 3, A[3] = 17
low = 4, high = 7, mid = 5, A[5] = 20
low = 6, high = 7, mid = 6, A[6] = 23
21 is not found

8 14
9 11 14 17 19 20 23 27
low = 0, high = 7, mid = 3, A[3] = 17
low = 0, high = 2, mid = 1, A[1] = 11
low = 2, high = 2, mid = 2, A[2] = 1426
14 is found
THINGS YOU CANNOT DO WITH 
ARRAYS
You cannot
use = to assign one array variable to another
    a = b;   /* a and b are arrays */
use == to directly compare array variables
   if  (a = = b)  ………..
directly scanf or printf arrays*
   printf (“……”, a);
*Note:You can use scanf and printf on 
some character arrays
27
PASSING ARRAYS TO FUNCTIONS
Array element can be passed to functions as 
ordinary arguments
IsFactor (x[i], x[0]) 
sin (x[5])

28
PASSING ENTIRE ARRAY TO A 
FUNCTION

An array name can be used as an argument to a 
function
Permits the entire array to be passed to the 
function
The way it is passed differs from that for ordinary 
variables
Rules:
The array name must appear by itself as 
argument, without brackets or subscripts
The corresponding formal argument is written in 
the same manner 29

Declared by writing the array name with a pair 
of empty brackets
WHOLE ARRAY AS PARAMETERS
#define ASIZE  5
float average (int B[ ]) Only Array Name/address passed.
{ [ ] mentioned to indicate that
int i, total=0; is an array.
for (i=0; i<ASIZE; i++)
total = total + B[i];
return ((float) total / (float) ASIZE);
}
void main ( )  {
int x[ASIZE] = {10, 20, 30, 40, 50};
   float x_avg; 
x_avg = average (x) ;
} 30

Called only with actual array name


CONTD. void main()
{
int n;
We don’t need to
float list[100], avg;
write the array size.
:
It works with arrays
avg = average (n, list);
of any size.
:
}

float average (int a, float x[])


{
:
sum = sum + x[i];
}
31
ARRAYS USED AS OUTPUT PARAMETERS
void VectorSum (int a[ ], int b[ ], int vsum[ ], int length) {
int i;
for (i=0; i<length; i=i+1)
vsum[i] = a[i] + b[i] ;
}
void PrintVector (int a[ ], int length)  {
int i;
for (i=0; i<length; i++) printf (“%d “, a[i]);
}

void main ()  {
int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3];
VectorSum (x, y, z, 3) ;
PrintVector (z, 3) ; 32

}
THE ACTUAL MECHANISM

When an array is passed to a function, the 
values of the array elements are not passed to 
the function
The array name is interpreted as the address 
of the first array element
The formal argument therefore becomes a 
pointer to the first array element
When an array element is accessed inside the 
function, the address is calculated using the 
formula stated before
Changes made inside the function are thus 
also reflected in the calling program 33
CONTD.
Passing parameters in this way is called 
        call­by­reference
Basically what does it mean?
If a function changes the values of array 
elements, then these changes will be made 
to the original array that is passed to the 
function
This does not apply when an individual 
element is passed as an argument

34
TWO DIMENSIONAL ARRAYS
We have seen that an array variable can store a 
list of values
Many applications require us to store a table of 
values

Subject 1 Subject 2 Subject 3 Subject 4 Subject 5


Student 1 75 82 90 65 76
Student 2
68 75 80 70 72
Student 3
88 74 85 76 80
Student 4
50 65 68 40 70 35
CONTD.
The table contains a total of 20 values, five in each line
The table can be regarded as a matrix consisting of four 
rows and five columns
C allows us to define such tables of items by using two­
dimensional arrays

36
DECLARING 2­D ARRAYS
General form:
   storage­class type   array_name [row_size][column_size];
Examples:
   int  marks[4][5];
   float  sales[12][25];
   double  matrix[100][100];

37
INITIALIZING 2­D ARRAYS
int a[2][3] =  {1,2,3,4,5,6};
int a[2][3] = {{1,2,3}, {4,5,6}};
int a[][3]   = {{1,2,3}, {4,5,6}};

All of the above will give the 2x3 array

1    2    3
         4    5    6

38
ACCESSING ELEMENTS OF A 2­D 
ARRAY
Similar to that for 1­d array, but use two indices
First indicates row, second indicates column
Both the indices should be expressions which evaluate 
to integer values (within range of the sizes mentioned 
in the array declaration)
Examples:
   x[m][n] = 0;
   c[i][k] += a[i][j] * b[j][k];
   a = sqrt (a[j*3][k]); 

39
EXAMPLE

int a[3][5];

A two-dimensional array of 15 elements


Can be looked upon as a table of 3 rows and 5 columns

col0 col1 col2 col3 col4


row0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]
row1 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]
row2 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]

40
HOW A 2­D ARRAY IS STORED IN 
MEMORY?

Starting from a given memory location, the elements are 
stored row­wise in consecutive memory locations (row­major 
order)
• x: starting address of the array in memory
• c: number of columns
• k: number of bytes allocated per array element
a[i][j]  is allocated memory location at  
                   address  x + (i * c + j) * k

a[0][0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]

Row 0 Row 1 Row 2 41


Output
ARRAY ADDRESSES
3221224480
int main()
3221224484
{ 3221224488
int a[3][5]; 3221224492
3221224496
int i,j;
3221224500
for (i=0; i<3;i++) 3221224504
3221224508
{
3221224512
for (j=0; j<5; j++) printf("%u\n", &a[i][j]); 3221224516
printf("\n");
3221224520
}
3221224524
return 0; 3221224528
} 3221224532
3221224536 42
HOW TO READ INTO THE ELEMENTS 
OF A 2­D ARRAY?
By reading them one element at a time
    for  (i=0; i<nrow; i++)
        for  (j=0; j<ncol; j++)
            scanf  (“%f”, &a[i][j]);
The ampersand (&) is necessary
The elements can be entered all in one line or in 
different lines

43
HOW TO PRINT THE ELEMENTS OF 
A 2­D ARRAY?
By printing them one element at a time
            for  (i=0; i<nrow; i++) 
                for  (j=0; j<ncol; j++)
                    printf  (“\n %f”, a[i][j]);
The elements are printed one per line

 for  (i=0; i<nrow; i++) 
                for  (j=0; j<ncol; j++)
                    printf  (“%f”, a[i][j]);
The elements are all printed on the same line

44
CONTD.
           for  (i=0; i<nrow; i++)
           {
               printf  (“\n”);
               for  (j=0; j<ncol; j++)
                   printf (“%f   ”, a[i][j]);
            }
The elements are printed nicely in matrix form

45
EXAMPLE: MATRIX ADDITION
int main()
{ for (p=0; p<m; p++)
int a[100][100], b[100][100], for (q=0; q<n; q++)
c[100][100], p, q, m, n; c[p][q] = a[p][q] + b[p][q];

scanf (“%d %d”, &m, &n); for (p=0; p<m; p++)


{
for (p=0; p<m; p++) printf (“\n”);
for (q=0; q<n; q++) for (q=0; q<n; q++)
scanf (“%d”, &a[p][q]);
printf (“%d ”, c[p][q]);
for (p=0; p<m; p++) }
for (q=0; q<n; q++) return 0;
scanf (“%d”, &b[p][q]); }
46
PASSING 2­D ARRAYS AS 
PARAMETERS
Similar to that for 1­D arrays
The array contents are not copied into the function
Rather, the address of the first element is passed
For calculating the address of an element in a 2­d 
array, we need:
The starting address of the array in memory
Number of bytes per element
Number of columns in the array
The above three pieces of information must be known 
to the function
47
EXAMPLE USAGE
void add (int x[][25], int y[][25],
int rows, int cols)
int main() {
{ :
int a[15][25], b[15]25]; }
:
:
add (a, b, 15, 25);
: We can also write
}
int x[15][25], y[15][25];
But at least the 2nd dimension
must be given
48
MULTIDIMENSIONAL ARRAYS

 A multidimensional array can be written as 
  storage­class  data­type   array_name [expression1]
[expression2] … [expression n] ; 
         

49
MULTIDIMENSIONAL ARRAYS
Examples:
  int t[10][20][30] = {
                                     {               /* table 1 */
                                       {1, 2, 3, 4},        /* row 1 */
                                       {5, 6, 7, 8},        /* row 2 */
                                       {9, 10, 11, 12}  /* row 3 */
                                     },
       {              /* table 2 */
                                       {21, 22, 23, 24},    /* row 1 */
                                       {25, 26, 27, 28},    /* row 2 */
                                       {29, 30, 31, 32}     /* row 3 */
                                     }
                                  }
This is an array of 10 tables, each having 20 rows and 30  50
columns. The rest of  the elements will be assigned to 0.
Arrays in Multifile programs
file1.c file2.c
int c[] = {1,2,3}; /* External extern int c[] ;/* External array
array definition */ declaration */

float f[] = {4,5,6.0}; extern float f[];

int main (){ int fun(){


…. c[2]= 5;
return 0; return 0;
} }

Array sizes are not specified in file1.c as the arrays are initialised

Array sizes are not specified in file2.c as they have already been specified.

51
 END

52
MORE ON ARRAY ADDRESSES
int main()
{
int a[3][5];
printf("a = %u\n", a);
Output
printf("&a[0][0] = %u\n", &a[0][0]);
printf("&a[2][3] = %u\n", &a[2][3]); a = 3221224480
printf("a[2]+3 = %u\n", a[2]+3); &a[0][0] = 3221224480
printf("*(a+2)+3 = %u\n", *(a+2)+3); &a[2][3] = 3221224532
a[2]+3 = 3221224532
printf("*(a+2) = %u\n", *(a+2)); *(a+2)+3 = 3221224532
printf("a[2] = %u\n", a[2]); *(a+2) = 3221224520
printf("&a[2][0] = %u\n", &a[2][0]); a[2] = 3221224520
&a[2][0] = 3221224520
printf("(a+2) = %u\n", (a+2)); (a+2) = 3221224520
printf("&a[2] = %u\n", &a[2]); &a[2] = 3221224520
53
return 0;
}

You might also like