lecture 7: functions - amazon s3€¦ · final hw due friday 12/4 5. cooking lesson lecture 7...
TRANSCRIPT
![Page 1: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/1.jpg)
ECE15: Introduction to Computer Programming Using
the C Language
Lecture 7: Functions
A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad
![Page 2: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/2.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 2
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 3: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/3.jpg)
#include <stdio.h> #include <math.h>
#define N 120 int main() { int i, p, sqrt_N; char sieve[N+1];
sqrt_N = (int) sqrt(N); for (i = 0; i < N+1; i++) sieve[i] = 1;
for (p = 2; p <= sqrt_N; p++) if (sieve[p]) for (i = 2; i <= N/p; i++) sieve[i*p] = 0;
printf("The prime numbers between 2 and %d are\n", N); for (i = 2; i <= N; i++) if (sieve[i]) printf("%d\n", i);
return 0; }
How Large is a Typical Program?
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 3
The programs encountered so far were fairly small
Complex tasks require large, complicated programs, often many thousands lines of code
![Page 4: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/4.jpg)
Modular Design
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 4
Break overall task into smaller modules, each constructed from even smaller ones: ‣Construct each part individually ‣Easier to debug, modify and understand ‣Reuse similar code parts in many places
Large programs - how to:
‣write? ‣ debug / modify? ‣make understandable? ‣ reuse repeated code segments?
Modular design
![Page 5: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/5.jpg)
HoMeWoRk
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Due Friday ❖ Next HW due over Thanksgiving Holiday ‣Can submit it as late as noon Monday 11/30
❖ Final HW due Friday 12/4
5
![Page 6: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/6.jpg)
Cooking Lesson
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6
Problem: Need to prepare a meal of spaghetti bolognese. Solve this complex problem by breaking it into smaller, easier, ones:
void spaghetti_bolognese() { prepare_spaghetti(); prepare_sauce(SPICY); mix(); serve(); }
void prepare_spaghetti() { boil_water(); add_spaghetti(); while(!ready) wait(2); }
+
![Page 7: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/7.jpg)
Modular Design in C: Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 7
"C has been designed to make functions efficient and easy to use. C programs generally consist of many small functions rather than a few big ones."
B. KernighanD. Ritchie
❖ Modular design implemented using functions ❖ Convenient way to encapsulate long computations ‣Accept parameters ‣Return a value
❖ In other languages: “procedures”, “routines”, “methods”
❖ Every C program is just a collection of functions
❖ Functions: ‣Make writing and modifying code easier ‣ Improve readability and facilitate debugging ‣Avoid code duplication and enable code reuse
Function Returned ValueParameters
Global Variables
![Page 8: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/8.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 8
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 9: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/9.jpg)
Three Ingredients of Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 9
return-type function-name(parameter-list) { variable definitions
statements // do what the function should do
return statement }
Body
Complete description of what function does Declaration (as above) Body - compound statement implementing the function
Declaration
Tells compiler what to expect Consists of name, parameters, and type of value returned
return-type function-name(parameter-list);
Computes the function function-name(parameter-list);
Declaration
Definition
CallExplain by Examples
![Page 10: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/10.jpg)
Basic Function❖ Example: Function squaring an integer
❖ Whole program
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 10
int square(int x);
int square(int x) { return x*x; }
Declaration
Definition
Call square(5);
Name Parameter list & type
Declaration
Returned-value type
Body
#include <stdio.h> int square(int x); int main() { int value, sqr; printf("Integer: "); scanf("%d", &value); sqr = square(value); printf("Square: %d\n", sqr); } int square(int x) { return x*x; }
square.c
Name Follows variable
name rules. Cannot be same as a variable in the program.
printf("Square: %d\n", square(value));
![Page 11: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/11.jpg)
What Happens
❖ main() executed
❖ Calls function
❖ Function executed from beginning { ❖ Continues till return ❖ Returns value following return
❖ Execution goes back to main
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 11
#include <stdio.h>
int square(int x);
int main() {
int value, sqr;
printf("Integer: "); scanf("%d", &value);
sqr = square(value);
printf("Square: %d\n", sqr); }
int square(int x) {
return x*x; }
Declaration
Call
Definition
![Page 12: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/12.jpg)
Multiple Parameters
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Functions can have multiple parameters
❖ Example: xn (n - nonnegative integer)
12
#include <stdio.h>
double power(double x, int n);
int main() { double base; int exponent; printf("base and power: "); scanf("%lf %d", &base, &exponent); printf("%g^%d = %g\n", base, exponent, power(base, exponent)); }
double power(double x, int n) { double p = 1.0; int i; for (i = 0; i < n; i++) p *= x; return p; }
power.c
Declaration
Call
Definition
2 parameters (note name difference)
![Page 13: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/13.jpg)
Multiple Return Statements
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 13
#include <stdio.h>
double abs_val(double y);
int main() { double v; printf("Type values, non numeric to exit: ");
while (scanf("%lf", &v) == 1) printf("%g\n", abs_val(v));
return 0; }
double abs_val(double x) { if (x<0) return -x; else return x; }
❖ Functions can have several return statements ❖ First return encountered ends computation and returns value
❖ Example: Absolute value of a double
Declaration
Call
Definition
Still returns
only one value!
abs_val.c
2 return statements
![Page 14: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/14.jpg)
Some functions perform a task and return no value Example: Function to facilitate and organize message printing Called with message index as parameter, prints appropriate message Does not return any value, void return value
Void fun’s can have return - but without value
void messages(int i) { switch (i) { case 0: printf("Finished successfully.\n"); break; case 1: printf("Input error.\n"); break; case 2: printf("Run-time error.\n"); break; default: printf("Invalid parameter.\n"); } }
No Return Value
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 14
#include <stdio.h>
void messages(int i);
int main() { ... if (..`bad input’..) messages(1); ... }
messages.c
No return
![Page 15: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/15.jpg)
Another Void Example
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Recall ordinal form of nonnegative integer (1st, 2nd, 24th,...)
15
#include <stdio.h>
void print_ordinal(int x);
int main() { int x; printf("Nonnegative integer: "); scanf("%d", &x); print_ordinal(x); return 0;
}
void print_ordinal(int x) {
int y=x%100, z;
if (y>=11 && y<=13) z=4; else z=x%10;
printf("Ordinal: %d%s\n", x, z==1 ? "st" : z==2 ? "nd" : z==3 ? "rd" : "th"); }
ordinal_fun.c
Seen in Lecture 4
Can easily print in many different
locations
can add “return;” (without any parameter)
![Page 16: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/16.jpg)
Void vs. Functions Returning Values
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Difference in return
‣Functions returning a value (int, double, etc.) typically have return X;
‣Functions returning nothing (void) have either NO return, or return;
❖ Difference in call ‣Functions returning value, have their return value utilized in the call:
‣Functions returning nothing, don’t have their value utilized in the call:
16
Some value
No value
int square(int x) {
return;
sqr = square(x); printf("%d", square(x));
messages(i);
return x*x;
void messages(int i) {
![Page 17: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/17.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 17
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 18: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/18.jpg)
Parameters
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ A function can have no parameters, declared by void
❖ Can also indicate by “nothing” (namely default parameter list is void)
❖ We have seen this default use before
❖ When parameters exist, default parameter type is int
‣may produce warning - best avoid
18
int getchar(void); int getchar();
int square(int x);
Check if declaration can have no parameter list and definition still does
int main();int main(void);
int square(x);
![Page 19: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/19.jpg)
Returned Values
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Functions terminate upon encountering any return, or final }
❖ Return a value of type specified in declaration
‣Always return one value, specified after return
‣ If multiple return statements, first encountered returns value
‣Returned value converted to declared type
‣ If there is no return by end of function, returns gibberish
❖ Functions can return no value
‣Declared as void
‣No return or nothing follows return
❖ Default return type is int (may produce warning)
19
void print_result(int x);
return;
getchar(); square(int);
int main(); main();
int square(int x);
return x*x;
return 5.9; 5
![Page 20: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/20.jpg)
Declarations
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Tell compiler of function prototype (parameters- and returned types) ❖ Must precede function call ❖ Must agree with definition on all types
❖ Since declaration just informs of types, can omit variable names
20
int square(int x);
int main() {...}
double square(float x) {...}
û ûint square(int);
int main() {...}
int square(int x) {...}
int power(int base, int exp);
int main() {...}
int power(int base, int exp){..}
int power(int, int);
int main() {...}
int power(int base, int exp){..}
Which is better?
![Page 21: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/21.jpg)
Main
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ No parameters (for now)
❖ Returns status code to operating system ‣ 0 - okay
❖ Must appear
❖ First function executed
21
int main( ){ ... }
return 0;
![Page 22: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/22.jpg)
❖ Functions typically appear sequentially, not inside other functions
❖ Order of functions does not matter
Order of Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 22
int main() {...}
int square(int x) {...}
int main() {... square(int x) {...} }
int square(int x) {...} int main() {...}
Except, they must be declared before called, see next slide
#include <stdio.h> int square(int x); int main() { int value; printf("Integer: "); scanf("%d", &value); printf("Square: %d\n", square(value)); } int square(int x) { return x*x; } square.c
#include <stdio.h> int square(int x); int square(int x) { return x*x; } int main() { int value; printf("Integer: "); scanf("%d", &value); printf("Square: %d\n", square(value)); }
much less
common
![Page 23: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/23.jpg)
Declaration and Definition
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Recall: Definition includes declaration information ❖ If definition appears before call, separate declaration not needed
23
int fact(int);
int main() { int n; printf("Factorialize: "); ... printf("%d!=%d\n", n, fact(n)); }
int fact(int n){ return n==1 ? 1 : n*fact(n-1); }
int fact(int n) { return n==1 ? 1 : n*fact(n-1); }
int main() { int n; printf("Factorialize: "); ... printf("%d!=%d\n", n, fact(n)); }
int sqr(int x); int main() { int n; printf("Integer: "); ... printf("Square: %d\n", sqr(n)); } int sqr(int x){ return x*x; }
int sqr(int x) { return x*x; } int main() { int n; printf("Integer: "); ... printf("Square: %d\n", sqr(n)); }
No declaration!!!
No declaration!!!
Definition b4 call
Definition b4 call
Definition after call Declaration needed
Definition after call Declaration needed
![Page 24: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/24.jpg)
Which Should Come First?
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Define functions first ❖ Avoids declarations & duplication ❖ Prepare ingredients before use ❖ Clean
❖ Don’t know which fun’s call others ❖ Some may call each other (risky!) ❖ Declare all functions first ❖ Then call in any order
24
#include <stdio.h>
int max(int a, int b) { ... } int min(int a, int b) { ... }
int main(){ max(x,y); ... }
#include <stdio.h>
int max(int a, int b); int min(int a, int b);
int main() { max(x,y); ... }
int max(int a, int b) { ... } int min(int a, int b) { ... }
Small Programs
Larger Programs
No declarations
![Page 25: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/25.jpg)
Relation Between Parameters
Lecture 2 ECE15: Introduction to Computer Programming Using the C Language
❖ Parameters passed according to location in list, not name
❖ Pass by value ❖ Variables inside and outside function bear no relation to each other ❖ Can have same name ❖ Modifying variable in function doesn’t affect same-name variable in main ❖ No worries about names in fun
25
int main() { int v=2, w=5, x=7; printf("%d\n", dbl(v)); printf("main: v=%d x=%d\n",v,x); printf("%d\n", dbl(w)); printf("main: v=%d x=%d\n",w,x); printf("%d\n", dbl(x)); printf("main: x=%d\n", x); return 0; }
#include <stdio.h>
int dbl(int x) {
printf("dbl-1: x=%d\n",x);
x *= 2;
printf("dbl-2: x=%d\n",x);
return x;
}
int fun(int x, int y) {return x/y;} fun(4, 2);
x=4; y=2;
fun(y, x);
2 0
param.c
No relation
![Page 26: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/26.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 26
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array Parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 27: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/27.jpg)
Conclusion:
gcd(a,b,c) = gcd(gcd(a,b), c)
GCD of Three Integers
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 27
Euclidean Algorithm computes greatest common divisor of two integers, gcd(a,b)
How to compute greatest common divisor of three integers, gcd(a,b,c)?
a b c gcd(a,b,c) gcd(a,b) gcd( gcd(a,b), c)36 24 18 6 12 640 60 25 5 20 59 6 5 1 3 1
Use euclidean algorithm twice
![Page 28: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/28.jpg)
Program with Functions
#include <stdio.h>
int gcd(int, int); int main() { int a, b, c, g_ab, g_abc;
scanf("%d%d%d", &a, &b, &c);
g_ab = gcd(a,b); g_abc = gcd(g_ab,c);
printf("gcd: %d",g_abc);
return 0; }
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 28
int gcd(int m, int n){ int remainder; while (n != 0) { remainder = m % n; m = n; n = remainder; } return m; }
gcd(a,b,c) = gcd(gcd(a,b), c)
Implement formula using the function gcd(m,n)gcd3.c
printf("gcd: %d\n", gcd(gcd(a,b), c));gcd3-short.c
Shorter?
❖Without functions, write gcd code twice
❖With functions - only once
![Page 29: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/29.jpg)
Newton Raphson
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 29
#include <stdio.h> #define MAX_ITERATIONS 10
double f(double x); double df(double x);
int main() { double x, fx, dfx; int i;
scanf("%lf", &x);
fa = f(x);
for (i = 0; i < MAX_ITERATIONS && (fx != 0); ++i) { fx = f(x); dfx = df(x); x -= fx/dfx; printf("Iteration: %d, Solution: %.12f\n", i, x); } printf("Solution is: %.12f\n", x); return 0; }
double f(double x) { return x*x-9; }
double df(double x) { return 2*x; }
Without functions, examine whole program With functions, change just relevant functions
nr_fun.c
![Page 30: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/30.jpg)
Archimedes-Pfaff πApproximation
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 30
b2n = 2*an*bn/(an+bn)
Perimeter of a circle: 2 πr =π
½ Perimeter of circumscribed n-gon: an
Perimeter of circumscribing n-gon: bn
For all n: an < π < bn
Johann Friedrich Pfaff
b4 = 4
a4 = 2√2
a8 = ?
b8 = ?
Archimedes
½
As n increases, approximation improves
a2n = an*b2n
![Page 31: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/31.jpg)
Original Program
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 31
#include <stdio.h> #define SR_ITER 35 #define PI_ITER 30 int main () { double a, b=4, x=1; int i, j; for (j = 0; j < SR_ITER; j++) { fx = x*x - 2; dfx = 2*x; if (dfx == 0) break; x -= fx/dfx; } a = 2*x; printf("a=%.15f b=%.15f\n",a,b); for (i=0; i<PI_ITER; i++) { b = 2*a*b/(a+b); x=1; for (j=0; j < SR_ITER; j++) { fx = x*x - a*b; dfx = 2*x; if (dfx == 0) break; x -= fx/dfx; }
pi.c
a = x; printf("a=%.15f b=%.15f\n", a,b);
} return 0; }
# iterations for square root
# iterations for pi
Simpler with functions
sqrt(2)
sqrt(a*b)
![Page 32: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/32.jpg)
Approximating π- with Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 32
#include <stdio.h> #define PI_ITER 30 double sqrt(double); int main () { int i; double a, b=4; a = 2*sqrt(2); printf("a=%.15f b=%.15f\n",a,b); for (i=0; i<PI_ITER; i++) { b = 2*a*b/(a+b); a = sqrt(a*b); printf("a=%.15f b=%.15f\n",a,b); } return 0; }
#define SR_ITER 35 double sqrt(double a) { int i; double x=1, fx, dfx; for (i=0; i<SR_ITER; i++) { fx = x*x - a; dfx = 2*x; if (dfx == 0) break; x -= fx/dfx; } return x; }
pi_fun.c
![Page 33: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/33.jpg)
Task: Compute area of a circle of radius r Function pi()calculates π iteratively Called from main() to evaluate circle area
Area of a Circle
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 33
#include <stdio.h>
double pi(void); double sqrt(double);
int main() { double r;
printf("Radius: "); scanf("%lf",&r);
printf("Area: %20.15f\n", pi()*r*r); return 0; }
double pi(void) { double a,b; int i; b = 4; a = 2*sqrt(2); for (i=0; i<20; i++) { b = 2*a*b/(a+b); a = sqrt(a*b); } return a; }
circle_area.c
#define SR_ITER 35 double sqrt(double a) { int i; double x=1, fx, dfx; for (i=0; i<SR_ITER; i++){ fx = x*x - a; dfx = 2*x; if (dfx == 0) break; x -= fx/dfx; } return x; }
![Page 34: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/34.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 34
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 35: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/35.jpg)
❖ What happens when the function is called? Memory allocated to function parameters double x and double y
Expressions 9.9*a and 2/lambda evaluated. Evaluation order unspecified.
Resulting values assigned (copied into) variables double x and double y. Type conversions performed as needed.This is known as call by value*. All functions in C are called by value.
Memory allocated to variables declared inside the function body, and the function-body block is executed.
What Happens at Function Call?
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 35
Called as:
double my_function(double x, double y) {...};
z = my_function(9.9*a, 2/lambda);
* Alternative is call by reference where, as in PERL, a reference to the variable (e.g. its address) is passed to function. In C, the reference can be passed via pointers (next lecture).
![Page 36: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/36.jpg)
What Happens at Function Return?
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 36
Again:
Called as:
double my_function(double x, double y) {...};
z = my_function(9.9*a,2/lambda);
What happens when the function returns? If function contains function execution stops when the (first such) statement is reached.
expression evaluated, its type converted to double if needed, result is assigned to the variable z.
If a statement is never reached, execution stops with the closing brace of the function, z assigned arbitrary value.
In both cases, all memory allocated to the function parameters and local variables is released, and calling program continues with next statement
return expression;
return expression;
![Page 37: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/37.jpg)
51?
int gcd(int m, int n) { ...
return m; }
int foo(void) { ...
d = gcd(9-1,2); return gcd(5,d); }
Function Call & Return: Example
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 37
8
nm ??
d ?
22
1
8 22
2
Recall gcd(int m, int n), computing the greatest common divisor of two integers using the Euclidean algorithm
nm ?2
0
0
![Page 38: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/38.jpg)
?? 434 3
Cannot Change Calling Parameters
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 38
x y?
x y43
temp
3
void swap(int x, int y) { int temp = x;
x = y;
y = temp; }
int main(void) { int x = 3, y = 4;
swap(x,y); }
Example: A function that swaps the values of x and y
Unchanged!
When f(x) calls a function f(int y), value of x copied into y f has no access to x f cannot change x
Swapping jinxed!
Next Lecture Changing
calling parameters
![Page 39: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/39.jpg)
What does the following program print?
Two Quizzes
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 39
#include <stdio.h>
int f(int x) { return (++x); } int main(void) { int a = 0; printf("f(%d) = %d\n", a, f(a));
printf("a = %d\n", a); return 0; }
f(0) = 1a = 0
Why can’t work? int x; scanf("%d", x);
A:
B:
![Page 40: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/40.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 40
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 41: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/41.jpg)
#include <stdio.h>
int abs_val(int x) { return x>0 ? x:-x; }
int main() { int i, myArray[5]={-1, 2, -3}; for (i=0; i<5; i++) myArray[i] = abs_val(myArray[i]); for (i=0; i<5; i++) printf("%d ",myArray[i]); printf("\n"); return 0; }
Array Elements as Parameters
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 41
array1.c
pass i’th element
❖ Both array elements, and whole arrays can be function parameters
❖ To pass an array element as parameter, just pass: array[ ]
regular int parameter
Example: Replace all array elements by their absolute value, print all
![Page 42: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/42.jpg)
Whole Arrays as Parameters
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 42
void printAll(int ar[], int length){ for (int i=0; i<length; i++) printf("%d ",ar[i]); printf("\n"); return; }
❖ To pass a whole array as function parameters, pass array name ❖ Need to pass length too!
#include <stdio.h> void absAll(int ar[], int length){ for (int i=0; i<length; i++) ar[i] = ar[i]>0 ? ar[i] : -ar[i]; return; }
array2.c
int main() { int myArray[5]={-1, 2, -3}; absAll(myArray, 5); printAll(myArray, 5); return 0; }
length passed separately
length passed separately
array parameter
length passed separately
length passed separately
array parameter
pass whole array, no []pass whole array, no []
Surprise?
Function modified array
elements!
Unlike regular variables (int, etc.), array parameters can be changed
by called functions. More in next lecture
![Page 43: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/43.jpg)
Both Elements and Whole Arrays
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 43
❖ Like previous examples, show both elements and whole array parameters ❖ Element param’s (absAll to absVal): declare as int, pass as array[i] ❖ Array param’s (main to absAll, printAll): decl. int ar[], pass myArray
#include <stdio.h> int absVal(int x){ return x>0 ? x : -x; }
array3.c
int main() { int myArray[5]={-1,2,-3}; absAll(myArray, 5); printAll(myArray, 5); return 0; }
void absAll(int ar[], int length){ for (int i=0; i<length; i++) ar[i] = absVal(ar[i]); return; } void printAll(int ar[], int length){
for (int i=0; i<length; i++) printf("%d ",ar[i]); printf("\n"); return; }
pass element
pass arraypass array
declare element
declare array
declare array
myArray modified by absAll!
Again note that a function can modify array parameters!
More next lecture
![Page 44: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/44.jpg)
Declaration Need not Include Name
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Example: Read array and calculate smallest element ❖ Recall: Declaration does not require parameter names ❖ This holds also for array parameters
44
#include <stdio.h> int smallest(int [], int);
void readAll(int [], int);
int main() { int num_elts; printf("# elements: "); scanf("%d", &num_elts); int array[num_elts]; readAll(array, num_elts); printf("%d is smallest\n", smallest(array, num_elts)); return 0; }
smallest.c
int smallest(int array[], int num) { int i, min=array[0]; for (i=1; i<num; i++) if (array[i]<min) min=array[i]; return min; }
void readAll(int ar[], int num) { for (int i=0; i<num; i++) scanf("%d", &ar[i]); return; }
Again note that readAll can
modify the array
Small functions make for more readable code!
![Page 45: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/45.jpg)
Passing 2-dimensional Arrays
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 45
#include <stdio.h> #define SIZE 3 void transpose(int ar[][SIZE]); void printMatrix(int [][SIZE]); int main() { int mat[][SIZE] = {1,2,3,4,5,6,7,8,9}; printf("Matrix:\n"); printMatrix(mat); transpose(mat); printf("Transpose:\n"); printMatrix(mat);
return 0; }
void transpose(int a[][SIZE]) { int i, j, temp; for (i=1; i<SIZE; i++) for (j=0; j<i; j++) { temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; }
void printMatrix(int b[][SIZE]) { int i, j; for (i=0; i<SIZE; i++) for (j=0; j<SIZE; j++) printf("%d %s", b[i][j], j==SIZE-1? "\n":""); }
transpose2.c
2-d array parameter width necessary
2-d array parameter width necessary!
pass array
2 definition styles
2 declaration styles
parameter name within function can be arbitrary
![Page 46: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/46.jpg)
Passing a Row of a 2-dim Array
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 46
int main() { int i, two_dim_array[NR][NC]; initialize(two_dim_array); for(i=0; i<NR; i++) { printf("Row %d: ", i); print_one_dim(two_dim_array[i], NC); } return 0; }
#include <stdio.h> #define NR 3 // number of rows #define NC 4 // number of columns
void initialize(int array[][NC]){ for (int i=0; i<NR; i++) for (int j=0; j<NC; j++) array[i][j]=i*NC+j; return; }
row.c
void print_one_dim(int array[], int length) { for (int i=0; i<length; i++) printf("%d ", array[i]); printf("\n"); return; }
1-d array
2-d array
pass one row of a 2-d array
pass whole 2-d array
2-d array
Initialize a 2-d array
Print it line by line
To pass row i of a 2-d array, pass array[i]
![Page 47: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/47.jpg)
A picture is worth a 1000 bytes
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 47
Cow getting out of focus?
Pictures represented as a 2-d array. Each location corresponds to a picture element (pixel) Its value indicates the color, 0 for black to 255 for white
What’s the connection?
Relevance
Image processing is an important application of programming
How to blur a picture?
Replace each pixel by the average of its surrounding pixels
![Page 48: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/48.jpg)
Blurring Example
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 48
62 77 88 87 65 82 60 101 91 95
77 103 64 85 59 94 65 104 111 81
73 71 64 200 179 173 200 205 78 81
58 108 72 185 186 163 166 161 71 49
93 98 75 170 175 192 174 177 86 78
75 46 79 178 173 181 172 177 68 85
83 50 91 38 74 64 99 80 103 65
64 66 84 82 72 74 76 66 92 60
65 72 49 77 61 45 59 60 57 72
80 75 85 66 94 91 58 68 65 59
Pixel value will be replaced by average of 9 surrounding
ones (here 112)
At edges average over fewer neighbors
![Page 49: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/49.jpg)
Blurring Example
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 49
80 79 84 75 79 71 84 89 97 95
77 75 93 99 114 109 120 113 105 90
82 77 106 122 147 143 148 129 105 79
84 79 116 145 180 179 179 146 110 74
80 78 112 144 178 176 174 139 106 73
74 77 92 117 138 145 146 126 102 81
64 71 79 97 104 109 110 104 88 79
67 69 68 70 65 69 69 77 73 75
70 71 73 74 74 70 66 67 67 68
73 71 71 72 72 68 64 61 64 63
After blurring:
![Page 50: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/50.jpg)
Declarations, main and inBound
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 50
#include<stdio.h> #include<stdbool.h>
#define M 10 // # rows #define N 10 // # columns
int inBound(int i, int j); int meanAroundPixel(int picture[][N], int i, int j); void copy2dArray(int from[][N], int to[][N]); void blurPicture(int picture[][N]);
int main() { ... int picture[M][N] = {...}; blurPicture(picture); ... }
blur.c
int inBound(int i, int j) { // is pixel inside picture? if(i < 0 || i >= M || j < 0 || j >= N) return false; return true; }
![Page 51: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/51.jpg)
mean, copy, blur
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 51
int meanAroundPixel(int picture[][N], int i, int j) { int ii, jj, sum = 0, neighbors = 0; for(ii = i-1; ii <= i+1; ii++) for(jj = j-1; jj <= j+1; jj++) if(inBound(ii,jj)) { sum += picture[ii][jj]; neighbors++; } return (int)((double)sum / neighbors + 0.5); }
void blurPicture(int picture[][N]) { int i, j; int blurred[M][N];
for(i = 0; i < M; i++) for(j = 0; j < N; j++) blurred[i][j] = meanAroundPixel(picture,i,j);
copy2dArray(blurred, picture); }
void copy2dArray(int from[][N],
int to[][N]) { int i, j;
for(i = 0; i < M; i++) for(j = 0; j < N; j++) to[i][j] = from[i][j]; }
![Page 52: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/52.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 52
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 53: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/53.jpg)
Header Files
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ In large programs, declarations provided in separate files
❖ Called header files (.h)
❖ Contain function declarations (rarely, also definitions)
❖ C standard library defines several: stdio.h, stdlib.h, math.h
❖ Included using #include directive
❖ Equivalent to typing the header file in that location
53
#include <stdio.h> // declarations of input/output functions #include <math.h> // declarations of mathematical functions
![Page 54: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/54.jpg)
stdio.h
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ #include <stdio.h>
❖ int scanf(...)
‣Reads input ‣ returns # values read
❖ int printf(...)
‣Prints output ‣Returns # characters written
❖ int getchar(void)
‣Reads and returns one input character
‣int, so it can hold EOF (end of file, next lecture)
❖ int putchar(char)
‣Writes one character ‣ If successful, returns printed char, otherwise returns EOF
54
int main() {
int a;
a=5;
return 0; }
#include <stdio.h>
int main() { int a;
a=5;
printf("%d", a);
return 0; }
No stdio.h
stdio.h needed
![Page 55: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/55.jpg)
stdbool.h
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 55
> locate stdbool.h /usr/include/stdbool.h > more /usr/include/stdbool.h stdio.h
similar but much more
complex
![Page 56: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/56.jpg)
Math.h
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ #include <math.h> ❖ Some systems: gcc -lm program.c ❖ Rounding ‣double ceil(double) - Ceiling ‣double floor(double) - Floor ‣double round(double) - Closest, half away from 0
❖ Arithmetic ‣double sqrt(double) - square root ‣double pow(double x, double y) - xy
❖ Trigonometric ‣double cos(double)- cosine ‣double sin(double)- sine
❖ Exponential ‣double exp(double x)- ex ‣double log(dbl.), log2(dbl.), log10(dbl.) - logarithms
56
![Page 57: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/57.jpg)
Some math.h Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 57
#include <stdio.h> #include <math.h>
int main() { double x, y;
printf("x, y: "); scanf("%lf , %lf", &x, &y);
printf("square root of %g: %g\n", x, sqrt(x));
printf("round of %g: %g\n", y, round(y));
printf("%g^%g: %g\n", x, y, pow(x,y));
return 0; }
math.c
![Page 58: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/58.jpg)
Negative, Prime, Square, or ...?
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 58
#include <stdio.h>
#include <math.h> int IsSquare(int);
int IsPrime(int);
int main() { int num;
while (scanf("%d", &num) == 1)
if (num < 0) printf("%d is negative\n", num);
else if (IsSquare(num)) printf("%d is a square\n", num);
else if (IsPrime(num)) printf("%d is a prime\n", num);
else printf("%d is a regular Joe\n", num); return 0; } numbers.c
int IsSquare(int n) { int sq = (int) round(sqrt(n));
return (sq*sq == n); }
Determine if an integer is prime, square, negative, or none of the above
int IsPrime(int n) {...}
Wrote several versions
![Page 59: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/59.jpg)
πRevisited
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Getting π via math.h
❖ How to find functions in math.h ?
59
#include <stdio.h> #include <math.h>
int main() { printf("Pi from:\n "); printf("atan: %.15f\n", 4*atan(1.)); printf("asin: %.15f\n", 2*asin(1.));
// Following not part of standard, system dependent printf("definition: %.15f\n", M_PI); return 0; }
pi_math.c
![Page 60: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/60.jpg)
stdlib.h
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ #include <stdlib.h> ❖ int abs(int) - absolute value ❖ int exit(int) - exists program (useful inside functions) ❖ int rand() - random integer in [0,RAND_MAX] ❖ void srand(unsigned int) - seeds rand
❖ Can seed with time (time in seconds since creation of Unix)
60
#include <stdio.h>
int main() { int i; srand(777); for (i=0; i<5; i++) printf("%d\n", rand()); return 0; }
random.c
srand(time(NULL));
Actually rand and srand don’t need stdlib.h(but RAND_MAX requires stdlib)
See also clock.c
How to generate a random number between 1 and 6?
![Page 61: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/61.jpg)
Creating Your Own Library
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Store declarations and definitions in library.h (or relevant name)
❖ Begin program with #include "library.h"
❖ Searches for library in current directory
❖ <file.h> searches in C library directory
‣ On mac: /usr/include
61
int min(int, int); int max(int, int);
int min(int x, int y) { return x<y ? x : y; }
int max(int x, int y) { return x>y ? x : y; } functions.h
#include <stdio.h> #include "functions.h"
int main() {
printf("min(3,7)=%d\n", min(3,7)); printf("max(3,7)=%d\n", max(3,7));
return 0; } minmax.c
Typically definitions stored separately (next slide). This
is just an example showing the “included” file is simply copied.
![Page 62: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/62.jpg)
Typical Large Programs
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ library.h contains only declarations ❖ Definitions stored separately in library.c or another .c file
❖ To compile: creates a.out
❖ Alternatively, create object code with -c option: - creates mm.o, fun.o
❖ To link, compile either .o or .c files - or create a.out
❖ Advantages: Efficient, doesn’t re-compile all, can hide source code 62
int min(int x, int y) { return x<y ? x : y; }
int max(int x, int y) { return x>y ? x : y; }
fun.c
#include <stdio.h> #include "fun.h"
int main() {
printf("min(3,7)=%d\n", min(3,7)); printf("max(3,7)=%d\n", max(3,7));
return 0; }
mm.cint min(int, int); int max(int, int);
fun.h
> gcc -c mm.c fun.c
> gcc mm.o fun.o > gcc mm.c fun.o
> gcc mm.c fun.c
![Page 63: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/63.jpg)
Another Multiple-File Example
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 63
> gcc part1.c part2.c part3.c
#include <stdio.h> void p2(); int main() { printf("main calling p2\n"); p2(); printf("main exiting\n");
return 0; }
part1.c #include <stdio.h> void p3(); void p2() { printf("p2 calling p3\n"); p3(); printf("p2 returning to main\n"); }
part2.c
#include <stdio.h> void p3() { printf("p3 returning to p2\n"); }
part3.c
#include in all files where needed
> gcc -c part1.c part3.c > ls part* part1.c part1.o part2.c part3.c part3.o > gcc part1.o part2.c part3.o
Declare fun. if not defined b4 call
![Page 64: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/64.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 64
Outline❖ Mechanics
‣Call ‣Return ‣Calling variables unchangeable
❖ Array Parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Multiple files ‣ C standard library ‣ Your library ‣Multiple files
❖ Variable Storage classes ‣ Local ‣ static ‣Global
❖ Recursion
![Page 65: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/65.jpg)
Scope: Subset of lifetime when variable is visible (accessible)
Lifetime: When memory is allocated (variable is born) and when released (variable ceases to exist)
Storage Classes
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 65
Variable attributes
‣Size (# bytes) allocated ‣ Interpretation of binary string stored ‣Operations permitted on variable
Three storage classes
local - live & visible locally, those we’ve seen, most common static - live throughout program, visible locally global- live & visible throughout program
So far: Type (int, char, double)
Storage class
Determine
Next:
![Page 66: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/66.jpg)
Lifetime & scope: From declaration till exit from block
Declared inside a block (several statements surrounded by {..})
Local Variables
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 66
All variables we have seen were local
int main(void){ int n=0; n++; int sqrt_n = sqrt(n); return 0; }
int foo(double x) { int n; return x+n; }
Remark: Also called automatic variables, declaration can be preceded by keyword auto (seldom used)
int main(){ int k=1; for (int i=0; i<3; i++) { double x=i+3; printf("%d %d %f", k, i, x); } double z=2; { double x = 5.0; printf(“%d %f %f”, k, z, x); } printf(“%d %d %f”, k, z); }
Most common storage class
![Page 67: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/67.jpg)
Masking
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 67
What if a sub-block contains a variable of the same name as its parent block?
Inside the block, once the internal variable is declared, it gets used
When internal block is exited, original variable returns to scope
Original variable continues to exist, but is temporarily out of scope
int main() { int a=1, b=2, c=3; { printf("a=%d b=%d c=%d",a,b,c); int a = 4; double b = 5.0; a = b; c = 6; printf("a=%d b=%g c=%d",a,b,c); int c=7; printf("a=%d b=%g c=%d",a,b,c); } printf("a=%d b=%d c=%d", a,b,c); }
mask.c
1 2 3
5 5 6
5 5 7
1 2 6
![Page 68: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/68.jpg)
{ int a = 1, b = 2, c = 3; printf(“%3d %3d %3d\n”,a,b,c); { int b = 4; double c = 5.0; printf(“%3d %3d %3f\n”,a,b,c); a = b; { int c; c = b; printf(“%3d %3d %3d\n”,a,b,c); } printf(“%3d %3d %3f\n”,a,b,c); } printf(“%3d %3d %3d\n”,a,b,c); }
Quiz
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 68
What does the following block print?
1 2 3
1 4 5.0
4 4 4
4 4 5.0
4 2 3
4x
![Page 69: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/69.jpg)
{ int a = 1, b = 2, c = 3; printf(“%d %d %d\n”,a,b,c); { int b = 4; double c = 5.0; printf(“%d %d %f\n”,a,b,c); a = b; { int c; c = b; printf(“%d %d %d\n”,a,b,c); } printf(“%d %d %f\n”,a,b,c); } printf(“%d %d %d\n”,a,b,c); }
Variable Stack
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 69
Local variables are actually stored in a variable stack. They are pushed in when they are born, and popped out when they die.
Variable Stack
c 4
c 5.0b 4c 3b 2a 1a 4
c
![Page 70: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/70.jpg)
❖ Local variables that never die..
❖ Declared inside a block:
❖ Initialized only once, even if the block is entered many times ❖ Initialized to zero by default
Static Variables
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 70
void toggle_light(void) { static int light = ON; if (light == OFF){ turn_light(ON); light = ON; } else { turn_light(OFF); light = OFF; } }
scope: same as local variables
lifetime: from allocation till end of program
static int n; static double x = 0.5;
Example: toggle a light
#define OFF 0 #define ON 1
Declaration, memory allocation, and initialization performed once, even if function called many times.
![Page 71: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/71.jpg)
#include <stdio.h>
void f(void) { static int count; // initialized to 0 printf("%d ", ++count); }
int main() { int i; for(i = 0; i < 5; i++) f(); for(i = 0; i < 5; i++) f(); return 0; }
Two Applications
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 71
Count # times a function is called during program’s execution
1 2 3 4 5 6 7 8 9 10
void g(void) {
static bool first_time = true; if (first_time) { ... // initialize on first call first_time = false; } ... // after initialization }
Initialize functions
count.cInitialized once
Initialized once
![Page 72: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/72.jpg)
Global Variables
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 72
❖Declared outside all blocks
❖Here too scope can be masked by local variables of same name
❖Can be used to communicate with functions, instead of parameters
❖ Initialized to 0
Scope: same - from allocation till end of program Lifetime: from allocation till end of program
Example
#include <stdio.h>
int x;
void f() { printf("%d\n", x+=2); }
int main() { printf("%d\n", x+=5); f(); printf("%d\n", x+=10); }
globalExample.c
5
7
17
![Page 73: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/73.jpg)
External Variables in Multiple Files
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Variables must be declared in files where used ❖ Local and static variables used in one function, hence in one file ❖ Global variable can be used in different functions, hence different files
‣ If not defined in a file where used, must be declared there as extern
‣Can be defined only once, but can be declared (extern) many times
73
#include <stdio.h> int x; int main() { f(); printf("x=%d\n", x); return 0; } extern1.c
extern int x;
void f() {
x++;
} extern2.c
![Page 74: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/74.jpg)
Quiz
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ What gets printed?
74
Sometimes convenient Confusing and risky! Use sparingly
#include <stdio.h>
int x = 20, y;
void f1(int x) { printf("x=%d y=%d\n",x,y); y = 11; x = 33; }
void f2(int x) { printf("x=%d y=%d\n",x,y); x = 45; y = 15; }
int main() { printf("x=%d y=%d\n",x,y); y = 5; f1(12); printf("x=%d y=%d\n",x,y); f2(y); x = 74; printf("x=%d y=%d\n",x,y); return 0; }
global.c
x=12 y=5
x=20 y=11
x=11 y=11
x=74 y=15
x=20 y=0
5x 11xx 15
![Page 75: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/75.jpg)
Debugging
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Global variables convenient for debugging ❖ Can print many variables from anywhere without passing all of them ❖ Here printAll has a single parameter but prints several
75
#include <stdio.h> int i, val; void printAll(char a[]) { printf("%s iteration=%d value=%d\n", a, i, val); } int main() { val=7; printAll("Before loop"); for (i=0; i<5; i++) { val+=2; printAll("Inside loop"); } printAll("After loop"); return 0; }
debug.c
![Page 76: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/76.jpg)
Area of TrianglesInput: Vertex coordinates of several triangles Output: Area of each triangle, largest area, # multiplications
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 76
a = d 1
2
b = d13
c = d23
x1, y1
x2, y2
x3, y3
Heron of AlexandriaHeron’s formula
![Page 77: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/77.jpg)
double tri_area(double x1, double y1, double x2, double y2, double x3, double y3) { double d12, d13, d23; d12 = distance(x1, y1, x2, y2); d13 = distance(x1, y1, x3, y3); d23 = distance(x2, y2, x3, y3); return heron(d12, d23, d13); }
Declarations and Functions
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 77
double distance(double x1, double y1, double x2, double y2) { count += 2; return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); }
double heron(double a, double b, double c) { double p = (a + b + c)/2; count += 3; return sqrt(p * (p-a) * (p-b) * (p-c)); }
#include <stdio.h> #include <math.h> int count; // count # multiplications, init 0
triangles.c
global variable
Distance between (x1,y1) and (x2,y2)
area of triangle whose sides have lengths a, b, c
area of triangle whose vertices are (x1,y1), (x2,y2), and (x3,y3)
![Page 78: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/78.jpg)
main()
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 78
int main() { double x1, x2, x3, y1, y2, y3, max_area = 0; while (scanf("%lf%lf …",&x1,&y1,&x2,&y2,&x3,&y3)==6) { double area = tri_area(x1, y1, x2, y2, x3, y3); if (area > max_area) max_area = area; printf("Triangle (%f,%f) (%f,%f) (%f,%f) has area %f\n", x1, y1, x2, y2, x3, y3, area); printf("%d multiplications so far.\n", count); } printf("Largest area: %.2f\n\n", max_area); return 0; }
global variable
local variable
a.out < triangles.datReading input from a file:
![Page 79: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/79.jpg)
Summary of Storage Classes
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 79
Local Static Global
Declaration int sum = 0; inside a block
static int sum; inside a block
int sum; outside all blocks
Lifetime To end of block To end of program To end of program
Scope To end of block To end of block To end of program
Initialization Not initialized Once, to zero Once, to zero
Can be masked
![Page 80: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/80.jpg)
Quiz
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Question: Global & static variables initialized, local are not - why? ❖ Answer: Efficiency. Global and static initialized once, local may be
initialized many times.
80
![Page 81: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/81.jpg)
❖ Modular Design ‣Why modularity ‣ Functions
❖ Functions ‣ Declaration ‣ Definition ‣ Call
❖ Details ‣ Parameters ‣ Declaration ‣Order
❖ Revisits ‣ gcd ‣Newton Raphson ‣Pi
❖ Mechanics ‣Call ‣Return ‣Calling variables Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 81
Outline❖ Array Parameters ‣ Elements ‣Whole arrays ‣ 2-d arrays
❖ Libraries ‣ stdio.h ‣math.h ‣ stdlib.h ‣ Your own
❖ Variable Storage classes ‣ Local ‣ static ‣Global ‣Masking
❖ Recursion
![Page 82: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/82.jpg)
Recursive Programs
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Algorithmic Paradigm where you operate on smaller and smaller parts ❖ Often implemented by functions that call themselves ❖ Can be elegant, beautiful, and clean ❖ Sometimes difficult to understand, inefficient, risky ❖ Use with caution
82
![Page 83: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/83.jpg)
Factorial
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Factorial: product of all integers up to n ❖ n!=n*(n-1)*...*2*1
83
#include <stdio.h>
int factorial(int n) { return n==1 ? 1 : n*factorial(n-1); }
int main() { int n; printf("Factorialize: "); scanf("%d", &n); printf("%d!=%d\n", n, factorial(n)); return 0; }
factorial.c
fact(1)=1 fact(2)=2*fact(1)=2*1 fact(3)=3*fact(2)=3*2*fact(1)=3*2*1 fact(4)=4*fact(3)=4*3*fact(2)=4*3*2*fact(1)=4*3*2*1
n n! value1 1 12 2*1 23 3*2*1 64 4*3*2*1 24
function calls itself!
Add examples before this one without a function calling itself, e.g. searching in a sorted array
![Page 84: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/84.jpg)
Power Recursively
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Example: Calculate baseexp
84
#include <stdio.h>
double pow_rec(double base, int n) { return n==0 ? 1. : base*pow_rec(base, n-1); }
int main() { double base; int exp; printf("Base: "); scanf("%lf", &base); printf("Exponent: "); scanf("%d", &exp); printf("%g^%d=%g\n", base, exp, pow_rec(base,exp)); return 0; }
power_rec.c
Calls itself!
pow_rec(5, 0)=1 pow_rec(5, 1)=5*pow_rec(5, 0)=5*1=5 pow_rec(5, 2)=5*pow_rec(5, 1)=5*5*pow_rec(5, 0)=5*5*1=25 pow_rec(5, 3)=5*pow_rec(5, 2)=5*5*pow_rec(5, 1)=5*5* pow_rec(5, 0) = 5*5*5*1=125
![Page 85: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/85.jpg)
Fibonacci Rabbits
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Leonardo Fibonacci, ~1170-1250 ❖ Introduced decimal system to Europe ❖ Asked following question ❖ Pair of newborn rabbits put in a field ❖ After one month, they mate ❖ After another month, give birth to new pair (male & female) ❖ Repeat every month, thereafter ❖ Never die ❖ How many rabbit pairs after one year?
85
![Page 86: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/86.jpg)
Fibonacci Numbers in Nature
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 86
![Page 87: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/87.jpg)
Fibonacci Program (recursive)
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ Represents: Number of rabbits alive after n months ❖ Defined:
87
#include <stdio.h>
int fib(int n) { return n<=1 ? 1 : fib(n-1)+fib(n-2); }
int main() { int n; printf("n: "); scanf("%d", &n); printf("Fibonacci(%d)=%d\n", n, fib(n)); return 0; }
Fibonacci1.cn F(n)0 11 12 23 34 55 86 137 21
‣F(0)=F(1)=1 ‣F(n)=F(n-1)+F(n-2) for n≥2
Inefficient
![Page 88: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/88.jpg)
Efficient Fibonacci (Non Recursive)
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 88
#include <stdio.h>
int main() { int n, i; printf("n: "); scanf("%d", &n); int fib[n+1]; fib[0]=fib[1]=1; for (i=2; i<=n; i++) fib[i]=fib[i-1]+fib[i-2]; printf("Fibonacci(%d)=%d\n", n, fib[n]); }
Fibonacci2.c
#include <stdio.h>
int main() { int n, i, fib[2]={1,1}; printf("n: "); scanf("%d", &n); for (i=2; i<=n; i++) fib[i%2]=fib[(i-1)%2]+fib[(i-2)%2]; printf("Fibonacci(%d)=%d\n", n, fib[n]); }
Fibonacci3.c
int j=0; for (i=2; i<=n; i++, j=1-j) fib[j]=fib[0]+fib[1];
Fibonacci4.c
![Page 89: Lecture 7: Functions - Amazon S3€¦ · Final HW due Friday 12/4 5. Cooking Lesson Lecture 7 ECE15: Introduction to Computer Programming Using the C Language 6 Problem: Need to prepare](https://reader035.vdocument.in/reader035/viewer/2022081607/5ed82e020fa3e705ec0dfbfc/html5/thumbnails/89.jpg)
Mystery Program
Lecture 7 ECE15: Introduction to Computer Programming Using the C Language
❖ What does the following program do?
89
#include <stdio.h>
void getput() { char c=getchar(); if (c == '\n') return; getput(); putchar(c); }
int main() { printf("String: "); getput(); printf("\n"); return 0; } mystery.c
\n
a\n
ab\n
abc\n
a
ba
cba