CSE-141: Structured Programming CSE-141: Structured Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

CSE-141: Structured Programming

 Lecture 16: Introduction to Arrays


Instructor
Md. Sabir Hossain
Lecturer
Dept. of CSE, CUET
Mobile: 01737143868/01882826575
Email: [email protected]
Recap

2
Today’s Target - Arrays
Introduction to Arrays
 A collection of variable data
 Same name
 Same type
 Contiguous block of memory
 Can manipulate or use
 Individual variables or
 ‘List’ as one entity

Celsius
temperatures
: I’ll name it
c.
4 Type is int.
Introduction to Arrays
 Used for lists of like items
 Scores, speeds, weights, etc.
 Avoids declaring multiple simple variables
 Used when we need to keep lots of values in memory
Sorting
Determining the number of scores above/below the
mean
Printing values in the reverse order of reading
Etc.

5
Declaring Arrays
 General Format for declaring arrays
<data type> <variable>
[<size>];
 Declaration
 Declaring the array  allocates memory
 Static entity - same size throughout program
 Examples
Type is int.
Name is
c.

6
Defined Constant as Array Size
 Use defined/named constant for array size
 Improves readability
 Improves versatility
 Improves maintainability
 Examples:

7
Powerful Storage Mechanism
 Can perform subtasks like:
 "Do this to i-th indexed variable"
where i is computed by
program
 "Fill elements of array scores
from user input"
 "Display all elements of array
scores“
 “Sort array scores in order”
 “Determine the sum or average
score”
 "Find highest value in array
scores"
8
Accessing Array Elements
 Individual parts called many things:
 Elements of the array
 Indexed or
subscripted variables
 To refer to an
element:
 Array name and
subscript or index
 Format:
arrayname[subscript
]
 Zero based
9  c[0] refers to c0, c sub
Accessing Array Elements
 Example

 Note two uses of brackets:


 In declaration, specifies SIZE of array
 Anywhere else, specifies a subscript/index

10
Accessing Array Elements
 Example
Given the declaration

 We reference elements of scores by

scores [0]

scores [1]

… subscript/index

scores [11]

11
Accessing Array Elements
 Size, subscript need not be literal constant
 Can be named constant or expression

12
Major Array Pitfall
 Array indexes go from 0 through size-1!
 C will 'let' you go out of the array’s bounds
 Unpredictable results – may get segmentation fault
 Compiler will not detect these errors!
 Up to programmer to 'stay in bounds‘
?

13
for-loops with Arrays
 Natural counting loop
 Naturally works well 'counting thru'
elements of an array
 General form for forward direction
 for (subscript = 0; subscript < size; subscript+
+)
 General form for reverse direction
 for (subscript = size-1; subscript >= 0;
subscript--)

14
for-loops with Arrays Examples

Score 1 is 56 Score 12 is 87
Score 2 is 52 Score 11 is 97
Score 3 is 80 Score 10 is 86
Score 4 is 74 Score 9 is 80
... ...
Score 12 is 87 Score 1 is 56

15
Uses of Defined Constant
 Use everywhere size of array is needed
 In for-loop for traversal:

 In calculations involving size:

 When passing array a function: (Details in Functions chapter):

16
Array as Function Parameter
 Include type and brackets []
Size inside brackets is optional and is ignored
 Passes pointer/reference to array
Function can modify array elements
 Common to also pass size
 Example:

17
Initializing Arrays
 Arrays can be initialized at declaration

 Size cannot be variable or named constant


 Equivalent to

18
Auto-Initializing Arrays
 If fewer values than size supplied:
 Fills from beginning
 Fills 'rest' with zero of array base type
 Declaration

 Performs initialization

19
Auto-Initializing Arrays
 If array size is left out
 Declares array with size required based on number of
initialization values
 Example:

 Allocates array scores with size of 3

20
Multidimensional Arrays
 Arrays with more than one dimension
Declaration: Additional sizes each enclosed in brackets
 Two dimensions
Table or ‘array of arrays’

Requires two subscripts – row and column

21
Initializing
Multidimensional
 Nested lists
Unspecified values set to zero
 2D Example:

22
Three-dimensional Visualization

23
Initialization of a three dimensional
array
Multidimensional Array Parameters
 Must specify size after first dimension

25
Next Class
Array Sub-tasks
 Partially-filled arrays
 Loading
 Searching
 Sorting
 Sum, average
 Extremes
Programming with Arrays
 Subtasks
 Partially-filled arrays
 Loading
 Searching
 Sorting
 Sum, average
 Extremes

27
Partially-filled Arrays (Common Case)
 Must be declared some maximum size
 Program must maintain
 How many elements are being used
and/or
 Highest subscript

28
Sizeof and Arrays
 Operator sizeof returns the total bytes in the
argument
Total elements = sizeof(array) / sizeof(data-type)
 Exampl
e

 Sizeof does not return total bytes being used


 You cannot use sizeof to determine the number of
elements being used in a partially filled array

29
Loading an Array
 Be careful not to overfill

30
Loading a Two-dimensional Array

31
Safer 2D Load

32
Searching an Array
Linear search
Simple
Binary search
Requires sorted array
74? Generally faster for
large arrays
May require the use of
an indicator to denote
found or not found

33
Linear Search Example Using While

34
Linear Search Example Using For

35
Sorting
 Place array into some
order
Ascending or
descending
 Many types
Simple: Brute force
More intelligent: Bubble,
selection, insertion, shell,
comb, merge, heap, quick,
counting, bucket, radix,
distribution, timsort,
gnome, cocktail, library,
cycle, binary tree, bogo,
pigeonhole, spread, bead,
pancake, …

36
Brute Force Sort
 Compare element to all elements below and then
move to next element, swap when appropriate

37
Brute Force Example

38
Bubble/Sinking Sort
 Compare adjacent elements, swap when appropriate
 Stop if no swaps on a pass

39
Bubble Sort Example

40
Sum & Average Example
 Verify positive count before computing average
Protects against division by zero

41
Extremes
 Same techniques as chapter 5 – best:
Assume first is extreme
Compare others to current extreme
Replace extreme when finding new extreme

42
Extremes: Find Maximum Example

43
Allah Hafez

You might also like