CS100A Lecture 22 17 November...

advertisement
CS100A Lecture 22 17 November 1998
Prelim 3 Statistics
Maximum 94
Median 68
Mean 66.6
Minimum 12
Standard deviation 14.9
Question 2 was poorly written. It could not be easily
understood. We apologize. We are exploring alternatives to
rectify the situation.
CS100A, Lecture 23, 19
November 1998
1
Introduction to the programming language C
Goals: Acquire a reading knowledge of C
Concepts:
• Basic C control structures, data, I/O
• Program organization
• Pointers and parameters
Reference: The stand reference is The C Programming
Language, by Kernighan & Ritchie (2nd ed., 1988). But
this is written for experienced programmers and can be
quite terse for beginners.
History: C was developed in the lat 1960’s early 1970s, as
a language for two people to use. It blossomed because the
operating system UNIX was written in it, and everyone
wanted UNIX.
CS100A, Lecture 23, 19
November 1998
2
Java vs. C
Java advantages
• Direct support of classes, objects, and other tools for
effectively organizing medium-to-large programs.
• Extensive standard class libraries (for I/O, GUIs,
networking, etc.).
• Automatic memory management (garbage collection).
• Portable (write once, run everywhere), because of the
Java Virtual Machine.
• Used for writing Applets for the world wide web
Disadvantages
• Portability, garbage collection, and other features
impose execution time and space overhead.
• Java runtime environment keeps Java program at a
distance from the underlying machine.
• Therefore, Java programs are much slower than C
programs.
CS100A, Lecture 23, 19
November 1998
3
Java vs. C (continued)
C advantages
• Data types and constructs are close to those provided
by the underlying hardware (microprocessor), so:
• Good for writing programs that squeeze maximum
performance from hardware.
• Possible to have absolute control over machine
resources --good for writing software that directly
manipulates hardware devices. C is often thought of as
a high-level assembly language.
• C Disadvantages
• Not objected oriented (but C++ is)
• No garbage collection. Programmer must manage the
allocation and freeing of storage. This is highly prone
to error.
• Care needed to write programs that are portable.
• As will be seen, programmer must manage “pointers”
or references themselves, an extremely confusing and
error-prone issue for many.
CS100A, Lecture 23, 19
November 1998
4
Basic C Data Types
•Standard types similar to those in Java
• int, long (integers)
• float, double (floating point)
• char (characters, normally ASCII)
•No type boolean
•0 represents false
•non-0 represents true
•relations (<. <=, ==, !=, >= >) and logical
operations (!, &&, ||) yield 0 of false, 1 if true
•Size of arithmetic types depends on machine/compiler.
Examples:
•int: usually 16 or 32 bits
•long: at least as many bits as int, usually 32,
sometimes 64.
•Need to be careful if you want portable code.
CS100A, Lecture 23, 19
November 1998
5
Basic C statements
•Assignment as in C:
variable = expression ;
•Loops and conditionals just like in Java.
if (condition)
statement
if (condition)
statement
else
statement
while (condition)
statement
for (initialize; test; step)
statement
Curly braces used to group statements, as in Java. But
declarations cannot appear in a block, only in a method
body. For example, the following is not legal C:
if (x < y)
{int tmp= x; x= y; y= tmp;}
CS100A, Lecture 23, 19
November 1998
6
C functions
A C program is a collection of functions. The syntax is
much like Java, but,since there are no classes, function
declarations appear freely in a source program. There is
no explicit notion of public or private access in C.
Example:
/* Yield maximum of x and y */
int max (int x, int y) {
if (x >= y)
return x;
else return y;
}
CS100A, Lecture 23, 19
November 1998
7
A procedure is a function with type void
/* Print n lines of stars;
line i, for 1<= i <= n, has i starts on it */
void print_stars (int n) {
int j, k;
/* invariant: first k-1 lines have been written */
for (i= 1; k <= n; k++) {
/* Print line k, with k stars */
for (j= 1; j <= k; j++)
printf(“*”);
println(“\n”);
}
}
CS100A, Lecture 23, 19
November 1998
8
.c Source files
• C function definitions are placed in source files that
have names ending in “.c”.
• All functions normally may be accessed (called) by any
other function in any file.
• A function definition may be preceded by “static” to
restrict access so that it may be called only by other
functions defined in the same file.
• External (“global”) variables may be defined in a .c file
outside any function. External variables are created
when program execution begins; they retain their values
until execution of the program terminates. External
variables may also be defined static in order to restrict
access to them to the file containing the variable
definition.
CS100A, Lecture 23, 19
November 1998
9
.h Source files
• Every function (and external variable) must be defined
exactly once by giving a full definition in some .c
source file.
• A function (or external variable) may be called (or
referenced) in other files provided that there is a
declaration of the function (or external variable) in the
other files.
• The declaration of a function gives the function name
and parameters, but not the function body. Example:
int max(int x, int y);
• Related declarations are often grouped in header files
(name ending in “.h”). The declarations in a head file
xyz.h can be incorporated in another file by the
directive
#include “xyz.h”
(for user files)
#include <xyz.h.>
(for standard C libraries)
or
CS100A, Lecture 23, 19
November 1998
10
Example: Standard Math Library
• File math.h contains declarations of the standard C
math library routines:
double sqrt (double x);
double sin (double x);
double cos (double x);
etc. …
• A client program can access the definitions using the
appropriate include directive:
#include <math.h>
/* yield twice the square root of x */
double sqrt2 (double x) {
return 2 * sqrt(x);
}
CS100A, Lecture 23, 19
November 1998
11
Standard Output
• The library <stdio.h> includes basic routines to read
formatted data from the standard input (usually the
keyboard) and print on the standard output (usually a
window on the monitor).
• The basic output routine is printf. A call to printf has
one or more arguments. The first is the “format string”,
which contains literal text to be printed interspersed
with formatting instructions for printing the remaining
arguments.
•Example: Print Fahrenheit-Celsius table
#include <stdio.h>
/* Print a table of Fahenehit-Celsius values
from 0 to 300 in increments of 20 */
void main (void) {
int d;
printf(“Fahrenheit Celsius\n”);
for (d= 0; d <= 300; d= d+20)
printf(“%3d
%6.1f\n”, d, (5.0/9.0) * (d-32) );
}
CS100A, Lecture 23, 19
November 1998
12
Parameters and arguments
• As in Java, when a C function is called, a frame is
allocated, with space for the functions parameters and
local variables, and the arguments of the call are
assigned to the parameters.
• Example: Consider execution of
#include <stdio.h>
void f (int x, int y) {
int tmp;
tmp= x; x= y; y= tmp;
}
void main(void) {
int j= 17;
int k= 42;
f(j, k);
printf(“j= %d, k= %d\n”, j, k);
}
CS100A, Lecture 23, 19
November 1998
13
Pointers and References
In Java, one can’t write a procedure to swap the values of
two int variables x and y. The following method and call
does not change x and y:
// Try to swap p1 and p2
public void notaSwap(int p1, int p2)
{int t= p1; p1= p2; p2= t;}
int x= 5; int y= 6; notaSwap(x,y);
But one can change the values of fields of a class:
public class Coord
{int x; int y;}
// Swap x fields of p1 and p2
public static void Swap(Coord p1, Coord p2)
{int t= p1.x; p1.x= p1.y; p1.y= t;}
Swap(p1, p2);
CS100A, Lecture 23, 19
November 1998
14
Pointers and References
•C provides operator & to create a pointer to a variable
int x= 5;
int & p= &x;
p
x
•int & x;
5
The type of x is “int &”, read as
“address of int)
•C provides operator a “dereferencing” operator
If p is a pointer to an int variable, then * is the variable.
* p = * p + 1;
p
x
•int * x;
6
The type of x is “int *”, read as
“pointer to int”
CS100A, Lecture 23, 19
November 1998
15
Procedure to swap two integers
void swap(int & x, int & y) {
int tmp;
tmp= * x;
*x= *y;
*y= tmp;
}
The parameters are no long of type int, but instead
“point to int”.
Therefore, to reference the actual variables, use
&x and &y
CS100A, Lecture 23, 19
November 1998
16
Standard input
• Function scanf in library <stdio.h> reads from the
standard input device and deciphers the input characters
according to the format string given as the first
argument of a call.
• The remaining arguments of a call to scanf are pointers
to variables where the input values should be stored.
• As with printf, C compilers generally can’t (or don’t)
check that the types of the variables match the format
codes in the format string. A mismatch, usually a
mistake, can lead to mysteriously scrambled bytes in
memory or a program or machine crash.
CS100A, Lecture 23, 19
November 1998
17
Standard input Example
This program uses the earlier written function (see slide
12)to read in two integers and print their maximum.
void main(void) {
int j, k;
printf(“Please type in two integers”);
// read integers into j and k.
scanf(“%d &d”, &j, &k);
printf(“the larger of the two is\n %d”,
max(j,k));
Note that scanf f requires pointers to variables as
arguments!
CS100A, Lecture 23, 19
November 1998
18
Download