Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views25 pages

Lecture 7 - Arrays

Uploaded by

sevdermys09
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)
16 views25 pages

Lecture 7 - Arrays

Uploaded by

sevdermys09
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/ 25

11/13/2023

BIL111 – Programming
Arrays
Feyza M. Hafızoğlu
[email protected]

Bilgisayar Mühendisliği
İstanbul Ticaret Üniversitesi

Can we solve this problem?


• Consider the following program (input underlined):

How many days' temperatures? 7


Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.

1
11/13/2023

Why the problem is hard


• We need each input value twice:
• to compute the average (a cumulative sum)
• to count how many were above average

• We could read each value into a variable... but we:


• don't know how many days are needed until the program runs
• don't know how many variables to declare

• We need a way to declare many variables in one step.

Arrays
• array: object that stores many values of the same type.
• element: One value in an array.
• index: A 0-based integer to access an element from an array.

index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3

element 0 element 4 element 9

2
11/13/2023

Array declaration
type name[size];
• Example:
int numbers[10];

index 0 1 2 3 4 5 6 7 8 9
value

Array declaration, cont.


• The size can be any integer expression.
int x = 2 * 3 + 1;
int data[x % 5 + 2];

• Uninitialized array elements contain "garbage" values.

3
11/13/2023

Accessing elements
name[index] // access
name[index] = value; // modify

• Example:
numbers[0] = 27;
numbers[3] = -6;
printf("%d", numbers[0]);

if (numbers[3] < 0) {
printf("Element 3 is negative.");
}
index 0 1 2 3 4 5 6 7 8 9
value 27 -6

Arrays of other types


double results[5];
results[2] = 3.4;
results[4] = -0.5;
index 0 1 2 3 4
value 3.4 -0.5

4
11/13/2023

Initializing arrays using a for loop


int numbers[10];
for(int i = 0; i < 10; i++)
numbers[i] = 0;

Quick array initialization


type name[size] = {value, value, … value};
• Example:
int numbers[5] = {12, 34, 51, 95, 74};
index 0 1 2 3 4
value 12 34 51 95 74

• Useful when you know what the array's elements will be


• The compiler figures out the size by counting the values

5
11/13/2023

Quick array initialization, cont’d.


• If there are fewer initializers than elements in the array, the
remaining elements are initialized to zero.

int numbers[5] = {12, 34, 51};

index 0 1 2 3 4
value 12 34 51 0 0

Initializing arrays using a list


• If the array size is omitted from a definition with an
initializer list, the number of elements in the list will be the
size of array:
• int numbers[] = {12, 34, 51, 95, 74};
index 0 1 2 3 4
value 12 34 51 95 74

6
11/13/2023

Array size as a symbolic constant


#define SIZE 5

int main() {

int numbers[SIZE];
for (int i = 0; i < SIZE; ++i)
number[i] = 0;
}

Out-of-bounds
• Legal indices: between 0 and the array's size - 1.
• Reading or writing any index outside this range will read garbage
values

• Example:
int data[10] = {0};
printf("%d", data[0]); // okay
printf("%d", data[9]); // okay
printf("%d", data[-1]); // wrong
printf("%d", data[10]); // wrong

index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0

7
11/13/2023

Accessing array elements


int numbers[8] = {0};
numbers[1] = 3;
numbers[4] = 99;
numbers[6] = 2;
int x = numbers[1];
numbers[x] = 42;
numbers[numbers[6]] = 11; // use numbers[6] as index

x 3

index 0 1 2 3 4 5 6 7
numbers value 0 4 11 42 99 0 2 0

Arrays and for loops


• It is common to use for loops to access array elements.
for (int i = 0; i < 8; i++) {
printf("%d ", numbers[i]);
}
printf("\n"); // output: 0 4 11 0 44 0 0 2

• Sometimes we assign each element a value in a loop.


for (int i = 0; i < 8; i++) {
numbers[i] = 2 * i;
}
index 0 1 2 3 4 5 6 7
value 0 2 4 6 8 10 12 14

8
11/13/2023

Weather question
• Use an array to solve the weather problem:
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.

Weather answer
// Reads temperatures from the user, computes average and # days above average.
int main() {
printf("How many days' temperatures? ");
int days;
scanf("%d", &days);

int temps[days]; // array to store days' temperatures


int sum = 0;

for (int i = 0; i < days; i++) { // read/store each day's temperature


printf("Day %d's high temp: ", (i + 1));
scanf("%d", &temps[i]);
sum += temps[i];
}
double average = (double) sum / days;

int count = 0; // see if each day is above average


for (int i = 0; i < days; i++)
if (temps[i] > average)
count++;
// report results
printf("Average temp = %.1lf\n", average);
printf("%d days above average\n", count);
}

9
11/13/2023

"Array mystery" problem


• traversal: An examination of each element of an array.

• What element values are stored in the following array?

int a[] = {1, 7, 5, 6, 4, 14, 11};


for (int i = 0; i < 7; i++) {
if (a[i] > a[i + 1]) {
a[i + 1] = a[i + 1] * 2;
}
}

Limitations of arrays
• You cannot compare arrays with == or equals:
int a1[] = {42, -7, 1, 15};
int a2[] = {42, -7, 1, 15};
if (a1 == a2) { ... } // false!

• An array does not know how to print itself:


int a1[] = {42, -7, 1, 15};
printf("%d", a1); // [I@98f8c4]

• Unlike other programming languages, there is no function


that returns the size of an array

10
11/13/2023

Arrays as parameters

Swapping values
İnt main() {
int a = 7;
int b = 35;
// swap a with b?
a = b;
b = a;
printf("%d %d", a, b);
}
• What is wrong with this code? What is its output?

• The red code should be replaced with:


int temp = a;
a = b;
b = temp;

11
11/13/2023

Array reversal question


• Write code that reverses the elements of an array.
• For example, if the array initially stores:
[11, 42, -5, 27, 0, 89]

• Then after your reversal code, it should store:


[89, 0, 27, -5, 42, 11]

• The code should work for an array of any size.

• Hint: think about swapping various elements...

Algorithm idea
• Swap pairs of elements from the edges; work inwards:

index 0 1 2 3 4 5
value 11
89 42
0 27
-5 27
-5 42
0 11
89

12
11/13/2023

Flawed algorithm
• What's wrong with this code?

int numbers[SIZE] = [11, 42, -5, 27, 0, 89];


// reverse the array
for (int i = 0; i < SIZE; i++) {
int temp = numbers[i];
numbers[i] = numbers[SIZE - 1 - i];
numbers[SIZE - 1 - i] = temp;
}

• The loop goes too far and un-reverses the array! Fixed version:

for (int i = 0; i < SIZE / 2; i++) {


int temp = numbers[i];
numbers[i] = numbers[SIZE - 1 - i];
numbers[SIZE - 1 - i] = temp;
}

Array reverse question 2


• Turn your array reversal code into a reverse function.
• Accept the array of integers to reverse as a parameter.

int numbers[SIZE] = {11, 42, -5, 27, 0, 89};


reverse(numbers);

• How do we write functions that accept arrays as parameters?


• Will we need to return the new array contents after reversal?
...

13
11/13/2023

Array parameter (declare)


type functionName(type name[], int size) {

• Example:
// Returns the average of the given array of numbers.
double average(int numbers[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += numbers[i];
}
return (double) sum / n;
}

Array parameter (call)


functionName(arrayName);

• Example:
int main() {
// figure out the average TA IQ
int iq[] = {126, 84, 149, 167, 95};
double avg = average(iq, 5);
printf("Average IQ = %lf", avg);
}
...

• Notice that you don't write the [] when passing the array.

14
11/13/2023

Reference semantics

A swap function?
• Does the following swap function work? Why or why not?
int main() {
int a = 7;
int b = 35;
// swap a with b?
swap(a, b);
printf("%d %d", a, b);
}

void swap(int a, int b) {


int temp = a;
a = b;
b = temp;
}

15
11/13/2023

Value semantics
• value semantics: Behavior where values are copied when
assigned, passed as parameters, or returned.
• All primitive types in C use value semantics.
• When one variable is assigned to another, its value is copied.
• Modifying the value of one variable does not affect others.

int x = 5;
int y = x; // x = 5, y = 5
y = 17; // x = 5, y = 17
x = 8; // x = 8, y = 17

Reference semantics
• reference semantics: Behavior where variables actually
store the address of a variable in memory.
• When one array is assigned to another, the array is
not copied; both variables refer to the same array.
• Modifying the value of one variable will affect others.

16
11/13/2023

The value of an array name


• “the value of an array name” is really the address of the
first element of the array

printf("%p", array); // 0031F930


printf("%p", &array); // 0031F930
printf("%p", &array[0]); // 0031F930

Arrays pass by reference


• Arrays are passed as parameters by reference.
• Changes made in the function are also seen by the caller.
int main() {
int iq[SIZE] = {126, 167, 95};
increase(iq, SIZE);
for(int i=0; i < SIZE; i++)
printf("%d ", iq[i]);
}
iq
void increase(int a[], int n) {
for (int i = 0; i < n; i++) {
a[i] = a[i] * 2;
}
} index 0 1 2
• Output: a value 252 334 190
[252, 334, 190]

17
11/13/2023

Array reverse question 2


• Turn your array reversal code into a reverse function.
• Accept the array of integers to reverse as a parameter.

int numbers = {11, 42, -5, 27, 0, 89};


reverse(numbers, 6);

• Solution:
void reverse(int numbers[], int n) {
for (int i = 0; i < n / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[n - 1 - i];
numbers[n - 1 - i] = temp;
}
}

Array parameter questions


• Write a function swap that accepts an arrays of integers
and two indexes and swaps the elements at those indexes.
int a1[] = {12, 34, 56};
swap(a1, 1, 2);
for(int i=0; i < SIZE; i++)
printf("%d ", a1[i]); // [12, 56, 34]

• Write a function swapAll that accepts two arrays of


integers and size of arrays as parameters and swaps their
entire contents.
• Assume that the two arrays are the same length.
int a1[] = {12, 34, 56};
int a2[] = {20, 50, 80};
swapAll(a1, a2, 3);
for(int i=0; i < SIZE; i++)
printf("%d ", a1[i]); // [20, 50, 80]
for(int i=0; i < SIZE; i++)
printf("%d ", a2[i]); // [12, 34, 56]

18
11/13/2023

Array parameter answers


// Swaps the values at the given two indexes.
void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// Swaps the entire contents of a1 with those of a2.


void swapAll(int a1[], int a2[], int n) {
for (int i = 0; i < n; i++) {
int temp = a1[i];
a1[i] = a2[i];
a2[i] = temp;
}
}

Array return question


• Write a function merge that accepts three arrays of integers
(two non-empty and one empty array) and returns a new array
containing all elements of the first array followed by all elements
of the second.
int a1[] = {12, 34, 56};
int a2[] = {7, 8, 9, 10};
int a3[7];
merge(a1, a2, a3, 3, 4);
for(int i=0; i < SIZE; i++)
printf("%d ", a3[i]);
// [12, 34, 56, 7, 8, 9, 10]

• Write a function merge3 that merges 3 arrays similarly.


int a1[] = {12, 34, 56};
int a2[] = {7, 8, 9, 10};
int a3[] = {444, 222, -1};
int a4[10];
merge3(a1, a2, a3, 3, 4, 3);
for(int i=0; i < SIZE; i++)
printf("%d ", a4[i]); // [12, 34, 56, 7, 8, 9, 10, 444, 222,
-1]

19
11/13/2023

Arrays for tallying

A multi-counter problem
• Problem: Write a function mostFrequentDigit that
returns the digit value that occurs most frequently in a
number.

• Example: The number 669260267 contains:


one 0, two 2s, four 6es, one 7, and one 9.
mostFrequentDigit(669260267) returns 6.

• If there is a tie, return the digit with the lower value.


mostFrequentDigit(57135203) returns 3.

20
11/13/2023

A multi-counter problem
• We could declare 10 counter variables ...
int counter0, counter1, counter2, counter3, counter4,
counter5, counter6, counter7, counter8, counter9;

• But a better solution is to use an array of size 10.


• The element at index i will store the counter for digit value i.
• Example for 669260267:

index 0 1 2 3 4 5 6 7 8 9

value 1 0 2 0 0 0 4 1 0 1

• How do we build such an array? And how does it help?

Creating an array of tallies


// assume n = 669260267
int counts[10] = {0};
while (n > 0) {
// pluck off a digit and add to proper counter
int digit = n % 10;
counts[digit]++;
n = n / 10;
}

index 0 1 2 3 4 5 6 7 8 9
value 1 0 2 0 0 0 4 1 0 0

21
11/13/2023

Tally solution
// Returns the digit value that occurs most frequently in n.
// Breaks ties by choosing the smaller value.
int mostFrequentDigit(int n) {
int counts[10] = {0};
while (n > 0) {
int digit = n % 10; // pluck off a digit and tally it
counts[digit]++;
n = n / 10;
}
// find the most frequently occurring digit
int bestIndex = 0;
for (int i = 1; i < 10; i++) {
if (counts[i] > counts[bestIndex]) {
bestIndex = i;
}
}
return bestIndex;
}

Characters arrays and strings


• Initializing a character array with a string:

char word[] = "hello";

• Initializing with an initializer list:

char word[] = {‘h’, ‘e’ , ‘l’ , ‘l’ , ‘o’ , ‘\0’};

• The last element of a character array is null character:‘\0’

22
11/13/2023

Characters arrays and strings


• Accessing the characters in a string:
char word[] = "hello";
char c = word[1] ; // e
word[1] = word[4]; // hollo

• Inputting into a character array:


char word[6];
scanf("%5s", word); // scanf reads upto 5 characters

• Outputting a character array


printf("%s\n", word);

#define SIZE 20

. . .

char string1[SIZE]; // reserves 20 characters


char string2[]="string literal"; // reserves 15 characters

printf("Enter a string (no longer than 19 characters):");


// read string from user into array string1
scanf("%19s", string1); //input no more than 19 characters

// output strings
printf("string1 is: %s\nstring2 is: %s\n", string1,
string2);

printf("string1 with spaces between characters is:\n");

for (int i = 0; i < SIZE && string1[i] != '\0'; ++i) {


printf("%c ", string1[i]);
}

23
11/13/2023

Multi-dimensional arrays
• An array of arrays, the elements of which are accessed with
multiple integer indexes.
• double: one double
• double[]: a one-dimensional array of doubles
• double[][]: a two-dimensional grid of doubles
• double[][][]: a three-dimensional collection of doubles
• Example:
double temps[3][5];

Initializing array elements:


double temps[3][5] = {{0.0}, {1.0, 2.0, 3.0}, {0.0}};

24
11/13/2023

Accessing to an array element


arrayName[rowIndex][columnIndex]

• Example:
temps[0][3] = 98.3;
temps[2][0] = 99.4;

Traversing array elements


void print(double grid[][], int rows, int columns) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%lf ", grid[i][j]);
}
printf("\n");
}
}

25

You might also like