#include<stdio.h> float sum(float x1, float x2) { /* functions take arguments * and return a value */ return x1+x2; } int main() { printf("%f\n", sum(2.0,3.0)); }
#include<stdio.h> int increment(int a) { /* the formal parameter a is a local * variable of the function increment * a is initialized to the value of * the actual parameter in the calling * function */ ++a; return a; } int main() { int c, d; c = 3; d = increment(c); printf("c = %d, d = %d\n",c,d); }
#include<stdio.h> int b; int plus_b(int a) { /* functions have access to * global variables */ return a + b; } int main() { int a; a = 1; b = 2; printf("%d\n", plus_b(a)); }
#include<stdio.h> int a, b; int f(int a) { return a + (b++); } int main() { /* what does this print? */ a = 1; b = 2; printf("%d\n",b + f(a)); printf("%d\n",b + f(a)); }
/* what does this print? */ ... printf("%d\n", f(a) + b); printf("%d\n", f(a) + b); ...
/* what does this change? */ int f(int a) { return (a++) + (b++); } ...
#include<stdio.h> void printNumbersLE(int n) { int i; for (i = n; i > 0; --i) printf("%d\t",i); } int main() { printNumbersLE(10); }
#include<stdio.h> void printNumberLE1() { printf("1\n"); } void printNumberLE2() { printf("2 "); printNumberLE1(); } void printNumberLE3() { printf("3 "); printNumberLE2(); } void printNumberLE4() { printf("4 "); printNumberLE3(); } int main() { printNumberLE4(); }Program 2
#include<stdio.h> void printNumberLE(int i) { if (i > 0) { printf("%d\t",i); printNumberLE(i-1); } } int main() { printNumberLE(10); }Program 3
/* what are these function? * can you find expressions for the number of * calls? */ int f1(int i) { if (i == 0) return 0; else return i + f1(i-1); } int f1(int i) { if (i == 0) return 1; else return i * f1(i-1); } int f2(int i) { /* compare this function to program 7 of the control * flow lecture. What do you think about its efficiency? */ if (i <= 0) return 0; else if (i == 1) return 1 else return f2(i-1) + f2(i-2); }
Next: ARRAYS