Download presentation source

Download Report

Transcript Download presentation source

CS100A Lecture 24, 24 November 1998
Chance to replace grade on Prelim 3, Question 2.
Everyone is expected to be in lecture on Thurs., 3 Dec.
A short quiz concerning the development of loops from
invariants will be given. You must hand it in.. If
• (0) your grade on the quiz is larger than your grade on
Question 2 of Prelim 3 and
• (1) you turn in your Prelim 3 with the Quiz, we will
raise your Question 2 grade to your Quiz grade.
Also, we will hand out course evaluations for you to
complete and hand in at the end of the lecture.
In preparation for the quiz, memorize the material on
next slide --it will help you in the same way that memorizing the steps in executing a method call helped.
BRING YOUR PRELIM 3 TO LECTURE on 3 DEC.
CS100A, Lecture 24, 24
November 1998
1
Memorize this slide
A loop invariant is a true-false statement (about the variables used in a loop) that is true before and after each
iteration.
Given an invariant P, we can develop a loop with
initialization in four steps:
• (1) Create initialization that makes P true.
• (2) Determine the condition B so that from !B and P you
can see that the desired result is true. (Or, equivalently,
determine the condition B such that you know the desired
result is not true.)
• (3) Figure out what statement(s) to put in the loop body
to make progress toward termination of the loop.
• (4) Figure out what else the loop body should do to ensure that after execution of the loop body invariant P is
still true.
init;
// invariant P: …
while ( B )
{S}
S must make progress
toward termination
and keep P true
CS100A, Lecture 24, 24
November 1998
2
Example of a loop developed from an invariant
Problem. Sorted array b[0..n-1] may contain duplicates.
Rearrange b[0..n-1] and store in k so that b[0..k-1] contains the non-duplicates of b[0..n-1]. Invariant P:
0
k
i
n
Sorted. Contains all dis- looked at, these values
b tinct values of b[0..i-1], but not
haven’t been
and has no duplicates
changed
looked at
(1) Initialization: Make first section empty using k= 0;
make second section empty using i= 0;
(2) Stop when last section is empty, i.e. when i=n. So,
continue as long as i != n.
(3) Make progress using i= i+1.
(4) Before incrementing i: if b[i] is not a duplicate, place
it in section b[0..k-1].
k= 0; i= 0;
while ( i != n) {
if (k = 0 || b[k-1] != b[i] )
{b[k]= b[i]; k= k+1;}
i= i+1;
}
CS100A, Lecture 24, 24
November 1998
3
Data structures in C
Review: C pointers and parameters
New concepts:
• C structures (struct) --like classes with no methods
• Type definitions (typedef)
• C arrays
• Struct and array parameters
• C strings
CS100A, Lecture 24, 24
November 1998
4
Pointer Parameters (review)
Example of a procedure
// Swap contents of variables pointed to by x and y
void swap (int * x, int * y)
{int tmp; tmp= *x; *x= *y; *y= tmp;}
Note: There was a typo in this function definition in the
notes from lecture 23. The correct type for the parameters is “int *”, not “int &”. The type “int &” in the
previous lecture is a C++ notation for the type of a
certain kind of parameter; it is not part of C.
Example of a call on procedure swap:
int j= 17;
int k= 24;
swap(&j, &k);
CS100A, Lecture 24, 24
November 1998
5
Type definitions and structs
• C provides a way to group a bunch of variables
together, in what is called a struct. A typedef is similar to
a class in Java, but the typedef can’t have methods as
fields
C
typedef struct {
int a;
char ch;
} Pair;
Corresponding Java
public class Pair {
int a;
char ch;
}
Pair abc; xyz= 10; xyz.ch= ‘q’;
•Declaration of a struct variable in C actually creates the
structure. No separate allocation is needed, as it is in
Java (using new …).
•struct variables may be local to a function,just like ints,
chars, and doubles.
struct { int a; int ch;} x; /* s is a variable with
/* two fields, a, ch
CS100A, Lecture 24, 24
November 1998
6
struct parameters
Structs in C behave exactly like ints and chars in Java.
In declaring a variable of some struct type, no reference
is created. A struct variable is passed by value.
typedef struct { … } Pair; // As before
void fv (Pair p)
{p.a= 42;}
frame for main
void main (void) {
Pair pr;
pr.a= 17;
pr.ch= ‘?’;
fv(pr)
}
pr
CS100A, Lecture 24, 24
November 1998
a ___
ch ___
7
struct pointer parameters
If you want to change a component of a struct variable,
pass a pointer to the struct:
typedef struct { … } Pair; // As before
void fr (Pair * p)
{(*p).a= 42;}
frame for main
void main (void) {
Pair pr;
pr.a= 17;
pr.ch= ‘?’;
fr(pr)
}
pr
a ___
ch ___
•Abbreviation. In C, instead of write
( * p) . a
one can write
p ->a .
CS100A, Lecture 24, 24
November 1998
8
Dynamic storage allocation in C
•The standard library function malloc is used to obtain a
block of storage. It is an extremely low-level function --its argument is the number of bytes or words to be
allocated (typically obtained using operator sizeof). It
returns an untyped pointer, which must be cast to the
desired type.
•Allocated storage must be explicitly freed by calling
procedure free. There is no automatic garbage collection.
#include <stlib.h>
Pair * p;
/* p is a pointer to a Pair*/
p= (Pair *) malloc( sizeof(Pair) );
p->a= 17;
…
free(p);
CS100A, Lecture 24, 24
November 1998
9
C arrays
• C arrays are syntactically similar to arrays in Java, but
the semantics (meaning) is different.
• Declaring an array in C actually allocates it.
• Declaring an array of structs allocates a block of
storage with space for all the structs in the array.
• The array name is effectively a pointer to the first
element of the array.
• Array indices start at 0.
• There is no built-in function to determine the length of
an array.
Examples
int b[10];
Pair v[10];
int k;
for (k= 0; k < 10; k= k+1)
b[k]= 0;
v[0].a= 10;
v[2].ch= ‘!’;
CS100A, Lecture 24, 24
November 1998
10
C array parameters
• When an array name is used as a parameter, the “value”
of the parameter is a pointer to its first element.
• Therefore, array parameters are always pointers. The
called function refers to the argument array directly. No
copy of the array is made.
• An & is usually not needed or appropriate for an array
argument
Example
/* Set s[0..n-1] to 0.0 */
void zero (double a[ ] , int n) {
int k;
for (k= 0; k<n; k= k+1)
a[k]= 0.0;
}
void main(void) {
double b[100];
zero(b, 100);
}
CS100A, Lecture 24, 24
November 1998
11
C array parameter example (continued)
• Because array names are treated as pointers, C
programmers tend to use pointers and arrays somewhat
interchangeably. Procedure zero could have been
written with a pointer parameter, as shown below. It
could still be called with an array name as argument.
Example
/* Set s[0..n-1] to 0.0 */
void zero (double * a , int n) {
int k;
for (k= 0; k<n; k= k+1)
a[k]= 0.0;
}
void main(void) {
double b[100];
zero(b, 100);
}
CS100A, Lecture 24, 24
November 1998
12
Arrays of structs a parameters
An array of structs is treated like any other array. If a
parameter is an array of structs, a pointer to the beginning of an array (i.e.an array name) is the appropriate
argument.
/* Store 0’s and blanks in pa[0..n-1] */
function zap (Pair pa [ ], int n) {
int k;
for (k= 0; k<n; k++)
{pa[k].a= 0; pa[k].ch= ‘ ’;}
void main( void ) {
Pair ray[42];
/* initialize ray[0..16] to 0’s and blanks */
zap(ray, 17);
}
CS100A, Lecture 24, 24
November 1998
13
Parameters that are structs containing arrays
Structs may contain arrays --but remember that struct
arguments will be copied unless pointers are used.
typedef struct {
int a[10];
} Ray;
void isCopied(Ray r) {
r.a[2]= -1; /* Doesn’t change the argument */
}
void notCopied(Ray * r) {
r.a[2]= -1; /* Changes the argument */
void main (void) {
Ray a;
isCopied(a);
notCopied(&a);
}
CS100A, Lecture 24, 24
November 1998
14
Strings
• In C, a string is an array of characters. The array
contains the characters in the string followed by an
extra char (byte) containing a binary zero.
• Example: “hello” is represented by an array:
h
e
l
l o
\0
• Because strings are arrays, and because array names are
basically pointers, the assignment and comparison
operations manipulate pointers, and not the strings
themselves.
char s[ ]= “hello”;
char t[ ]= s; /* s and t point to same place*/
s[1]= ‘?’;
/* s and t are now “h?llo” */
• Standard library strlib.h contains routines to copy string
values, catenate them, compare them, etc.
CS100A, Lecture 24, 24
November 1998
15