1 Arrays
1 Arrays
サルバド-ル・フロランテ 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
• 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];
9
Example: Array Declarations
// example 1D array declaration
char str[5];
int A[5], B[10];
float Grades[40];
double D[1000];
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;
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];
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;
28
Acdg. to (Kernighan & Ritchie, 1988, page 99)
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];
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;
void void
PrintList(int L[], int S) PrintList(_______, int S)
{ {
int j; int j;
Example:
char str[5] = { ‘Z’, ‘e’, ‘B’, ‘$’, ‘\0’};
int A[5] = { 8, -5, 9, 6, -23 };
int List[10] = { 1, 2, 3 };
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?
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
return min;
}
int
main()
{
int A[SIZE] = {10, 23, 11, 63, -55, 99, -20, 88};
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;
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
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;
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
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;
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
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;
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;
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.
50
Selection sort
void
SelectionSort(int A[], int n)
{
int i, j, min, temp;
52
Q: Are there other sorting algorithms?
Yes -- you will learn them in your future subjects
on Data Structures & Algorithms, and Algorithm
Complexity.
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;
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;
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;
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;
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:
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:
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