Professional Documents
Culture Documents
Fall 2016
SBASSE, LUMS
Goals of this Lecture
1. Arrays
2. Pointers
3. Pass by value
4. Pass by reference.
2
Readings & Quiz
• Chapter 6 (Units: 6.1-6.3)
3
Introducing Arrays
• An array is used to process a collection of data
of the exact same type
4
So how to declare an array?
• Remember:
• int a = 0;
5
Two important points
• Arrays can be accessed by indices that start from 0
(ZERO)
• So a[0] will in fact provide you with the first element of the
array
• Hence:
• The largest index is one less than the size
• The first index value is zero
6
How is an
array stored
in memory?
7
Using Arrays in programs
• An indexed variable can be used anywhere as an
ordinary variable of the type
8
A bit on the index
• a[3] is one of the indexed variables
• Any integer?
• No, an integer in the range 0 to (size -1)
9
So let’s play with the index
10
What if we overshoot an array?
• A common error is using a nonexistent index
• Index values for int a[6] are the values 0 through 5
out of range
error message!
11
Example
• If an array is declared as: int a[6];
12
Initializing Arrays
• int scores[3] = { 2, 12, 1 };
Is equivalent to:
•
int scores [3];
scores [0] = 2;
scores [1] = 12;
scores [2] = 1;
13
An other initialization
• int a[10] = {5, 5};
14
Class Fun!
• Filling an array
• Copying an array
• Sum and average value of an array
• Minimum and maximum values
• Linear search of a given element in an array
• Adding an element
• Removing an element
• Swapping an element
15
Filling an array
Slide 7- 16
Copying an array
Slide 7- 17
Sum and average value of an array
Slide 7- 18
Minimum and maximum values
Slide 7- 19
Linear search of a given element
in an array
Slide 7- 20
Adding an element
Slide 7- 21
Removing an element
Slide 7- 22
Homework
• Develop an algorithm for finding the most frequently occurring value in an array of numbers?
• A run is a sequence of adjacent repeated values. Give pseudocode for computing the length of the
longest run in an array. For example, the longest run in the array with elements
12553124322223655631 has length 4.
• Write a function reverse that reverses the sequence of elements in an array. For example, if
reverse is called with an array containing
1 4 9 16 9 7 4 9 11
then the array is changed to
11 9 4 7 9 16 9 4 1
• Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, . . ., n2 is a magic square if
the sum of the elements in each row, in each column, and in the two diagonals is the same value.
4 15 14 1
9 6 7 12
5 10 11 8
16 3 2 13
• Write a program that reads in 16 values from the keyboard and tests whether they form a magic
square when put into a 4 × 4 array. You need to test two features:
1. Does each of the numbers 1, 2, ..., 16 occur in the user input?
2. When the numbers are put into a square, are the sums of the rows, columns, and diagonals
equal to each other?
23
Up next!
• Streams - Reading and Writing text Files
• Structures
24