Vous êtes sur la page 1sur 65

CS3101-1

Programming
Languages - C
Lecture 1

Matthew P. Johnson
Columbia University
Fall 2003

10/17/08 CS3101-1, Lecture 1 1


Welcome
 6 weeks, in-class final exam
 2-hour sessions, w/short break
 First class: overview of Unix, C
 Others: 1 or two topics, in depth

10/17/08 CS3101-1, Lecture 1 2


Course Info
 1 credit 1/3 semester  same
bang/buck as usual (3000-level)
 O(4) homeworks – 70%
 Programming & written
 Final exam – 25%
 Participation/quizzes – 5%
 Quizzes on reading

10/17/08 CS3101-1, Lecture 1 3


Contact Info
 Class page:
http://www.columbia.edu/~mpj9/3101
 PPTs
 In-class examples
 Me: mpj9@columbia.edu
 OHs: Saturdays
 TA: Jacob Porway
 jmp204@columbia.edu
 OHs: see web
 Feedback is good!
 Prepend “CS3101-C” to subject lines!
10/17/08 CS3101-1, Lecture 1 4
Textbook
 The C Programming Language
 Second Edition (ANSI), 1988
 K&R
 Classic text by language’s
designers
 Available Papyrus, Amazon and
B&N (links on class page)
 Lectures will (roughly) follow text

10/17/08 CS3101-1, Lecture 1 5


IMPORTANT
 I’ll repeat your questions before
answering, for CVN
 If I forget, remind me!
 Get participation XC

10/17/08 CS3101-1, Lecture 1 6


Rest of this class
 Description & History of C
 Intro to Unix
 0th Homework
 C Tutorial

10/17/08 CS3101-1, Lecture 1 7


Description of C
 General-purpose language
 Procedural (= functions + data)
 Mid-level
 Relatively small, simple to learn
 C programs ~ Hemingway’s “tight,
athletic prose” (Scribner blurb)
 CU (and others) jumped from C to Java,
skipping C++
 Cross-platform language, single-platform
compilers (unlike Java)
 Char-based
10/17/08 CS3101-1, Lecture 1 8
History of C
 Developed by Dennis Ritchie at AT&T,
early 70s, for DEC PDP-11
 Unix written in, closely associated with, C
 Family of languages:
 BCPL, Martin Richards
 B (typeless), Ken Thompson, 1970
 C, Dennis Ritchie, Bell Labs, early 70s
 C++, Bjarne Stroustrup, Bell Labs, 80s
 Java, James Gosling Sun, 1995
 C#, Microsoft, recently
 C++, Java, C# conserve (much) C syntax
10/17/08 CS3101-1, Lecture 1 9
Why C?
 Prior to C, two broad types of languages:
 Applications languages
 High-level
 COBOL, etc.
 Portable but inefficient
 Systems languages
 Low-level
 Assembly
 Efficient but not portable
 Goal of C: efficient and portable
 How: abstract above hardware arch, but
not far!
10/17/08 CS3101-1, Lecture 1 10
Java v. C
 C is fast (in part) because there’s so little error-
checking
 ar[-2] or ar[100000] doesn’t throw an
exception
 just gives you read/write access where that
elm would be
 No garbage collection
 Con: must do (heap) memory management
yourself
 Pro: maybe you can do it better

 No boolean or string types


 Booleans “implemented” as numbers

 Strings are “just” char arrays

10/17/08 CS3101-1, Lecture 1 11


Why not Java,
C++, etc.?
 Java is safe and elegant, but slow
 C++ is unsafe and fast, but highly
complex
 C is unsafe, but succinct and fast
 C/C++ is still used for:
 Systems programming
 Windows, Unix, etc.
 Java bytecode interpreters

 High-perf back-end servers

10/17/08 CS3101-1, Lecture 1 12


Unix
 You don’t have to do your hw on cunix
 Can download Turbo C from class page
 But hw must be submitted with cunix
submit script;
 hw must compile on Unix (with cc/gcc) to
be graded
 Can Ftp and recompile before submitting
 Non-compiling hw will not be graded!
 Editors on cunix: Emacs, Pico, etc.

10/17/08 CS3101-1, Lecture 1 13


Programming with
Emacs/gcc
Create source file in $ emacs myprog.c
Emacs
Save file, exit Ctrl-X, Ctrl-S, Y
Compile $ gcc myprog.c  a.out
Compile with $ gcc myprog.c  a.out
executable name
Compile with with all $ gcc myprog.c –Wall
warnings on
Run executable $ a.out, $ a.out <
from.txt > to.txt

10/17/08 CS3101-1, Lecture 1 14


gcc tips
 Compile with warnings on –Wall
 Fix the first error first
 One typo can cause huge numbers
of errors

10/17/08 CS3101-1, Lecture 1 15


Unix Commands
Unix Windows
ls dir
cp copy
mv move
rm del
mkdir mk
cd cd
type type

10/17/08 CS3101-1, Lecture 1 16


Submitting from
cunix
 Instructions:
1) Put hw in its own directory
2) Re-compile
3) $ /opt/ACISsubmit/bin/submit cs3101-1
4) Wait for email confirmation
 Important:
 Omits binary files, *~ (backups)
 Submits all text files in and below current
directory
 Don’t submit from your ~ directory!
 Hw submitted by mail will not be graded!

10/17/08 CS3101-1, Lecture 1 17


Where to code
 On cunix: Emacs, Pico, etc.
 On Win: Textpad, fancy IDEs
 FTP: use utility, or put
ftp://newcunix.cc.columbia.edu in
IE address bar, log in, drag&drop

10/17/08 CS3101-1, Lecture 1 18


Homework 0
 Write, compile, and run a Hello,
World program
 Prints “Hello world, from <my
name>.”
 Hand in:
1. Source file
2. Readme file (with just your name)
3. Trace file($ hello > trace.txt)

10/17/08 CS3101-1, Lecture 1 19


Collaboration
Policy
 All subsequent work
 Must be done independently
 Collaboration = cheating
 Seescary CU cheating policies
  deans, honor committees, not fun

 This homework only


 Collaboration is fine
 Hw0 is instrumental: learn how to
compile & submit

10/17/08 CS3101-1, Lecture 1 20


C Tutorial
 Quick & dirty intro to language
 Learn to write by writing, learn to
program by programming
 First program: Hello, World
#include <stdio.h>
main() {
printf(“Hello, world.\n”);
}

10/17/08 CS3101-1, Lecture 1 21


C Tutorial –
Hello, World
 In Java, a program is >= 1 class
 In C, a program is >= 1 function
 In both, main() is the entry point
 Contains the instructions performed when
program is run
 The body of a ftn is demarcated by
braces (“curly brackets”): { }
 Inside, instructions to be performed
when ftn is called
 main() called on program start-up

10/17/08 CS3101-1, Lecture 1 22


C Tutorial -
#include
 Before main() function, we have
#include <stdio.h>
 Tells compiler where to look for printf()
function
 Operationally similar to Java’s import
 # indicates command to C Preprocessor
 #include line replaced with contents of file
 Usually a header file (.h)
 Acts as an interface describing the publicly
available functions in the .c file
 System .h’s in < >, one’s own in “ ”
10/17/08 CS3101-1, Lecture 1 23
C Tutorial –
printf()
 Our program contains one
statement: a call to printf()
 From “formatted print”
 Similar to Java’s
System.out.print()
 More complicated for non-strings
 Uses pattern-matching for
formatting (instead of OO)

10/17/08 CS3101-1, Lecture 1 24


C Tutorial -
Parameters
 We passed “Hello, World.\n” to
printf() as a parameter
 Tells function what to do
 In this case, what to print

 ‘\n’ is the new line escape

character
 Result is similar to Java’s

System.out.println()

10/17/08 CS3101-1, Lecture 1 25


C Tutorial – Esc
chars
 Stores internally \t Tab
as a char
\r Carriage
 A char-based
return
concept
\a Alarm bell
 Not
corresponding to \” “
any actual
character, or can’t \’ ‘
be represented
\\ \

10/17/08 CS3101-1, Lecture 1 26


C Tutorial -
Temps
 More complicated program - print table of
Fahr. – Cels. temperatures:

0 <0-in-Celsius>
20 <20-in-Celsius>
… …
300 <300-in-Celsius>
 Math?
 C = 5/9 * (F-32)

10/17/08 CS3101-1, Lecture 1 27


C Tutorial -
Temps
#include <stdio.h>
/* prints F-C table
*/
main() {
int fahr, cels;
int lwr, upr, step;
lwr = 0;
upr = 300;

fahr = lwr;
while (fahr <= upr) {
cels = 5*(fahr-32)/9;
printf(“%d\t%d\n”, fahr, cels);
fahr = fahr + step;
}
10/17/08 } CS3101-1, Lecture 1 28
C Tutorial -
Temps
 Things to notice:
 /* */ enclose comments – no
effect on program
 Some but not all compilers accept
// for single line comments
3. Var declarations
 Announce that fahr, etc, will be
names of pieces of data, of type int

10/17/08 CS3101-1, Lecture 1 29


C Tutorial -
Temps
 Var types determine what sort of
value a var can take on
 Other var types:
 long (large integers)
 floats (rational numbers)

 doubles (larger, higher precision

floats)
 chars

10/17/08 CS3101-1, Lecture 1 30


C Tutorial -
Temps
 Many data type sizes are …
undefined, i.e., compiler/machine-
dependent
 Restrictions (in bytes):
 |char| = 1 < |short| <= |int| <= |long|
 Often:
 |short| = |int| = 16  -32768…32767
 |long| = 32  -1038…1038

10/17/08 CS3101-1, Lecture 1 31


C Tutorial -
Temps
 Assignments
 Like in Java: value of RHS stored
in LHS
 lvalue = can appear on LHS of

assignment (e.g, vars)


 Statements terminated by ;
 More generally:
 Statement = expr + ;

10/17/08 CS3101-1, Lecture 1 32


C Tutorial -
Temps
 Table lines all of same form: two
numbers, such that columns are
aligned to the left
 print lines the same way
 Here using while loop
 Repeated evals test condition; if
passes test, execs while body
 While body is a statement or block
of statements

10/17/08 CS3101-1, Lecture 1 33


C Tutorial -
Temps
 Celsius computation line:
cels = 5*(fahr-32)/9;
 Why not this:
cels = 5/9*(fahr-32);?
 val1 and val2 are of the same type, 
the value of val1 op val2 will also be
of that type
 5 and 9 are ints  5/9 is an int
 5/9 as an int is just 0
 all Celsius temps become 0

10/17/08 CS3101-1, Lecture 1 34


C Tutorial -
Temps
 printf() line:
printf(“%d\t%d\n”, fahr, cels);
 First param to printf() is always
a string, with >=0 wildcards (%x)
 Subsequent params (suitably
interpreted & formatted) replace
corresponding wildcards in output
 %d – interpret as int, format as
decimal

10/17/08 CS3101-1, Lecture 1 35


C Tutorial –
Temps’
 Improvements:
 %d uses as much width as nec
  specify right-aligned widths:
printf(“%3d %6d\n”, f, c);
 %nd prints
 an int
 right-aligned

 in an n-length field

10/17/08 CS3101-1, Lecture 1 36


C Tutorial –
Temps’
  use floats for greater precision
float f = 0; float c = 0;
while (f <= upr) {
c = (5.0/9.0) * (f – 32.0);
printf(“%3.0f %6.1f\n”, f, c);
}
 %n.mf prints
 a float
 right-aligned
 in an n-length field
 with m digits past the decimal point
10/17/08 CS3101-1, Lecture 1 37
C Tutorial –
Temps’
 More succinct with a for loop:
main() {
int f;
for (f = 0; f <= 300; f += 20)
printf(“%3d %6.1f\n”, f,
(5.0/9)*(f–32));
}
 Notice:
 Fewer vars
 Sent expr (not var) to printf()
 Doesn’t use float in <= check
 Used +=

10/17/08 CS3101-1, Lecture 1 38


C Tutorial –
Temps’
 For loop pattern:
for (init; test; inc) {}

init;
while (test) {
/* body code */
inc;
}
 Restriction: cannot declare loop var in for
init (unlike in Java)

10/17/08 CS3101-1, Lecture 1 39


C Tutorial –
Temps’’
 In general: hard-coded, frequently
appearing literals (“magic numbers”)
are bad
 One soln: symbolic constants
 Defined with preprocessor – no ;
 Pattern: #define name replace-text
 Replaces all occurrences except:
 In “ ”
 In part of other name

10/17/08 CS3101-1, Lecture 1 40


C Tutorial –
Temps’’
 New version:
#define LOWER 0 /* … */
#define UPPER 300
#define STEP 20

main() {
int f;
for (f = LOWER; f <= UPPER;
f += STEP)
printf(“%3d %6.1f\n”, f,
(5.0/9)*(f–32));
}

10/17/08 CS3101-1, Lecture 1 41


Simple I/O -
countchars
 char c = getchar();
 Reads next char from stdio
 Keyboard/re-directed file (<)
 No intercap in name
 If end-of-file, returns EOF (= -1)

 For today: assume input from file

 putchar(c);
 Prints char to screen/re-directed
file (>)

10/17/08 CS3101-1, Lecture 1 42


Simple I/O -
countchars
main() {
long nc = 0;
while (getchar() != EOF)
++nc;
printf(“%ld\n”, nc);
}

10/17/08 CS3101-1, Lecture 1 43


Simple I/O –
countchars’
 Notice: %ld interprets as long
 Convert to for loop:
main() {
long nc;
for (nc = 0; getchar() != EOF; ++nc)
;
printf(“%ld\n”, nc);
}
 Notice: If EOF is first char, ++nc never
executed (“boundary condition”)
10/17/08 CS3101-1, Lecture 1 44
Line counting
main() {
int n, nl; char c;
nl = 0;
while ( (c = getchar()) != EOF)
if (c == ‘\n’)
++nl;
}

10/17/08 CS3101-1, Lecture 1 45


Line counting
 Notice:
2. Used compact form:
(c = getchar()) != EOF
 Every expr has a value
 Value of an assignment expr is the
value assigned
3. Equality testing:
if (c == ‘\n’)
 Would this have compiled:
if (c = ‘\n’)?
Yes!
10/17/08 CS3101-1, Lecture 1 46
Equality testing
 C has no boolean type!
  bools are represented by ints
 0  false
 !0 (anything but 0)  true
 Literally: !1 == 0, x != 0  !x == 1
 Conversely:
 “true” expression  1
 “false” expression  0
 Be careful with =, ==
 Turn on –Wall
 Lesson: = != ==
10/17/08 CS3101-1, Lecture 1 47
Parentheses
 We used parentheses:
while ( (c = getchar()) != EOF)
 What if we wrote
while (c = getchar() != EOF)
if (c == ‘\n’) ++nl;?
 Does it compile?
 Yes
 Does it work correctly?
 No
10/17/08 CS3101-1, Lecture 1 48
Parentheses
 Reason: = has lower precedence than !=
 != evaled first
 Consider cases:
 New char == EOF
 getchar() != EOF  0
 (c = getchar() != EOF)  0
 while check  false
 Similarly: getchar() != EOF 
(c = getchar() != EOF)  1, c == 1, while
check  true
 But: if-check is never true because c is
now set to 1
10/17/08 CS3101-1, Lecture 1 49
Parentheses
 Parentheses also required for
 If checks
 While checks

 (even parameter-less) Function calls

10/17/08 CS3101-1, Lecture 1 50


Arrays
 Simplest type of composite data
structure
 Ordered seq of vars of same type
 Goal: Count total number of each
digit, tabs, etc., in input

10/17/08 CS3101-1, Lecture 1 51


countchars
#include <stdio.h>

main() {
int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;
for (i = 0; i < 10; i++)
ndigit[i] = 0;

while ((c = getchar()) != EOF)


if (c >= ‘0’ && c <= ‘9’)
++ndigit[c-‘0’];
else if (c ==‘ ’ || c==‘\n’ || c==‘\t’)
++nwhite;
else
++nother;

10/17/08 CS3101-1, Lecture 1 52


countchars
(cont.)
printf(“digits: “);
for (i = 0; i < 10; ++i)
printf(“#%d: %d, ”, i, ndigits[i]);
printf(“\n#whitespace: %d, #other: %d\n”,
nwhite, nother);
}
 Notice:
 int array created by declaration (no new
operator)
 [10] goes after var name, not after type
 Must init array values (don’t assume 0)

10/17/08 CS3101-1, Lecture 1 53


ASCII chars &
digits
Notice: Array elms are lvalues
 We store digit counts in array, index ~ digit
 e.g., see char ‘2’  inc ndigit[2]

 What is relationship bet 2 & ‘2’?


 2 == ‘2’?
 No
 ‘2’ == some int corresponding to the char ‘2’
 ‘3’ == some int ~ the char ‘3’
== ‘2’ + 1
== ‘1’ + 1 + 1
== ‘0’ + 1 + 1 + 1
== ‘0’ + 3
 3 == ‘3’ – ‘0’
10/17/08 CS3101-1, Lecture 1 54
Arrays indices
 For c in {‘0’…’9’}, c-‘0’ turns out to be the
corresponding digit in {0…9}
 What if it didn’t?
 What if it was a non-int val?
 Compile error
 What if it was an int too small or too big?
 ndigit[800] or ndigit[-5]
 calcs where corresponding int would be
 reads/writes to that location  probably
crashes
 be careful!
10/17/08 CS3101-1, Lecture 1 55
else-if
 We had structure:
if (cond1)
stmt1;
else if (cond2)
stmt2;
else
stmt3;
 Notice:
 ; ends every statement

 No elseif keyword – just combine

 Whitepace doesn’t matter to compiler – just


make legible

10/17/08 CS3101-1, Lecture 1 56


Functions
 Group of instructions that can be
called repeatedly
 Similar to static methods in Java
 Exist independently of any
“objects” – no construction to call
 So far, seen only main function
 New ftn: C has no ^ (pwr) op – let’s
write a ^ ftn

10/17/08 CS3101-1, Lecture 1 57


Functions
 General form:
return-type name (parm-list) {
declars;
stmts;
optionally return val;
}

10/17/08 CS3101-1, Lecture 1 58


power
#include <stdio.h>
int power (int b, int exp);
main() {
int i;
for (i = 0; i < 10; ++i)
printf(“%d %d %d\n”,
i, power(2,i), power(-3,i);
}

10/17/08 CS3101-1, Lecture 1 59


power (cont.)
int power (int b, int exp) {

int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p *= b;
return p;
}

10/17/08 CS3101-1, Lecture 1 60


Functions
 Notice:
 Ftn states it’s I/O: params it takes, type of
val (if any) it returns
 Ftn should be defined or declared before
it is called
 Params are passed-by-val: change to
param in ftn is not seen by caller
 Syntax used to be:
power(base, n) {
int base, n; …

10/17/08 CS3101-1, Lecture 1 61


power’
 Take advantage of call-by-val:
int power(int b, int exp) {
int p;
for (p = 1; n > 0; --n)
p *= b;
return p;
}
 Removed one var
 Passed-in b not effected
 We can simulate pass-by-ref with pointers
– more later
10/17/08 CS3101-1, Lecture 1 62
Strings
 Like booleans, no built-in type
 Just arrays of chars – no other structure
 char s[] = “Hello\n”;
is shorthand for
char s[] = {‘H’, ‘e’, …, ‘o’, ‘\n’, ‘\0’};
 ‘\0’ is the null char
 Indicates end of string
 n-char string really uses n+1 bytes

10/17/08 CS3101-1, Lecture 1 63


Strings
 Nothing built-in to a string/array telling its
length, like s.length() in Java
 How to find out?
 For arrays (usually): remember!
 For strings: look for ‘\0’
i = 0;
for (i = 0; s[i] != ‘\0’; i++)
;
return i;

10/17/08 CS3101-1, Lecture 1 64


Next time
 Topics: Operators, Operands, &
Control Flow
 For next time:
1. Get your book
2. Skim chapter 1
3. Read chapter 2, 3
4. hw0

10/17/08 CS3101-1, Lecture 1 65

Vous aimerez peut-être aussi