<<

Learning to Program

Lecture P1: Introduction to C Programming is learned with practice and patience. ■ Don’t expect to learn solely from these lectures.

■ Do exercises.

■ Experiment and lots of code.

Do reading. #include int main(void) { ■ Finish King Chapters 1-6 today! printf("This is a C program.\n"); return 0; Aspects of learning to program. } ■ Language syntax.

■ Algorithms.

■ Libraries.

■ These are different skills and learning processes.

2

C Background An Example

Born along with in the early 1970’s. Print a table of values of function f(x) = 2 - x3 . A first attempt:

■ One of popular languages today. table1.c #include C Features.

■ Concise. int main(void) { double x, y; ■ Widespread usage.

■ Exposes low-level details of machine. printf(" x f(x)\n"); x = 0.0; y = 2.0 - x*x*x; Consequences. printf("%4.1f %6.3f\n", x, y); x = 0.1; ■ Positive: you can do whatever you want.  y = 2.0 - x*x*x; Flexible and powerful. printf("%4.1f %6.3f\n", x, y); ■ Negative: you can do whatever you want. . . .  Shoot yourself in the foot. x = 1.9; y = 2.0 - x*x*x; printf("%4.1f %6.3f\n", x, y); return 0; }

3 4 Printf Library Function Anatomy of Printf

Contact between your C program and outside world. %f to print double

■ Puts characters on "standard output."

■ By default, stdout is the "terminal" that you're typing . double x, y; '\n' is x = 0.927; character y = 2.2; Internally, all numbers represented in BINARY (0's and 1's). printf("%4.1f %6.3f\n", x, y); ■ printf() displays useful representation (int, double).

Formatted output. 4 6 ■ How do you want the numbers to look? – integers, how many digits? – real numbers, how many digits after decimal place? 0 . 9 2 . 2 0 0 ... ■ Very flexible.

1 3 space in printf statement

6 7

Running a Program in Unix Unix Anatomy of a While Loop % gcc table.c When you commands, you are controlling an % a.out Previous program repeats the same code over and over. abstract machine called the "Unix ." x f(x) ■ Repetitive code boring to write and hard to debug.

0.0 2.000 ■ Use while loop to repeat code. ■ Compile: convert the program from human's 0.1 1.999 language (C) to machine’s language. 0.2 1.992 – 1st try: syntax errors in C program 0.3 1.973 x ← 0 0.4 1.936 – eventually, a named a.out 0.5 1.875 x = 0.0; 0.6 1.784 while (x < 2.0) { 0.7 1.657 y = 2 - x*x*x; ■ Execute: start the machine. 0.8 1.488 (at first instruction in main) printf("%f %f\n", x, y); 0.9 1.271 y ← 2 - x3 x = x + 0.1; – 1st try: semantic errors in C program 1.0 1.000 true x < 2.0 print x, y } 1.1 0.669 – eventually, desired "printf" output x ← x + 0.1 1.2 0.272 C code 1.3 -0.197 1.4 -0.744 false 1.5 -1.375 1.6 -2.096 1.7 -2.913 1.8 -3.832 1.9 -4.859

9 10 While Loop Example Anatomy of a Function

Print a table of values of function f(x) = 2 - x3. A second attempt. Convenient to break up programs into smaller modules or functions.

■ Layers of abstraction.

table2.c ■ Makes code easier to understand. #include ■ Makes code easier to debug.

int main(void) { ■ Makes code easier to change later on. double x, y;

printf(" x f(x)\n"); 1.2f(x) = 2 - x3 0.272 x = 0.0; uses while loop while (x < 2.0) { Input Output y = 2.0 - x*x*x; printf("%4.1f %6.3f\n", x, y); x = x + 0.1; double f (double x) { } return 2 - x*x*x; } return 0; } C function

11 12

Anatomy of a Function Anatomy of a C Program

C function similar to mathematical function. table3.c

Prototype or interface is first line of C function. #include

■ specifies input argument(s) and their types double f (double x) { – can be integers, real numbers, , vectors, user-defined function return 2.0 - x*x*x; ■ specifies return value }

Body or implementation. output type function name int main(void) { assignment double x, y; ■ The rest, enclosed by { } statement function declaration printf(" x f(x)\n"); x = 0.0; double sum (double x, double y) { function call scratch space while (x < 2.0) { double z; flow control statement statements z = x + y; y = f(x); statement printf("%4.1f %6.3f\n", x, y); stop execution return z; input 2 input 2 x = x + 0.1; of function } type name }

return 0; output value }

13 14 Random Integers Random Integers

Print 10 "random" integers. Print 10 "random" integers between 0 and 599.

■ Library function rand() in stdlib.h returns integer between 0 ■ No precise match in library. and RAND_MAX (32,767 = 216 - 1 on arizona). ■ Try to leverage what's there to accomplish what you want. Unix int600.c int.c % gcc int.c Unix #include % a.out #include % gcc int600.c #include 16838 #include % a.out 5758 int randomInteger(int n) { 168 int main(void) { 10113 return rand() % n; p % q gives remainder575 int i; 17515 } of p divided by q 101 for (i = 0; i < 10; i++) 31051 175 printf("%d\n", rand()); 5627 int main(void) { 310 return 0; 23010 int i; 562 } 7419 for (i = 0; i < 10; i++) 230 16212 printf("%d\n", randomInteger(600)); 341 4086 return 0; 16 } 386

16 17

Random M x N Pattern Random M x N Pattern

* * * * ** *** * ** ** -down design.

* * * * * **** * *** ** ■ Break a big problem into smaller subproblems. * * * * * * * * * ■ Break down subproblems into sub-subproblems. * * * * * * *** ** * ** * * * * **** ** * * ■ Repeat until all details filled in. * * * * * * ** *** *** * * * * * *** * ** * loop M times * * * * * **** *** * ** print a random row * * * * * *** * ***

** ** * *** * * *** ** ** * * ** * * loop N times * ** ** ** * **** * * ** ** * ***** * * ** ** print a random element ** ** ** * **** * ** ** ** *** * *** * ** ** *** * ** ** ** * * * * * * if coin flip is heads print "*" ** ** ** * * * ** else print " "

18 19 randpattern.c Libraries #include #define M 9 How is library function printf() created? #define N 9 ■ User doesn’t need to know details (see COS 217). int randomInteger(int n) {...} ■ User doesn’t want to know details (abstraction). int main(void) { int i, j; Print random M x N pattern. How is library function rand() created? i = 0; while (i < M) { ■ Linear feedback shift register? Cosmic rays?

■ Depends on compiler and . j = 0; while (j < N) { ■ Caveat 1: "random" numbers are not really random. if (randomInteger(2) == 1) printf("*");  Can never have all properties of random bits. else printf(" "); Computers do exactly what we tell them to do!

j++; ■ Caveat 2: on many systems, our randomInteger()is very poor. } Print a random element. printf("\n"); Moral: check assumptions about library function. i++; } Print a random row. return 0; }

20 21

Gambler’s Ruin Gambler's Ruin

Simulate gambler placing $1 even bets. gambler.c #include ■ Will gambler always go broke. #include ■ If so, how long will it take if gambler starts with $c? int randomInteger(int n) { ... }

int main(void) { int cash, seed; scanf() takes scanf("%d %d", &cash, &seed); input from terminal srand(seed); srand() sets random seed Æ Æ $6 while I still have while (cash > 0) { money left, repeat

Cash if (randomInteger(2) == 1) cash++; else a bet cash--; Æ print money left printf("%d\n", cash); $0 } return 0; }

22 23 Gambler's Ruin Gambler's Ruin

Simulate gambler placing $1 even bets. Simulate gambler placing $1 even bets. Q. How long does the game last if we start with $c ? Q. How long does the game last if we start with $c ?

Unix Unix To print plot, replace: % gcc gambler.c % gcc gambler.c

% a.out % a.out % a.out % a.out printf("%d\n", cash); 4 543 4 1234 4 543 4 1234 33 *** *** 42 Hmmm. **** ** with 53 ***** *** 44 **** **** 33 *** *** i = cash; 44 **** **** while (i > 0) { 35 *** ***** printf("*"); 26 ** ****** 17 * ******* i--; 06 ****** } 7 ******* 8 ******** printf("\n"); 9 *********

24 25

Top-Down Design of Numerical Experiment Gambler’s Ruin Experiment

Goal: run experiment to see how long it takes to go broke.

out how this changes for different values of c. gexperiment.c #include #include for all initial cash values between 2 and 9 int randomInteger(int n) { ... } run numerical experiments single experiment int doit(int cash) { (code as before) int cnt = 0; while (cash > 0) { repeat 5 times if (randomInteger(2) == 1) how long before ruin? cash++; else cash--; cnt++; } do gambler’s ruin and return value return cnt; }

26 27 Gambler’s Ruin Experiment Gambler’s Ruin Experiment

Unix % gcc gexperiment.c gexperiment.c (cont) % a.out int main(void) { # bets int cash, t; 2 2 6 304 2 2 initial cash 3 33 17 15 53 29 cash = 2; 4 22 1024 7820 22 54 repeat for all initial while (cash < 10) { 5 243 25 41 7 249 cash values 2 to 9 printf("%2d ", cash); 6 494 14 124 152 14 t = 0; 7 299 33 531 49 93 while (t < 5) { 8 218 10650 36 42048 248 repeat 5 times printf("%7d", doit(cash)); 9 174090315 83579 299 759 69 t++; } printf("\n"); How long will it take to go broke? cash++;  Guaranteed to go broke, but expected is infinite! } Layers of abstraction. return 0; Æ Æ } ■ Random bit Æ gambler’s ruin sequence Æ experiment.

28 29

Programming Advice Debugging

Understand your program. Find the FIRST bug and fix it.

■ What would the machine do? Syntax error - illegal C program.

Read, understand, and borrow from similar code. ■ Compiler error messages are good - tell you what you need to change. Develop programs incrementally.

each piece separately before continuing. Semantic error - wrong C program.

■ ■ Plan multiple lab sessions. Use "printf" method.

Always a logical explanation.

Enjoy the satisfaction of a fully functional program!

30 32 Programming Style Summary

Concise programs are the norm in C. Lots of material.

Your goal: write READABLE and EFFICIENT programs. C is a structured programming language.

■ Use consistent indenting. ■ Functions, loops.

– automatic indenting in emacs ■ Simple but powerful tools.

■ Choose descriptive variable names.

■ Use comments as needed. Programming maturity comes with practice.

■ Everything seems simpler in lecture and textbooks.

■ Always more difficult when you do it yourself!

"Pick a style that suits you, then ■ Learn main ideas from lecture, learn to program by writing code. use it consistently."

-Kernighan and Ritchie

33 35

Anatomy of a While Loop

Lecture P1: Supplemental Notes The while loop is a common repetition structure.

while (condition) { statements; } while loop

true condition statements

false

37 Anatomy of a For Loop Anatomy of a Do-While Loop

The for loop is another common repetition structure. The do-while loop is not-so-common repetition structure.

for (expr1; expr2; expr3) { statements; do { initialize } statements; } while (condition) expression 1 statements do-while loop increment expression 3 loop-continuation condition true condition expression 2 statements true body false false

38 39

For Loop Example Final Attempt

Print a table of values of function f(x) = 2 - x3. A fourth attempt. Print a table of values of function f(x) = 2 - x3. A fifth attempt.

table5.c table4.c #include #include double f (double x) { int main(void) { return 2.0 - x*x*x; double x, y; }

printf(" x f(x)\n"); int main(void) { x += 0.1 is shorthand uses for loop for (x = 0.0; x < 2.0; x = x + 0.1) { double x; in C for x = x+ 0.1 y = 2 - x*x*x; printf("%4.1f %6.3f\n", x, y); printf(" x f(x)\n"); } for (x = 0.0; x < 2.0; x += 0.1) no need for { } if printf("%4.1f %6.3f\n", x, f(x)); return 0; only one statement return 0; } }

40 41 What is a C Program? Random Real Numbers

C PROGRAM: a sequence of FUNCTIONS that manipulate data. Print 10 "random" real numbers between 0.0 and 1.0.

■ main() function executed first. ■ No precise match in library.

■ Try to leverage what’s there to accomplish what you want. A FUNCTION consists of a sequence of DECLARATIONS followed by a sequence of STATEMENTS. real.c Unix ■ Can be built-in like printf(...).

■ Or user-defined like f(x) or sum(x, y). #include % gcc real.c #include % a.out A DECLARATION names variables and defines type. int main(void) { 0.513871 0.175726 ■ double double x; int i; for (i = 0; i < 10; i++) 0.308634 ■ integer int i; printf("%f\n", 1.0 * rand() / RAND_MAX); 0.534532 return 0; 0.947630 A STATEMENT manipulate data or controls execution. } 0.171728 ■ assignment: x = 0.0; 0.702231 0.226417 ■ control: while (x < 2.0) {...} Integer division: 16838 / 32767 = 0. 0.494766 ■ function call: printf(...); C has conversions for mixed types: 0.124699 1.0 * 15838 / 32767 = 0.513871.

42 43