1 / 77

Fundamental of Programming (C)

Fundamental of Programming (C). Lecture 7 Modular programming. Outline. Introduction to pointer Introduction to function User define function Function prototype (declaration) Function definition Function call and return Formal and Actual Parameters Scope of Identifiers Storage classes

layne
Download Presentation

Fundamental of Programming (C)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Fundamental of Programming (C) Lecture 7 Modular programming

  2. Outline • Introduction to pointer • Introduction to function • User define function • Function prototype (declaration) • Function definition • Function call and return • Formal and Actual Parameters • Scope of Identifiers • Storage classes • Recursion

  3. Pointer Fundamentals • When a variable is defined thecompiler (linker/loader actually) allocates a real memory address for the variable • int x; • When a value is assigned to a variable, the value is actually placed to the memory that was allocated • x=3; x

  4. Pointers • When the value of a variable is used, the contents in the memory are used • y=x; will read the contents in the 4 bytes of memory, and then assign it to variable y • &xcan get the address of x (referencing operator &) • The address can be passed to a function: • scanf("%d", &x); • The address can also be stored in a variable ……

  5. Pointers • To declare a pointer variable type * pointername; • For example: • int x, k; • int * p1; //(or p1 is a int pointer) • char *p2; • p1 = &x; /* Store the address in p1 */

  6. Using Pointers • You can use pointers to access the values of other variables, i.e. the contents of the memory for other variables • To do this, use the * operator (dereferencing operator) • Depending on different context, * has different meanings • For example: int n, m=3, *p; p=&m; n=*p; printf("%d\n", n); // 3 printf("%d\n",*p); // 3

  7. ptr2: 0x1014 0x1010 ptr1: 0x100C 0x1008 i2: 0x1004 i1: 0x1000 Using Pointers int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; 0x1000 0x1000 2 3 3 1

  8. An Example int m=3, n=100, *p, *q; p=&m; printf("m is %d\n",*p); // 3 m++; printf("now m is %d\n",*p); // 4 p=&n; printf("n is %d\n",*p); // 100 *p=500; printf("now n is %d\n", n); // 500 q=&m; *q = *p; printf("now m is %d\n", m); // 500 *p *p

  9. Divide and Conquer Modular Programming • Break a large problem into smaller pieces • Smaller pieces sometimes called functions • Why? • Helps manage complexity • Smaller blocks of code • Easier to read • Encourages re-use of code • Within a particular program or across different programs • Allows independent development of code • Provides a layer of ‘abstraction’

  10. Returnedvalue Function X Functions - Mathematical View

  11. Functions • Every C program starts with main() function • Functions could be • Pre-defined library functions • e.g., printf, sin, tan • Programmer-defined functions • e.g., my_printf, area int main() { … }

  12. Pre-defined library functions • The C standard libraryis a standardized collection of header files and library functions, which are used to implement common operations

  13. Pre-defined library functions • <math.h> • Defines common mathematical functions • e.g. sin, cos. sqrt, pow • <stdio.h> • Defines core input and output functions • e.g. printf, scanf, puts, gets • <time.h> • Defines date and time handling functions • e.g. time, clock • <stdlib.h> • Defines pseudo-random numbers generation functions • e.g. rand, srand

  14. C mathematical functions • double      fmod( double x, double y ); • Computes the remainder of the division operation x/y • double      exp( double arg ); • Computes the e (Euler's number, 2.7182818) raised to the given power arg • double      log( double arg ); • Computes the natural (base e) logarithm of arg • double      log10( double arg ); • Computes the common (base 10) logarithm of arg • double      sqrt( double arg ); • Computes square root of arg • double      pow( double base, double exp); • Computes the value of base raised to the power exp

  15. C mathematical functions • double      sin( double arg ); • Computes sine of arg (representing angle in radians) • double      cos( double arg ); • Computes cosine of arg (representing angle in radians) • double      tan( double arg ); • Computes tangent of arg (representing angle in radians) • overview of math functions in http://en.wikipedia.org/wiki/C_mathematical_functions#stdlib.h

  16. An example #include <stdio.h> #include <math.h> int main(void) { double angle; printf("Input angle in radians: \n"); scanf("%lf", &angle); printf("The sine of the angle is %f\n", sin(angle)); return 0; }

  17. An example #include <stdio.h> #include <math.h> int main(void) { double x1,y1,x2,y2, dist; printf("Enter x1 y1 x2 y2 :"); scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2); dist = sqrt(pow((x2-x1),2) + pow((y2-y1),2)); // printf("Distance is %lf\n", dist); return 0; }

  18. Random numbers generation functions • intrand(); • Returns a uniformly distributed pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included) • RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent. • #define RAND_MAX 32767 /*implementation defined*/ • srand() should be called before any calls to rand() to initialize the random number generator • void srand( unsigned seed ); • Initializes the built-in random number generator used to generate values for rand() with the seed value seed

  19. An Example #include <stdio.h> #include <stdlib.h> int main(void) { unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

  20. An Example #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */ }

  21. Random Numbers in [a b] • Generate a random number [0 .. 7] • x = rand() % 8; • Generate a random number [10 ..17] • x = 10 + rand() % 8; • rand() % (b-a+1) + a;

  22. User- defined OR Programmer-defined function

  23. Functions - Definition Structure • typefunction_name (type arg1, type arg2){ • statements; • } • Function 'header' • Return data type (if any) • Name • Descriptive • Arguments (or parameter list) • Notice: data type and name • Statements • Variable declaration • Operations • Return value (if any) A function that calculates the product of two numbers double product(double x, double y) { double result; result = x * y; return result; }

  24. An Example #include <stdio.h> /* function prototype */ double product(double x, double y); intmain() { double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0; } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; } • Function prototype • Like a variable declaration • Tells compiler that the function will be defined later • Helps detect program errors • Note semicolon!! • Function definition • See previous slide • Note, NO semicolon • Function return • return statement terminates execution of the current function • Control returns to the calling function • if returnexpression; • then value of expression is returned as the value of the function call • Only one value can be returned this way • Function call • main() is the 'calling function' • product() is the 'called function' • Control transferred to the function code • Code in function definition is executed

  25. Function – An Example • Write a function named 'sum' • sums two integers • returns the sum • Steps • Function header • return data type • function name • argument list with data types • Statements in function definition • variable declaration • operations • return value intsum_int(int x, int y) { int result; result = x + y; return result; }

  26. Formal and Actual Parameters • Formal parameter • Variables declared in the formal list of the function header (written in functionprototype & function definition) • Actual parameter • Constants, variables, or expression in a function call that correspond to its formal parameter • The number of actual parameters in a function call must be the same as the number of formal parameters in the function definition • A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on • The type of each actual parameter must be the same as that of the corresponding formal parameter

  27. An Example #include <stdio.h> intcalSum(int,int); /*function prototype*/ int main(void) { ….. ….. sum = calSum(num1,num2); /* function call */ ….. } intcalSum(int val1, int val2) /*function header*/ { …… …… …… } Formal Parameters Actual Parameters Formal Parameters

  28. An Example • If the function requires some arguments to be passed along, then the arguments need to be listed in the bracket ( ) according to the specified order void Calc(int, double, char, int); int main(void) { int a, b; double c; char d; … Calc(a, c, d, b); return (0); } Function Call

  29. Functions that do not return a value • Use the return type of void • voidfunctionName( DataType arg_1,…) • voidfunctionName() • voidfunctionName( void)

  30. 1 2 3 4 Function Call – An Example #include <stdio.h> //function prototype //global variable declaration int main(void) { local variable declaration; statements; fn1( ); fn2( ); return (0); } void fn1(void) { local variable declaration; statements; } void fn2(void) { local variable declaration; statements; return; }

  31. Function Call – An Example • If the function returns a value, then the returned value need to be assigned to a variable so that it can be stored intGetUserInput (void); /* function prototype*/ int main(void) { int input; input = GetUserInput( ); return(0); /* return 0; */ } • However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value • We can also call a function inside another function printf("User input is: %d", GetUserInput( ));

  32. Receive nothing and return nothing #include <stdio.h> void greeting(void); /* function prototype */ int main(void) { greeting( ); greeting( ); return(0); // return 0; } void greeting(void) { printf("Have fun!! \n"); } • Have fun!! • Have fun!! • Press any key to continue

  33. Receive nothing and return nothing #include <stdio.h> intgetInput(void) /* ignore function prototype */ { int number; printf("Enter a number:"); scanf("%d",&number); return number; } int main(void) { int num1, num2, sum; num1 = getInput( ); num2 = getInput( ); sum = num1 + num2; printf("Sum is %d\n",sum); return(0); } • Enter a number: 5 • Enter a number: 4 • Sum is 9 • Press any key to continue

  34. Receive parameter(s) and return nothing #include <stdio.h> intgetInput(void); void displayOutput(int); int main(void) { int num1, num2, sum; num1 = getInput(); num2 = getInput(); sum = num1 + num2; displayOutput(sum); return(0); } intgetInput(void) { int number; printf("Enter a number:"); scanf("%d",&number); return number; } void displayOutput(int sum) { printf("Sum is %d \n",sum); } • Enter a number: 5 • Enter a number: 4 • Sum is 9 • Press any key to continue

  35. Call by value And Call by reference • Call by value • In this method, only the copy of variable’s value (copy of actual parameter’s value) is passed to the function. Any modification to the passed value inside the function will not affect the actual value • In all the examples that we have seen so far, this is the method that has been used • Call by reference • In this method, the reference (memory address) of the variable is passed to the function. Any modification passed done to the variable inside the function will affect the actual value • To do this, we need to have knowledge about pointers and arrays

  36. Call by value – An Example #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) { double result; result = A * B; return result; } • How are the arguments passed into functions? • 'Pass by value' • function arguments are expressions • In the function call: • Expressions are evaluated and copies of their values are put into temporary memory locations • The names of the corresponding parameters in the function definition are made to be the names of the copies • The values of the expressions in the function call are not changed

  37. Call by value – An Example #include <stdio.h> intcalSum(int,int); /*function protototype*/ int main(void) { int sum, num1, num2; printf("Enter two numbers to calculate its sum:\n"); scanf("%d%d",&num1,&num2); sum = calSum(num1,num2); /* function call */ printf("\n %d + %d = %d", num1, num2, sum); return(0); } intcalSum(int val1, int val2) /*function definition*/ { int sum; sum = val1 + val2; val2 = 100; return sum; } • Enter two numbers to calculate its sum: • 4 • 9 • 4 + 9 = 13 • Press any key to continue

  38. Call by reference #include <stdio.h> void CalByVal(a, b) { a = 0; b = 10; } void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) { *a = 0; *b = -5; // a = 0; !!!! } int main(void) { int a = 1, b = 5; printf("Before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("After cal CalByVal: a = %d, b = %d\n", a, b); printf("Before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("After cal CalByRef: a = %d, b = %d\n", a, b); getch(); return 0; /* Exit program. */ }

  39. Call by reference #include <stdio.h> voidprod_sum(double x, double y, double *ptr1, double *ptr2); int main() { double var1 = 3.0, var2 = 5.0; double prod, sum; prod_sum(var1, var2, &prod, &sum); printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum); } /* function definition */ voidprod_sum(double A, double B, double *rslt_prod, double *rslt_sum) { *rslt_prod = A * B; *rslt_sum = A + B; } • Instead ofproduct() • prod_sum() • How can I get the function to give both product and sum? • put * in front of variable name in prototype and function definition • put & in front of variable names in function call

  40. Pointers and Arrays • Recall that the value of an array name is also an address void main() { int x[10]; ReOrder(x); // ReOrder(&x); } void ReOrder(int *x) { inti, j, t; for(i = 0; i < 9; i++) for(j = i + 1; i < 10; ++j) if(x[i] < x[j]) { t = x[i]; x[i] = x[j]; x[j] = t; } }

  41. Organizing Multi-File Programs • A large C program should be divided into multiple files // main.c #include <stdio.h> void Test() { // …} int main() { // … return 0; } // math.c double mathVar; double sin() { double tempSin; // … return tempSin; }

  42. Identifiers and Scope • Identifier • The name of a variable, function, label, etc. • int my_var1; /* a variable */ • pow_table(); /* a function */ • start: /* a label */ • Question: • Does it make a difference where in a program an identifier is declared? YES! --> concept of ‘scope’

  43. Scope of Identifiers • Scope of a declaration of an identifier • The regionof the program that the declaration is active (i.e., can access the variable, function, label, etc.) • Five types of scope: • Program (global scope) • File • Function prototype • Function • Block ("between the { } scope")

  44. Scope of Identifiers - Program Scope #include <stdio.h> int a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) { double result; a = 20; result = x * y; return result; } • Program (global) scope • if declared outside of all functions • "Visible" to all functions from point of declaration • Visible to functions in other source files • Use only when necessaryand then very carefully!! • If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable a = 10 a = 20

  45. An Example // File name: main.c #include <stdio.h> int a = 10; /* function definition */ double product(double x, double y) { double result; // … a = 70; return result; } int main() { a = 80; } // File name: ExternFile.c externinta = 10; /* function definition */ void TestExtern() { // … a = 90; // … }

  46. Scope of Identifiers - File Scope #include <stdio.h> staticint a = 10; double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) { double result; result = x * y; return result; } • Filescope • Keyword static • Makes variable a ‘visible’ only within this source file • Use file scope to avoid naming conflict if multiple source files are used

  47. An Example // File name: main.c #include <stdio.h> staticinta = 10; /* function definition */ double product(double x, double y) { double result; // … a = 70; return result; } int main() { a = 80; } // File name: ExternFile.c externinta = 10; /* function definition */ void TestExtern() { // … a = 90; // … }

  48. Scope of Identifiers - Function Prototype Scope #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); } /* function definition */ double product(double A, double B) { double result; result = A * B; return result; } • Function prototype scope • Identifiers x and y are not visible outside the prototype • Thus, names in the prototype do not have to match names in the function definition • MUST match types, however!

  49. Scope of Identifiers - Function Scope • Function scope • Active from the beginning to the end of a function #include <stdio.h> int main() { inta; // … return 0; } intFunctionScopeTest() { int b; // … return 0; }

  50. Scope of Identifiers - Block Scope #include <stdio.h> double product(double x, double y); int main() { int a = 10; double var1 = 3.0, var2 = 5.0; doubleans; ans = product(var1, var2); // … } /* function definition */ double product(double x, double y) { double result; // a = 60; Error result = x * y; return result; } • Block (local) scope • A block is a series of statements enclosed in braces { } • The identifier scope is active from the point of declaration to the end of the block ( } ) • Nested blocks canboth declare the same variable name and not interfere

More Related