0% found this document useful (0 votes)
8 views29 pages

Understanding Arrays in C and MATLAB

Uploaded by

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

Understanding Arrays in C and MATLAB

Uploaded by

Mohammed Ayman
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Lecture 5A: Arrays

Content
I. Definition of Array
II. 1‐D Arrays
III Arrays and Functions
IV. 2‐D Arrays
V. Multidimensional Arrays
Appendix
I. Definition of Array
• Array is a collection of a fixed number of elements of the same data type
− Common identifier (name)
− Stored sequentially in the memory (contiguous allocation)

•It is a powerful data structure for grouping alike variables for easy access

• Although C and MATLAB arrays are based on the same computer science
concept, the syntax is very different

All variables in MATLAB are arrays


Vect = [ 4 7 2 6 5 ]; % create a 1‐D array with 5 elements
numel(Vect) % obtain the number of elements in the array vect
X = Vect(2); % get the 2nd element and assign it to a scalar

Arrays in C programs must be declared before they can be used


int vect[5] = { 4, 7, 2, 6, 5 }; /*declare a 1‐D array with 5 elements*/
int x = vect[0]; /* get the 1st element (its index is 0) and assign it to a variable */
The first array element has index 0
II. 1‐ D Array: Declaration
Syntax:
/* declaration of an array without initialization */
OPTIONAL
type arrayName[ numberOfElements ];

/* declaration of an array with initialization */


type arrayName[ numberOfElements ] = {list of values};

type - any basic data type arrayName numberOfElements:


int, double, float a valid C identifier A numeric or a symbolic
char, short … constant

Examples:
#define SIZE 32
. . . .
float amplitude[SIZE]; /* declared without initialization */
char letters[3] = {‘A’, ’E’, ‘I’}; /* declared and initialized */
int numbers[] = {6, 35, 128}; /* declared and initialized, array size
is determined automatically [3] */
int number [];
…Continued
• Arrays must be declared with a fixed number of elements
according to C89 version but not the latest

/*-----Declaration----*/
int itemsInStock[5]; /* size is a numeric constant */
/* OK, but not convenient */
or
#define SIZE 5 /* easy to change when needed */
. . .
int itemsInStock[SIZE]; /* size is a symbolic constant*/

int size = 5;
int itemsInStock[size]; /* size is not a constant */
/* not supported by C89 */ 13
1-D Array Access
• Individual variables in an array are called elements
• Elements in an array are accessed via indexing
• To access an individual element you need to specify its index
double x[8]; /* array declaration. 8 is the size */

. . . .
x[0] = 12.0; /* access an element. 0 is an index */
x[2] = 6.0; /* access an element. 2 is an index */
. . .
x[7] = 3.5; /* access an element. 7 is an index */

x : x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]


12.0 6.0 3.5

index: 0 1 2 3 4 5 6 7
first element has index 0 last element has index 7
…Continued

index can be a constant, a variable, or an expression


Syntax: of integral data type
arrayName[ index ]
Examples:
sum += x[7]; /* is a numeric constant */
temp = x[i]; index is an integer variable
x[i+1] = /* */
y[2*j - 1]; index is produced
! Index mustby
bean
an integer */
sum += /* expression */
x[3.5]; index
Cautions /* Error
– index must be an integral number ( int, short etc. )
– index must range from 0 to the numberOfelements – 1 for
correct access to your array elements
– C does not check the value of the index
– any invalid index may cause unexpected outcomes
…Continued

There is NO Index range checking in C


int dataBuffer[5]; /* array to store 5 integer numbers */

Memory
17 . . . . . . .
int dataBuffer[-1] = 17;
dataBuffer[0]
dataBuffer[2] = 24;

dataBuffer
dataBuffer[1]
dataBuffer[6] = 35;
itemsInStock[2]
24
C does not check whether the index is
dataBuffer[3]
within the valid range or not dataBuffer[4]
− No error or warning messages
. . . . . . .
−Can corrupt other variables 35
− Unexpected behaviour at run time or
program crash: segmentation fault
1-D Array Manipulation
Using Loops for Sequential Access
• To access the array elements sequentially, we can use loops
• Example: the following array square will be used to store the squares of the
integers: 0 through 10 (e.g., square[0] is 0 , square[10] is 100)

#define SIZE 11
…..
int main() {
int square[SIZE], i;

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


square[i] = i * i;

9
Unsupported Operations
Caution: you can’t use the array name to
– a constant to all the array elements
float salePrice[SIZE];
X salePrice = 15.0;
– one array content to another, even if they match
completely in type and size
int inData[4]={2, 4, 8, 3}, outData[4];

X outData = inData;

− compare two array contents through the array names


X if( outData == inData )

- For any of the above operations, use Loops to go through the


elements of the array
III. Arrays and Functions
• Function parameters:
1. Individual array elements: elements are passed the same way as simple data types
(their values are copied); use arrayName[Index of element]

2. Complete Array: user array name only. The array is passed by reference (their
values are not copied, but the address of the array is). The called function can access
the array directly

• Besides the array you have to pass the array size to the called function, to
access the valid range of the array

• Return value:
– C does not allow functions to return a value of the type array
double[] createArray( int size); /* Error */
If you need to return an array, add it in the function parameters
void createArray( int size, int data[]);
…Continued

Example: Empty [ ] indicate that

1. Function prototype this function parameter


is an array
float findSmallest( float marks[], int size);
2. Function call: pass the whole array the array name
float examMarks[50]; without brackets
baseNumber = findSmallest( examMarks, 50);
3. Function definition
float findSmallest( float marks[], int size )
{
float min = marks[0];
int i;
for( i=1; i < size; ) Marks points to
i++ examMarks,
if( min > marks[i] ) min = marks[i];
see slide 17
return min;
}
…Continued

Since the function has full access to the actual array data, it
may mistakenly change it
dataIn[0] dataOut[0]

dataIn[1] dataOut[1]

dataIn[2] dataOut[2]

dataIn[3] dataOut[3]

void addVector( int dataIn[], int dataOut[], int size )


{
for(int i=0; i < size; i++) {
dataOut[i] = dataIn[i] + dataIn[i]%2;
if (dataOut[i] == 0) dataIn[i]++;
} A bug: the source data
return ; array will be corrupted
} Meant to be: dataOut[i]+
+
…Continued

To prevent accidental modification of arrays, pass them as


const
int itemsIn[250];
int itemsOut[250];
itemsIn[5] = 128;
addVector( itemsIn,
itemsOut, 250 );

{ Can't be modified
void addVector( const Can be modified
intfor(int i=0;
dataIn[], inti < sz; i++) {
dataOut[], int sz =
dataOut[i] ) dataIn[i] + dataIn[i]%2;
if (dataOut[i] == 0) dataIn[i]++;
}
return ;
}
11/03/2016
…Continued

#include <stdio.h>
If the array is not to be
modified, declare it as
int sum( const int data[], int size ); const

int main(void)
{
int array[5] = {1,2,3,4,5}; specify only the array
int total; name, no brackets
/* call the sum() function */
total = sum( array, 5 );
printf(“Total is %d\n”, total);
return (0);
}
If the array is not to be
/* function definition */ modified, declare it as
int sum( const int data[], int size ) const
{
. . .
return theSum;
}
Example 1: Pass by Reference

A function that stores the same value ( in_value ) in all elements


of the array corresponding to its formal array parameter list .
…Continued

The function’s local


variable

If x is an array with five type int elements, the function call


fill_array(x, 5, 1); stores the value of 1 in the five elements of array x .
The array x is passed by reference, whereas in_value and i are passed by value
Example 2: max of an array
Write a function get_max to find the largest value in an array. It uses
the variable list as an array input parameter.

Function call example:x_large = get_max(x, 5);


Example 3: return the sum of 2 arrays

Write a function add_arrays to add two arrays.


…Continued
Example function call:
add_arrays(x, y, x_plus_y, 5);

Formal parameters ar1 , ar2 , and arsum of the function point to the actual parameter arrays
in the calling functions x, y, and x_plus_y (pass by reference) unlike n which is passed by value.
Example 4: search an array
The function search finds a target value in an array

If array ids is declared in the calling


function, the assignment statement:

index = search(ids, 4902, ID_SIZE);

calls function search to search the first


ID_SIZE elements of array ids for the
target ID 4902 . The index of the first
occurrence of 4902 is saved in index. If
4902 is not found, then index is set to
−1 .
Example 5: statistical computation using arrays

Write a program that computes the mean and


standard deviation of an array of data and displays
the difference between each value and the mean.
…Continued

Standard deviation
IV. 2‐ D Arrays
• Created by defining two separate element numbers: number of rows and
number of columns
• Declaration
type name[numOfRows][numOfColumns];

• Example: an array of integers with 5 rows and 4 columns


int codeTable[5][4];

• Accessing elements: to access an element of a 2‐D array you need to specify


both the row and the column indexes
Examples:
int x = 2, y = 1, z = 0;
codeTable[1][2] = 128;
codeTable[x][y] = z + codeTable[1][2];
codeTable[3] = 0; /* Error. This is a 2‐D array */
2D Array Initialisation
• You can use either,

1. Grouping of braces to initialise each row of elements


0 1 2
int myArray[3][3] = { {0, 1, 2}, {1, 2, 3}, {2, 3, 4} };
1 2 3

myArray[0][1] returns 1 2 3 4

myArray[1][2] returns 3

2. Use nested loop to access each element via its pair of indices:
for (int x = 0; x <=2; x++) { // row index
for (int y = 0; y <=2, y++) // column index
myArray[x][y] = ( x + y); // adds values to element

• If you’re initalising the array elements to 0, int myArray[3][3] = {{0}}; works too!
2D Array Access
 Use nested loops to iterate through each dimension of the array

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


int i, j;

for ( i = 0; i < 5; i++ ) // row


for ( j = 0; j < 2; j++ ) // column
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
2D Arrays and Functions

The number of columns


• Function prototype must be a constant

double findSmallest( double matrix[][3], int rows);


• Function call
double data2D[25][3];
. . .
minNumber = findSmallest( data2D, 25);
This function can process 2D
arrays only with 3 columns
• Function definition
double findSmallest( double matrix[][3], int rows )
{
double min = matrix[0][0];
for(i=0; i < rows; i++)
for(j=0; j < 3; j++)
if(min > matrix[i][j]) min = matrix[i][j];
return min;
}
V. Multidimensional Arrays
 Multidimensional arrays are supported where every dimension should be
associated with a [SIZE] in your array declaration

 A simple example of a 3D array: considering storing a video.


 Each frame of the video is a 2D image with intensity values: image (i,j).
 To have multiple frames, we can use Mat[Height][Witdth][Depth] to store
“Depth” frames, where each frame is a 2 D array of dimension Height*Width.

 4D arrays is an array of 3D arrays… and so forth


Appendix: sizeof() function
 Some of inbuilt functions are used to calculate length of array such as sizeof()
function
 Example:
int arr[] = {1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14};
printf("Num of elements: %d, sizeof(arr)/sizeof(arr[0]);
Prints: Number of elements: 11

sizeof(arr) by itself returns size of array in bytes, in this case 44 (int = 4 bytes).
sizeof(arr[0]) returns memory size of element. So 44/4 = 11
Example
int myArray[5] = {1, 3, 5, 7, 9}, search, c,
size; size = sizeof(myArray)/sizeof(myArray[0]);
printf("Enter value to find \n");
scanf("%d", &search);
for (c = 0; c<size; c++)
{
if (myArray[c] == search)
printf("Its in positions %d", c + 1);
}

You might also like