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 write lots of code.
Do reading. #include
■ Algorithms.
■ Libraries.
■ These are different skills and learning processes.
2
C Background An Example
Born along with Unix in the early 1970’s. Print a table of values of function f(x) = 2 - x3 . A first attempt:
■ One of most popular languages today. table1.c #include
■ 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 at. double x, y; '\n' is newline 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 more 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 type commands, you are controlling an % a.out Previous program repeats the same code over and over. abstract machine called the "Unix shell." 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 file 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
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, strings, 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 sum 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
16 17
Random M x N Pattern Random M x N Pattern
* * * * ** *** * ** ** Top-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
■ Depends on compiler and operating system. 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
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 make a bet cash--; Time Æ 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.
■ Find out how this changes for different values of c. gexperiment.c #include
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 wait 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.
■ Test 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
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
42 43