Programming in C 1 Programming with Arrays Subtasks - - PowerPoint PPT Presentation

programming in c
SMART_READER_LITE
LIVE PREVIEW

Programming in C 1 Programming with Arrays Subtasks - - PowerPoint PPT Presentation

Programming in C 1 Programming with Arrays Subtasks Partially-filled arrays Loading Searching Sorting Sum, average Extremes 2 Partially-filled Arrays (Common Case) Must be declared some maximum


slide-1
SLIDE 1

1

Programming in C

slide-2
SLIDE 2

2

Programming with Arrays

  • Subtasks
  • Partially-filled arrays
  • Loading
  • Searching
  • Sorting
  • Sum, average
  • Extremes
slide-3
SLIDE 3

3

Partially-filled Arrays (Common Case)

  • Must be declared some maximum size
  • Program must maintain

 How many elements are being used

and/or

 Highest subscript

slide-4
SLIDE 4

4

Sizeof and Arrays

  • Operator sizeof returns the total bytes in the

argument

 Total elements = sizeof(array) / sizeof(data-type)  Example

  • 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

slide-5
SLIDE 5

5

Loading an Array

  • Be careful not to overfill

 Do not read directly into array elements

slide-6
SLIDE 6

6

Loading a Two-dimensional Array

slide-7
SLIDE 7

7

Safer 2D Load

slide-8
SLIDE 8

8

Searching an Array

 Linear search

 Simple

 Binary search

 Requires sorted array  Generally faster for

large arrays

 May require the use of

an indicator to denote found or not found

74?

slide-9
SLIDE 9

9

Linear Search Example Using While

slide-10
SLIDE 10

10

Linear Search Example Using For

slide-11
SLIDE 11

11

Sorting

 Place array into some

  • rder

 Ascending or descending

 Many types

 Simple: Selection  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, …

slide-12
SLIDE 12

12

Selection Sort

  • Compare element to all elements below and then

move to next element, swap when appropriate

slide-13
SLIDE 13

13

Bubble/Sinking Sort

  • Compare adjacent elements, swap when appropriate
  • Stop if no swaps on a pass
slide-14
SLIDE 14

14

Sum & Average Example

  • Verify positive count before computing average

 Protects against division by zero

slide-15
SLIDE 15

15

Extremes

  • Same techniques as chapter 5 – best:

 Assume first is extreme  Compare others to current extreme  Replace extreme when finding new extreme

slide-16
SLIDE 16

16

Extremes: Find Maximum Example

slide-17
SLIDE 17

17

Programming in C

T H E T H E E N D N D