0% found this document useful (0 votes)
19 views32 pages

_ARRAYS_2

The document provides an overview of 1D and 2D arrays in programming, including their definitions, declarations, and usage in C. It explains how to declare arrays, initialize them, and pass them to functions, as well as the differences between passing entire arrays and individual elements. Additionally, it covers the structure of 2D arrays, their memory representation, and methods for calculating the address of elements in both row-major and column-major order.

Uploaded by

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

_ARRAYS_2

The document provides an overview of 1D and 2D arrays in programming, including their definitions, declarations, and usage in C. It explains how to declare arrays, initialize them, and pass them to functions, as well as the differences between passing entire arrays and individual elements. Additionally, it covers the structure of 2D arrays, their memory representation, and methods for calculating the address of elements in both row-major and column-major order.

Uploaded by

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

1

Arrays 1D and 2D
2

Introduction
• Arrays
– Structures of related data items
– Static entity – same size throughout the program
– Dynamic data structures
3
Name of array (Note that all

Arrays elements of this array have the


same name, c)

• Array
– Group of consecutive memory locations
– Same name and type c[0] -45
c[1] 6
• To refer to an element, specify c[2] 0
c[3] 72
– Array name c[4] 1543
– Position number c[5] -89
c[6] 0
• Format: c[7] 62

arrayname[ position number ] c[8] -3


c[9] 1
– First element at position 0 c[10] 6453
– n element array named c: c[11] 78

• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Position number of the
element within array c
4

Arrays
• Array elements are like normal variables
c[ 0 ] = 3;
printf( "%d", c[ 0 ] );
– Perform operations in subscript. If x equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
5

Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array ( data type )
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
6

Examples Using Arrays


• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced syntax error
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array

Exercise : Histogram
1 /* Fig. 6.8: fig06_08.c
7
2 Histogram printing program */
Outline
3 #include <stdio.h>
4 #define SIZE 10
5
1. Initialize array
6 int main()
7 {
2. Loop
8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
9 int i, j;
10 3. Print
11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );
12
13 for ( i = 0; i <= SIZE - 1; i++ ) {
14 printf( "%7d%13d ", i, n[ i ]) ;
15
16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */
17 printf( "%c", '*' );
18
19 printf( "\n" );
20 }
21
22 return 0;
23 }
8
Element Value Histogram
Outline
0 19 *******************
1 3 ***
2 15 ***************
Program Output
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *
9

Examples Using Arrays


• Character arrays
– String “first” is really a static array of characters
– Character arrays can be initialized using string literals
char string1[] = "first";
• Null character '\0' terminates strings
• string1 actually has 6 elements
– It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
– Can access individual characters
string1[ 3 ] is character ‘s’
– Array name is address of array, so & not needed for scanf
scanf( "%s", string2 );
• Reads characters until whitespace encountered
• Can write beyond end of array, be careful
1 /* Fig. 6.10: fig06_10.c 10
2 Treating character arrays as strings */ Outline
3 #include <stdio.h>
4 1. Initialize strings
5 int main()
6 {
2. Print strings
7 char string1[ 20 ], string2[] = "string literal";
8 int i;
2.1 Define loop
9
10 printf(" Enter a string: ");
11 scanf( "%s", string1 ); 2.2 Print
12 printf( "string1 is: %s\nstring2: is %s\n"
characters
13 "string1 with spaces between characters is:\n", individually
14 string1, string2 );
15 2.3 Input string
16 for ( i = 0; string1[ i ] != '\0'; i++ )
17 printf( "%c ", string1[ i ] ); 3. Print string
18
19 printf( "\n" );
20 return 0;
21 }
Enter a string: Hello there
string1 is: Hello
string2 is: string literal
string1 with spaces between characters is: Program Output
H e l l o
11

Passing Arrays to Functions


• Passing arrays
– To pass an array argument to a function, specify the name of
the array without any brackets
int myArray[ 24 ];
myFunction( myArray, 24 );
• Array size usually passed to function
– Arrays passed call-by-reference
– Name of array is address of first element
– Function knows where the array is stored
• Modifies original memory locations
• Passing array elements
– Passed by call-by-value
– Pass subscripted name (i.e., myArray[ 3 ]) to function
1 /* Fig. 6.13: fig06_13.c
12
2 Passing arrays and individual array elements to functions */

3 #include <stdio.h>
Outline
4 #define SIZE 5

6 void modifyArray( int [], int ); /* appears strange */ 1. Function


7 void modifyElement( int ); definitions
8

9 int main()

10 {
2. Pass array to a
11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; function
12

13 printf( "Effects of passing entire array call "

14 "by reference:\n\nThe values of the "


2.1 Pass array
15 "original array are:\n" );
element to a
16 function
17 for ( i = 0; i <= SIZE - 1; i++ )
Entire arrays passed call-by-
18 printf( "%3d", a[ i ] ); reference, and can be modified
19
3. Print
20 printf( "\n" );

21 modifyArray( a, SIZE ); /* passed call by reference */

22 printf( "The values of the modified array are:\n" );

23

24 for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-by-


25 printf( "%3d", a[ i ] );
value, and cannot be modified
26

27 printf( "\n\n\nEffects of passing array element call "

28 "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] );

29 modifyElement( a[ 3 ] );

30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );

31 return 0;

32 }
33 13
34 void modifyArray( int b[], int size ) Outline
35 {
36 int j; 3.1 Function
37
definitions
38 for ( j = 0; j <= size - 1; j++ )
39 b[ j ] *= 2;
40 }
41
42 void modifyElement( int e )
43 {
44 printf( "Value in modifyElement is %d\n", e *= 2 );
45 }

Effects of passing entire array call by reference:

The values of the original array are:


0 1 2 3 4 Program Output
The values of the modified array are:
0 2 4 6 8

Effects of passing array element call by value:

The value of a[3] is 6


Value in modifyElement is 12
The value of a[3] is 6
Arrays
• Arrays in C
– int list[5], *plist[5];
– list[5]: (five integers) list[0], list[1], list[2], list[3], list[4]
– *plist[5]: (five pointers to integers)
• plist[0], plist[1], plist[2], plist[3], plist[4]
– implementation of 1-D array
list[0] base address = 
list[1]  + sizeof(int)
list[2]  + 2*sizeof(int)
list[3]  + 3*sizeof(int)
list[4]  + 4*sizeof(int)
Arrays

• Arrays in C (cont’d)
– Compare int *list1 and int list2[5] in C.
Same: list1 and list2 are pointers.
Difference: list2 reserves five locations.
– Notations:
list2 - a pointer to list2[0]
(list2 + i) - a pointer to list2[i] (&list2[i])
*(list2 + i) - list2[i]
16

• int A[5]={ 5,4,6,8,9},i;


• for (i=0;i<5;i++)
• {
• printf(“%d %d ”,*(a+i), *(i+a))
• }
17
2D Array

• 2D array can be defined as an array of arrays.


• The 2D array is organized as matrices which can
be represented as the collection of rows and
columns.
• However, 2D arrays are created to implement a
relational database look alike data structure.
• It provides ease of holding bulk of data at once
which can be passed to any number of functions
wherever required.
18

• int arr[max_rows][max_columns];
• however, It produces the data structure which
looks like following.
19
• Access 2D arrray
– we can store the value stored in any particular cell of a 2D array to some
variable x by using the following syntax.
– int x = a[i][j];
• Initialize
– declare and initialize the 2D array is given as follows.
– int arr[2][2] = {0,1,2,3};
#include <stdio.h>
void main ()
{
printf("\n printing the elements ....\
int arr[3][3],i,j;
n");
for (i=0;i<3;i++)
for(i=0;i<3;i++)
{
{
for (j=0;j<3;j++)
printf("\n");
{
printf("Enter a[%d][%d]: ",i,j);
for (j=0;j<3;j++)
scanf("%d",&arr[i][j]);
{
} printf("%d\t",arr[i][j]);
} }
}
}
20
Mapping 2D array to 1D array
21
Row Major ordering

• first, the 1st row of the array is stored into the


memory completely, then the 2nd row of the array
is stored into the memory completely and so on till
the last row
22
Column Major ordering

• first, the 1st column of the array is stored into the


memory completely, then the 2nd row of the array
is stored into the memory completely and so on till
the last column of the array.
23
Calculating the Address of the random
element of a 2D array
• By Row Major Order
– If array is declared by a[m][n] where m is the number of rows
while n is the number of columns, then address of an element a[i]
[j] of the array stored in row major order is calculated as,
– Address(a[i][j]) = BA. + ((i * n) + j) * size
– where, BA. is the base address or the address of the first element
of the array a[0][0]
24
Example :

• LOC (A [i, j]) = base_address + W [N * i + j]


• Here,
• base_address = address of the first element in the array.
• W = Word size, means a number of bytes occupied by each element
of an Array.
• M = Number of rows in the array.
• N = Number of columns in the array.
• Note: Array Index starts from 0.
• Suppose we want to calculate the address of element A [1, 2] and the
matrix is of 2*4. It can be calculated as follow:
Here,
base_address = 1000, W= 2, M=2, N=4, i=1, j=2
LOC (A [i, j]) = base_address + W * [(N*i) + j]
LOC (A[2, 3]) = 1000 + 2 *[4*(1) + 2]
= 1000 + 2 * [4 + 2]
= 1000 + 2 * 6
= 1000 + 12
= 1012
25

• By Column major order


– If array is declared by a[m][n] where m is the number of rows while
n is the number of columns, then address of an element a[i][j] of the
array stored in row major order is calculated as,
– Address(a[i][j]) = BA + ((j*m)+i)*Size
– where BA is the base address of the array.
• Example :
26
• The Location of element A[i, j] can be obtained by evaluating expression:
• LOC (A [i, j]) = base_address + W * [M * j + i]
• Here,
• base_address = address of the first element in the array.
• W = Word size means a number of bytes occupied by each element of an Array.
• M = Number of rows in the array.
• N = Number of columns in the array.
• Note: Array Index starts from 0.
• Here we have taken a 2-D array A [2, 4] which has 2 rows and 4 columns.
• Suppose we want to calculate the address of element A [1, 2] in column-major order and
the matrix is 2*4. It can be calculated as follow:
• Now to calculate the base address of any index using column-major order we can use the
process given below.
• It can be calculated as follow:
Here,
base_address = 2000, W= 2, M=2, N=4, i=1, j=2
LOC (A [i, j]) = base_address + W [M * j + i ]
LOC (A[1, 2]) = 2000 + 2 [2*2 + 1]
= 2000 + 2 * [4 + 1]
= 2000 + 2 * 5
= 2000 + 10
= 2010

27
28
• Let’s say there’s a class of 30 students, and we
want to store their grades for each of their courses
(six courses in total).
• Is there a way we can map all this information
using the knowledge we have covered so far? Yes,
we can!
29
Three-Dimensional Array
30

Advantages
31

Disadvantages
32

Applications of Arrays
• Apart from being widely used in programming,
arrays have additional applications as well:

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