0% found this document useful (0 votes)
20 views69 pages

1 Arrays

The document provides an overview of arrays in programming, including their definitions, types (1D, 2D, 3D), and how to declare and access them in C. It includes visual examples, syntax for declarations, and exercises for practice. Key concepts such as memory storage, passing arrays as parameters, and basic algorithms for manipulating array data are also discussed.

Uploaded by

White Listed
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)
20 views69 pages

1 Arrays

The document provides an overview of arrays in programming, including their definitions, types (1D, 2D, 3D), and how to declare and access them in C. It includes visual examples, syntax for declarations, and exercises for practice. Key concepts such as memory storage, passing arrays as parameters, and basic algorithms for manipulating array data are also discussed.

Uploaded by

White Listed
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/ 69

Arrays

/* Read Chapter 1 of the Course Notes for details. */

サルバド-ル・フロランテ 1
Visual Examples of Arrays

https://www.photos-public-domain.com/2011/08/30/truth/

https://pixabay.com/vectors/chessboard-chess-board-game-29630/ https://en.wikipedia.org/wiki/Rubik%27s_Cube#/media/
File:Rubiks_cube_solved.jpg 2
Visual Examples of Arrays
1D array

group of 5 letters

https://www.photos-public-domain.com/2011/08/30/truth/

https://pixabay.com/vectors/chessboard-chess-board-game-29630/ https://en.wikipedia.org/wiki/Rubik%27s_Cube#/media/
File:Rubiks_cube_solved.jpg 3
Visual Examples of Arrays

https://www.photos-public-domain.com/2011/08/30/truth/

1st row
2D array

8 rows by 8 columns
= group of 64 squares

8th row
1st col 8th col
https://pixabay.com/vectors/chessboard-chess-board-game-29630/ https://en.wikipedia.org/wiki/Rubik%27s_Cube#/media/
File:Rubiks_cube_solved.jpg 4
Visual Examples of Arrays
3D array

3 (length) by
3 (width) by
3 (height)
https://www.photos-public-domain.com/2011/08/30/truth/ = group of 27 small cubes

1st row

8th row
1st col 8th col
https://pixabay.com/vectors/chessboard-chess-board-game-29630/ https://en.wikipedia.org/wiki/Rubik%27s_Cube#/media/
File:Rubiks_cube_solved.jpg 5
Q: What is an Array?
• is a DATA STRUCTURE variable that stores a group
of elements of the data same data type (i.e.,
homogeneous)
• elements are stored in contiguous memory which
is allocated statically
• an array is characterized by:
– name
– dimensionality // 1D, 2D, 3D, …
– size // number of elements
– element data type
6
Q: How do you declare an array in C?
• 1D array // also called “list”
size must be a non-
<data type> <name> [ <size1> ] negative integer

• 2D array // also called “table”, “matrix”


<data type> <name> [ <size1> ][<size2>]

• 3D array
<data type> <name> [ <size1> ][<size2>][<size3>]

7
Example: Array Declarations
// example 1D array declaration
char str[5]; name : str
int A[5], B[10]; dimensionality : 1D
float Grades[40]; size : 5
double D[1000]; element type : char

8
Example: Array Declarations
// example 1D array declaration
char str[5];
int A[5], B[10];
float Grades[40];
double D[1000];

// example 2D array declaration


char CrossWord[10][10]; // 10 rows x 10 columns
int Sudoku[9][9];
float Table[2][4];
double Matrix[3][5]; name : Matrix
dimensionality : 2D
size : 3 rows by
5 columns
element type : double

9
Example: Array Declarations
// example 1D array declaration
char str[5];
int A[5], B[10];
float Grades[40];
double D[1000];

// example 2D array declaration


char CrossWord[10][10]; // 10 rows x 10 columns
int Sudoku[9][9];
float Table[2][4];
double Matrix[3][5];

// example 3D array declaration


int RubikCube[3][3][3]; name : RubikCube
dimensionality : 3D
size : 3x3x3
element type : int
10
Exercise: Declare array variables for the ff.

https://www.photos-public-domain.com/2011/08/30/truth/

https://www.goodfreephotos.com/other-
photos/stack-of-flat-rocks.jpg.php

https://pixabay.com/vectors/chessboard-chess-board-game-29630/
https://en.wikipedia.org/wiki/Rubik%27s_Revenge#
/media/File:Rubiks_revenge_solved.jpg
11
Let’s concentrate first on 1D arrays.

12
Q: How do you visualize/draw a 1D Array?

Option 1: draw it
vertically

13
Q: How do you visualize/draw a 1D Array?
Option 2: or draw it
horizontally

14
Q: How do you visualize/draw a 1D Array?
Drawing an array
of characters

15
Q: How do you visualize/draw a 1D Array?

Drawing an array
of floating point
values

16
Q: How do you access an array element?
Declaration: int A[8];

17
Q: How do you access an array element?
There is a unique Declaration: int A[8];
index for each
element.

18
Q: How do you access an array element?
Declaration: int A[8];
index is from 0
to size - 1

19
Q: How do you access an array element?
A[0] Declaration: int A[8];

A[1]
A[2] Access an element by
giving the array name, and
A[3] its index enclosed in [ ].
A[4]

A[5]
A[6]

A[7]

20
Exercise: Answer the questions below.
Declaration: int A[8]; A[0]
What is the value corresponding to the following? If the A[1]
array access is invalid, explain the reason why.
A[2]
1. A[ 0 ] + A[ 1 ]
2. A[ -1 ] A[3]
3. A[ 8 ] A[4]
4. A[ 8/2 ]
5. A[ 8/2.0 ] A[5]
6. A[ 68 – ‘A’ ]
7. A[ A[ 2 ]/2 ] A[6]
8. A[ -A[ 6 ] ]
9. A[ A[ 7 ] % 8 ] A[7]
10. A [ A[3] / A[0] ]

21
Example program
#include <stdio.h>
int
main()
{
char str[5]; // 1D array declaration
int i;

22
Example program
#include <stdio.h>
int
main()
{
char str[5]; // 1D array declaration
int i;

Questions:
1. What are the values of the elements of array str[]right after the
declaration?
2. How many bytes will be allocated for the use of array str[]?

23
Example program
#include <stdio.h>
int
main()
{
char str[5]; // 1D array declaration
int i;

str[0] = ‘Z’; // element initialization


str[1] = ‘e’;
str[2] = ‘B’;
str[3] = ‘$’;
str[4] = ‘\0’; // ‘\0’ is the null byte

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


printf(“%c”, str[i]); // use a loop to access all elements

return 0;
}
24
Q: How is a 1D array stored in the memory?
A 1D array is stored in
// example 1D char array indexing in fixed size contiguous
char str[5]; memory.
int i; Memory Map
str[0] = ‘Z’; Pointer Value
str[1] = ‘e’; :
str[2] = ‘B’;
str[3] = ‘$’; &str[0] 11AA Z str[0]
str[4] = ‘\0’;
&str[1] 11AB e str[1]
for (i = 0; i < 5; i++) B
&str[2] 11AC str[2]
printf(“%c”, str[i]);
&str[3] 11AD $ str[3]
&str[4] 11AE \0 str[4]
:

25
Exercise: Answer the questions below.
// example 1D int array indexing
int A[5];
int i; Pointer Value
:
for (i = 0; i < 5; i++) 8
scanf(“%d”, &A[i]); &A[0] 22BB A[0]
&A[1] _____ -5 A[1]
for (i = 0; i < 5; i++) 9
&A[2] _____ A[2]
printf(“%d”, A[i]);
&A[3] _____ 6 A[3]
&A[4] _____ -23 A[4]
Questions: :
1. What is the data type of A[i]?
2. What is the data type of &A[i]?
3. What is the data type of A?
4. What are the addresses of A[1] to A[4]? Assume sizeof(int) is 4.
5. How many bytes were allocated for the use of array A[]?
26
Q: Can you pass an array as parameter?
void int
InputList(int A[], int n) main()
{ {
int i; int A[5];

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


scanf(“%d”, &A[i]); InputList(A, 5);
}
PrintList(A, 5);
void
PrintList(int L[], int S) return 0;
{ }
int j;

for (j = 0; j < S; j++)


printf(“%d\n”, L[j]); Questions:
} 1. What is passed to InputList()?
2. What is passed to PrintList()?

27
Q: Can you pass an array as parameter?
void int
InputList(int A[], int n) main()
{ {
int i; int A[5];

for (i = 0; i No need
< n; to indicate size
i++)
scanf(“%d”, inside
&A[i]);
[] InputList(A, 5);
}
PrintList(A, 5);
void
PrintList(int L[], int S) return 0;
{ }
int j;

for (j = 0; j < S; j++)


printf(“%d\n”, L[j]); Questions:
} 1. What is passed to InputList()?
2. What is passed to PrintList()?

28
Acdg. to (Kernighan & Ritchie, 1988, page 99)

• “..the name of an array is a synonym for the


location of the initial element, …”
• “When an array name is passed to a function,
what is passed is the location of the initial
element. Within the called function, this
argument is a local variable and so an array name
parameter is a pointer, that is, a variable
containing an address.”
• “In evaluating a[i], C converts it to *(a + i)
immediately; the two forms are equivalent.”
29
& * [] relationship

Equivalence 1:

A[i] == *(A + i)

Equivalence 2:

&A[i] == A + i

30
& * [] relationship
Value
Pointer
:

8
&A[0] == A + 0 22BB A[0] == *(A + 0)
-5
&A[1] == A + 1 22BF A[1] == *(A + 1)
9
&A[2] == A + 2 22C3 A[2] == *(A + 2)
6
&A[3] == A + 3 22C7 A[3] == *(A + 3)
-23
&A[4] == A + 4 22CB A[4] == *(A + 4)
:

31
Exercise: Fill in the blanks.
// array indexing version // pointer dereferencing version
int int
main() main()
{ {
int i, A[5]; int i, A[5];

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


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

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


printf(“%d\n”, A[i]); printf(“%d\n”, _________);

return 0; return 0;
} }

32
Exercise: Fill in the blanks.
// array indexing version // pointer dereferencing version
void void
InputList(int A[], int n) InputList(__________, int n)
{ {
int i; int i;

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


scanf(“%d”, &A[i]); scanf(“%d”, _______);
} }

void void
PrintList(int L[], int S) PrintList(_______, int S)
{ {
int j; int j;

for (j = 0; j < S; j++) for (j = 0; j < S; j++)


printf(“%d\n”, L[j]); printf(“%d\n”, _________);
} }
33
Q: How do you define a 1D array?
Syntax:
<data type> <name> [ <size> ] = { __, __, … }

Example:
char str[5] = { ‘Z’, ‘e’, ‘B’, ‘$’, ‘\0’};
int A[5] = { 8, -5, 9, 6, -23 };
int List[10] = { 1, 2, 3 };

Q: What are the values of List[3] to List[9]?

34
Q: What can we do with 1D arrays?
Basic algorithms on a group of items include:
• Minimum - find the lowest value
• Maximum - find the highest value
• Sum - find the total of the values in the group
• Average = sum/n (where n is the # of elements)
• Count - how many values in the group satisfy a given
condition?
• Search - Is x in the group?
• Sort - arrange values in increasing/decreasing order

35
Example: Given the following 1D array, compute the
Minimum, Maximum, Sum and Average.

• Minimum is ___
• Maximum is ___
• Sum is ___
• Average is ___

36
Example: Given the following 1D array, answer the
following counting problems?

How many are elements are


• positive? ___
• negative? ___
• even? ___
• odd? ___
• higher than 50? ___
• there between -10 and 50
inclusive? ____

38
Minimum Algorithm
#define SIZE 8

// Find the smallest value in the group. Assume that the values are unique.
// Return the index of the minimum element.
int
Minimum(int A[], int n)
{
int i;
int min = 0; // assume that 1st element is the smallest

for (i = 1; i < n; i++) // note: start with index 1 not 0


if (A[min] > A[i])
min = i; // update the minimum index

return min;
}

int
main()
{
int A[SIZE] = {10, 23, 11, 63, -55, 99, -20, 88};

printf(“%d\n”, Minimum(A, SIZE));


return 0;
}

39
Exercise: Maximum Algorithm
// Find the highest value in the group. Assume that
// the values are unique.
// Return the index of the maximum element.
int
Maximum(int A[], int n)
{
int i;

/* Implement the body of this function. */

40
Sum Algorithm
// Find the sum of the values in the group.
// Return the sum (also called total).
int
Sum(int A[], int n)
{
int i;
int acc = 0; // don’t forget to initialize the accumulator

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


acc = acc + A[i]; // acc += A[i];

return acc;
}

41
Exercise: Average Algorithm
// Find the average of the values in the group.
// Return the average.
float
Average(int A[], int n)
{
int i;

/* Implement the body of this function. */

42
Counting Positive Numbers Algorithm
// Count the number of positive elements in the group.
// Return the count.
int
CountPositive(int A[], int n)
{
int i;
int ctr = 0; // don’t forget to initialize the ctr

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


if (A[i] > 0) // check the necessary condition
ctr++;

return ctr;
}

43
Exercise: Count the Odd Number
// Count the number of odd numbers in the group.
// Return the count.
int
CountOdd(int A[], int n)
{
int i;

/* Implement the body of this function. */

44
Search Algorithm
Problem: Determine if a given search key value is (found) in a known
universe of key values. Use a 1D array with size n to represent the list
of unique keys.

Solution:
1. Linear search algorithm: O(n)
Watch: https://www.youtube.com/watch?v=TwsgCHYmbbA

2. Binary search algorithm: O(lg n) but requires that the array be in


sorted order
Watch: https://www.youtube.com/watch?v=T98PIp4omUA

45
Linear Search Algorithm
// Search for key in A[] with n elements.
// Return index if found, otherwise, return -1
int
LinearSearch(int key, int A[], int n)
{
int i;

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


if (key == A[i]) // found
return i;

return -1; // not found if we reach this point


}

Questions:
1. How many times, at the minimum, will the if () be performed?
2. How many times, at the maximum, will the if() be performed?

46
Example: Determine the value returned by the LinearSearch()
function call based on the following 1D array.

• LinearSearch(10, A, 8) is ___.
• LinearSearch(-55, A, 8) is ___.
• LinearSearch(22, A, 8) is ___.

47
Binary Search Algorithm
int
BinarySearch(int key, int A[], int n)
{
int low = 0, high = n - 1, mid;
int found = 0;

while (!found && low <= high) {


mid = low + (high – low)/2;
if (key == A[mid]) // found
found = 1;
else if (key < A[mid]) // search lower half
high = mid – 1;
else // key > A[mid] search upper half
low = mid + 1; // search upper half
}

if (found)
return mid;
else
return -1;
} 48
Sorting Algorithm
Problem: Given an unordered set of key values, re-arrange them
such that they will be in increasing order (or decreasing order).

Use a 1D array with size n to represent the list of key values. The
array is sorted in increasing order when A[i] <= A[i+i] for
i = 0 to n - 2.

Solution: Selection sort (discussed in CCPROG2 Course Notes)


Watch: https://www.youtube.com/watch?v=3hH8kTHFw2A

50
Selection sort
void
SelectionSort(int A[], int n)
{
int i, j, min, temp;

for (i = 0; i < n - 1; i++) {


min = i; // min is the index of the lowest element

for (j = i + 1; j < n; j++)


if (A[min] > A[j])
min = j;

// swap A[i] with A[min]


if (i != min) {
temp = A[i];
A[i] = A[min];
A[min] = temp;
}
}
}
51
Selection sort with a separate Swap() function
void void
Swap(int *px, int *py) SelectionSort(int A[], int n)
{ {
int temp; int i, j, min;

temp = *px; for (i = 0; i < n - 1; i++) {


*px = *py; min = i;
*py = temp;
} for (j = i + 1; j < n; j++)
if (A[min] > A[j])
min = j;

// swap A[i] with A[min]


if (i != min)
Swap(&A[i], &A[min]);
}
}

52
Q: Are there other sorting algorithms?
Yes -- you will learn them in your future subjects
on Data Structures & Algorithms, and Algorithm
Complexity.

Refer to: https://visualgo.net/en/sorting

Mergesort: https://www.youtube.com/watch?v=Ns7tGNbtvV4
Quicksort: https://www.youtube.com/watch?v=ywWBy6J5gz8

53
Q: Can you manipulate more than 1 array?
void
Copy(int destination[], int source[], int n)
{
int i;

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


destination[i] = source[i];
}

int
main()
{
int A[5] = {10, 20, 30, 40, 50};
int B[5];

Copy(B, A, 5); Q1: What are the contents of array B before calling Copy()?
// other codes here… Q2: What are the contents of array B after calling Copy()?
return 0;
}

54
Q: Can you manipulate more than 1 array?
void
VectorAdd(int A[], int B[], int C[], int n)
{
int i;

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


C[i] = A[i] + B[i];
}

int
main()
{
int A[5] = {10, 20, 30, 40, 50}
int B[5] = {-20, 25, -2, 100, -90};
int C[5];
Q1. What are the contents of array C before calling VectorAdd()?
VectorAdd(A, B, C, 5); Q2. What are the contents of array C after calling VectorAdd()?
// other codes here…
return 0;
}
55
Exercise: Solve the following problems (from our Course Notes)

56
57
Next, we cover 2D arrays.

58
Q: How do you access 2D array elements?
// example 2D char array declaration
char C[2][3]; // 2D array declaration

// row 0 elements
C[0][0] = ‘C’; col 0 col 1 col 2
C[0][1] = ‘O’;
C[0][2] = ‘M’; row 0 C O M
// row 1 elements
C[1][0] = ‘P’;
row 1 P R O
C[1][1] = ‘R’;
C[1][2] = ‘O’;
// print elements in row major order
for (row = 0; row < 2; row++) {
for (col = 0; col < 3; col++)
printf(“%c “, C[row][col]);
printf(“\n”);
}
59
Q: How is a 2D array stored in the memory?

A 2D array is stored in
row major order (fixed
size contiguous memory).

60
Example program
#include <stdio.h>
#define NROWS 3
#define NCOLS 2
int
main()
{
int T[NROWS][NCOLS]; // 2D array declaration
int i, j;

for (i = 0; i < NROWS; i++) // array initialization


for (j = 0; j < NCOLS; j++)
scanf(“%d”, &T[i][j]);

for (i = 0; i < NROWS; i++) // print array elements


for (j = 0; j < NCOLS; j++)
printf(“%d\n”, T[i][j]);

return 0;
}

61
Example program
#define NROWS 3
#define NCOLS 2 int
void main()
InitializeMatrix(int A[][NCOLS]) {
{ int T[NROWS][NCOLS]; // 2D array declaration
int i, j;
InitializeMatrix(T);
for (i = 0; i < NROWS; i++)
for (j = 0; j < NCOLS; j++) PrintMatrix(T);
scanf(“%d”, &A[i][j]);
} return 0;
}
void
PrintMatrix (int B[][NCOLS])
{
int i, j;

for (i = 0; i < NROWS; i++) {


for (j = 0; j < NCOLS; j++) Column size is necessary. But
printf(“%d ”, B[i][j]);
there is NO need to indicate the
printf(“\n”); row size.
}
}
62
Exercise: Based on the array M[][] definition below, write the
addresses and values in the memory map.
double M[3][2] = { {6.6, 5.5}, {4.4, 3.3}, {2.2, 1.1} };

Address Value
:
&M[0][0] 88AA ___ M[0][0]
&M[0][1] ___ ___ M[0][1]
&M[1][0] ___ ___ M[1][0]
&M[1][1] ___ ___ M[1][1]
&M[2][0] ___ ___ M[2][0]
&M[2][1] ___ ___ M[2][1]

63
Exercise: Based on the array M[][] definition in the previous slide,
implement void PrintRowMajor(double M[3][2]) which
will produce the following one-line output on the screen:

6.6 5.5 4.4 3.3 2.2 1.1

void PrintRowMajor(double M[3][2])


{
// use nested loop(s), brute force NOT allowed

64
Exercise: Based on the array M[][] definition in the previous slide,
implement void PrintColumnMajor(double M[3][2])
which will produce the following one-line output on the scren:

6.6 4.4 2.2 5.5 3.3 1.1

void PrintColumnMajor(double M[3][2])


{
// use nested loop(s), brute force NOT allowed

65
Q: What can we do with 2D arrays?
Basic algorithms on a group of items include:
• Minimum - find the lowest value
• Maximum - find the highest value
• Sum - find the total of the values in the group
• Average = sum/n (where n is the # of elements)
• Count - how many values in the group satisfy a given
condition?
• Search - Is x in the group?
• Sort - arrange values in increasing/decreasing order

66
Exercise: Given the following 2D array, compute the
Minimum, Maximum, Sum and Average.
Assume the following codes

#define NROWS 3
• Minimum is ___
#define NCOLS 5
• Maximum is ___
int M[NROWS][NCOLS];
• Sum is ___
Assume also that the contents of M are: • Average is ___
• Row 1 Sum is ___
• Col 3 Sum is ___

67
Exercise:
Assume a 2D array int M[NROWS][NCOLS]. Implement the ff
functions:
1. int Minimum(int M[][NCOLS]) – return the smallest element in M.
2. int Sum(int M[][NCOLS]) – return the sum of the elements in M.
3. int RowSum(int M[][NCOLS], int row_index) – return the sum of
the elements in row row_index.
4. int ColSum(int M[][NCOLS], int col_index) – return the sum of the
elements in column col_index.
5. float Average(int M[][NCOLS]) – return the average of the
elements in M.
6. int * Search(int M[][NCOLS], int key) – do a linear search on M in
row major order. If the key is found, return its memory address;
otherwise return NULL.

69
Exercise: Solve the following problems (from our Course Notes)

70
The ideas discussed so far can be
extended to arrays of higher
dimension than 2D (i.e., 3D, 4D…).

71
-- The End --

サルバド-ル・フロランテ 72

You might also like