Upload
jeremiah-gilbert
View
253
Download
1
Tags:
Embed Size (px)
Citation preview
Unit 8
Arrays and Strings
Introduction toC Programming
Unit 7 Review
Unit 8: Review of Past Material
Functions - ReviewFunction Header
Return TypeIdentifier - name of functionParameter List
Data type and Identifier for each parameterComma-separated list, enclosed in parentheses
Function BodyCompound Statement in bracesMust contain a return statement unless
return type is void
Variable ScopeGlobal variable
Declared at top of a fileAccessible throughout the compilation
Local variableDeclared inside a function at top of function bodyKnown only within the function
Block scopeDeclared inside a nested compound statement
(block of code)Known only within the block
Two or more variables with same name - the one at the smaller scope hides the one(s) at larger scope(s)
PointersPointer has a data type corresponding to the variable
pointed toPointers are declared using the "*" asterisk characterThe address of a variable is obtained using the "&"
characterTo use a pointer to access memory, precede it with "*"Used to create output parameters for functions
Each output parameter is declared as a pointerThe function call must use the address of a variable as
the argumentInside the function, the external variable is accessed by
pointer
Arrays
Unit 8: Arrays and Strings
Data StructuresGroup of related data items
Stored in one contiguous area of memoryCan be accessed and manipulated as a group
or unitRecord (C language "struct")
Combination of data items of various data types
Each data item called a "field" in the recordArray (C language "array")
Multiple data items of matching data typeEach data item called an "element" in the array
Arrays - DeclarationData type, variable identifier, size in square
bracketsSize must be a constant expression, not a run-time
expressionSize must be a positive integer
int numbers [ 5 ];
The example above declares an array variable of 5 elements
The elements are numbered starting from 0:numbers[0], numbers[1], numbers[2],
numbers[3], numbers[4]
Notice that the last element is "4", not "5" !
Arrays - Access to Array ElementsThe element is identified by its index
(numerical position)Name of array (identifier) followed by
subscriptSubscript is index in square bracketsIndex value must be integer expression
Examples using the numbers array:value = numbers[10];
value = numbers[i+2];
numbers[4] = value + 3;
numbers[0] =
Arrays - Caution!Array element numbering (index) starts at 0, not
1The elements are numbered [0], [1], [2], … [n-1]int numbers[5];
numbers[0], numbers[1], numbers[2],
numbers[3], numbers[4]
Common Programming Error:Accessing past end of array - logic errornumbers[5]
C Language does not check for this error
Array InitializersFollow array declaration with a list of
expressions in bracesint numbers[5] = {3, 12, -42, 0, 6};
If a size is specified, and list is too short, zeros are used at endIf a size is specified, and list is too long, this is an errorIf a size is not specified (empty square brackets)
The compiler counts the number of initializersThe count is used as the size
int numbers[] = {3, 12, -42, 0, 6};
Array Usage - Parallel ArraysParallel Arrays - Arrays of related data
itemsExample: A list of 100 rectangles, dimensions
length and widthUse two arrays of doubles, each size 100
double length[100], width[100];
length[i] = 40;
width[i] = 25;
Array Usage - Use with FunctionsArrays and Functions
An element can be passed as an argument to a functionarea = calcArea(length[3], width[3]);
An entire array can be passed as an argument to a functionSize not passed automatically, must be an explicit
separate parameter
f(numbers, 5);
An array cannot be returned from a function
Multi-Dimension ArraysArrays can have one to six dimensions
A two-dimensional array is like a gridThe first dimension is the row, second is the column
Specify each size in separate square bracketsdouble grid[50][25];
When accessing, provide separate subscriptsgrid[r][c] = 42.5;
Multi-Dimension ArraysWhen initializing, initialize one row at a time
Initializer is "list of lists"Use braces for the entire listUse braces for list of initializers for each row
double xy[4][3] = {{0, 12.2, 14.7},{2.5, 8.3, -6},{2.0}, /* "Short" list filled with zeros */{1E6, 3.2E-1, 47.9} };
Searching and Sorting
Unit 8: Arrays and Strings
SearchingOften-used algorithm
Goal: Find a value, discover it's indexMay have result of "not found"
Array is list of values, look through the listIs the list unsorted (random order)? Linear Search
pp. 411-413Look through each element from beginningFinds the first occurrence
Is the list sorted (sequential order) ? Binary SearchDivide list in halfFinds one occurrence, not necessarily the firstMore efficient than linear search (over the long run)
SortingCommon, often-used algorithmsMany sort algorithms have been developed
Simple, but less efficientComplex, faster performance
Example: Selection Sort pp. 413-415Find smallest element (first occurrence) in list [0]
… [n-1]Swap smallest element with first elementNow, use Selection Sort on remaining list [1] …
[n-1]Continue until the "remaining unsorted list" has
1 element
String Variables: Arrays of Characters
Unit 8: Arrays and Strings
StringsImportant, commonly-used data typeGroup of characters treated as a unitExamples of common uses
Names of people, places, devices, etcInstructions to userError messagesWeb addresses and URLs
C Language StringsC does not actually have a string data typeA C string uses a character array
The string begins with the 0th element, might not fill array
To indicate end of string, a sentinel 0-value character is used
The sentinel must always be presentchar s1[10] = "George";
The format specifier for printf and scanf is "%s"
G e o r g e \0