Modular Programming With Functions

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Chapter Five Functions
Computer Programming w/ Eng. Applications
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
 2007 Pearson Education, Inc. All rights reserved C Functions.
CS 201 Functions Debzani Deb.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modular Programming with Functions.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
CMSC 1041 Functions II Functions that return a value.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
 2007 Pearson Education, Inc. All rights reserved Random Number Generation  rand function – Load – Returns "random" number between
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
1 10/18/04CS150 Introduction to Computer Science 1 Functions Divide and Conquer.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
EPSII 59:006 Spring Call-by-value example #include void increment(int); //prototype for increment function int main(void) { int a=1; printf("Value.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
CHAPTER 8 Scope, Lifetime, and More on Functions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
Functions.
User-Written Functions
Functions and an Introduction to Recursion
Functions, Part 2 of 2 Topics Functions That Return a Value
A Lecture for the c++ Course
CMPT 201 Functions.
Quiz 2.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
User-defined Functions
Modular Programming with Functions
Chapter 6 - Functions Outline 5.1 Introduction
User-defined Functions
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
Functions that return a value
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Modular Programming With Functions 1 1

4.1 Modularity How do you solve a big/complex problem? Divide it into small tasks and solve each task. Then combine these solutions. Divide and Conquer 2 2

4.1 Modularity (cont’d) In C we use functions also referred to as modules to perform specific tasks that we determined in our solution 3 3

Advantages of using modules Modules can be written and tested separately Modules can be reused Large projects can be developed in parallel Reduces length of program, making it more readable Promotes the concept of abstraction A module hides details of a task We just need to know what this module does We don’t need to know how it does it 4 4

4.2 Programmer Defined Functions Every C program starts with main()function Additional functions are called or invoked when the program encounters function names Functions could be Pre-defined library functions (e.g., printf, sin, tan) or Programmer-defined functions (e.g., my_printf, area) Functions Perform a specific task May take arguments May return a single value to the calling function May change the value of the function arguments (call by reference) 5 5

Function definition return_type function_name (parameters) { declarations; statements; } int my_add_func(int a, int b) { int sum; sum = a + b; return sum; } 6 6

Programmer-Defined Functions Terminology Function Prototype describes how a function is called int my_add_func(int, int); Function Call result = my_add_func(5, X); Function implementation int my_add_func(int a, int b) { … } Function parameters Formal parameters Actual parameter Formal parameters must match with actual parameters in order, number and data type. If the type is not the same, type conversion will be applied (coercion of arguments). But this might cause some errors (doubleint) so you need to be careful! 7 7

Example: Pre-defined Functions So far, we used several pre-defined functions! #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; } double sin(double radian); double sin(double radian) { /* details of computing sin */ } 8 8

Example: Programmer-defined Functions #include <stdio.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; } #include <stdio.h> double distance(double, double, double, double); 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 = distance(x1,y1,x2,y2); printf(“Distance is %lf\n”, dist); return 0; } double distance(double x1, y1,x2,y2) return sqrt(pow((x2-x1),2) + pow((y2-y1),2)); 9 9

Exercise (6,8) (-3,5) (4,-1) Suppose you are given the coordinate points of a triangle as shown above, write a program that can find the length of each edge… User enters: (x1, y1), (x2, y2), and (x3, y3) 10

Value Returning Functions Function returns a single value to the calling program Function definition declares the type of value to be returned A return expression; statement is required in the function definition The value returned by a function can be assigned to a variable, printed, or used in an expression 11 11

Void Functions A void function may be called to perform a particular task (clear the screen) modify data perform input and output A void function does not return a value to the calling program A return; statement can be used to exit from function without returning any value 12 12

Exercise: void function #include <stdio.h> void print_i_star(int i); main() { int i; for (i=1; i<=5; i++) { print_i_star( i ); } void print_i_star(int i) int j; for (j=1; j<=i; j++) printf(“*”); printf(“\n”); return; Write a program to generate the following output? * ** *** **** ***** for (i=1; i<=5; i++) { for (j=1; j<=i; j++) printf(“*”); printf(“\n”); } 13 13

Example: value returning function n!=n*(n-1)*…*1, 0! = 1 by definition Function name Return Type int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return(factres); Parameter Declarations Declarations Statements 14 14

Example – use fact() t = 5 s = ? #include <stdio.h> int fact(int n); /* prototype */ int main(void) { int t= 5,s; s = fact(t) + fact(t+1); printf(“result is %d\n”, s); return 0; } t = 5 s = ? Function call 15 15

Example – execution of factorial function (cont’d) s = ? n = 5 factres = 1 int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return(factres); 16 16

Example – execution of factorial function (cont’d) s = ? n = 5 4 3 2 1 factres = 1 5 20 60 120 int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return(factres); 17 17

Example – execution of factorial function (cont’d) #include <stdio.h> int fact(int n); /* prototype */ int main(void) { int t= 5,s; s = 120 + fact(t+1); printf(“result is %d\n”, s); return 0; } t = 5 s = ? Function call 18 18

Example – execution of factorial function (cont’d) s = ? n = 6 factres = 1 int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return(factres); t+1 19 19

Example – execution of factorial function (cont’d) s = ? n = 6 5 4 3 2 1 factres = 1 6 30 120 360 720 int fact(int n) { int factres = 1; while(n>1) factres = factres*n; n--; } return(factres); 20 20

Example – execution of factorial function (cont’d) #include <stdio.h> int fact(int n); /* prototype */ int main(void) { int t= 5,s; s = 120 + 720; printf(“result is %d\n”, s); return 0; } t = 5 s = 840 result is 840 21 21

Example – reuse of factorial function Write a statement to compute Enter X, Z, K, D … y=(fact(X)+fact(Z)*5)/(fact(K)-fact(D)); 22 22

Example – reuse of factorial function in another function Write a select function that takes n and k and computes “n choose k” where int select(int n, int k) { return fact(n)/(fact(n-k)*fact(k)); } 23 23

Function Examples 24 24

Exercise Write a function to compute maximum and minimum of two numbers int max(int a, int b) { if (a > b) return a; else return b; } int min(int a, int b) { if (a < b) return a; else return b; } 25 25

Exercise Are following calls to max function valid? What will be the result? int max(int a, int b); int min(int a, int b); int main() { int x = 2, y = 3, z = 7, temp; temp = max(x,y); temp = max(4,6); temp = max(4,4+3*2); temp = max(x,max(y,z)); } 26 26

Example for void function void print_date(int mo, int day, int year) { /*output formatted date */ printf(“%i/%i/%i\n”, mo, day, year ); return; } 27 27

Exercise Write a function that takes score as parameter and computes and returns letter grade based on the scale below. 80-100 A 60-79 B 40-59 C 0-39 D 28 28

Solution char get_letter_grade(int score) { char grade; if ((score >= 80) && (score <=100)) grade = 'A'; else if ((score >= 60) && (score <= 79)) grade = 'B'; else if ((score >= 40) && (score <= 59)) grade = 'C'; else if ((score >= 0) && (score <= 39)) grade = 'D'; return grade; } 29 29

Exercise Write a function to compute logba double log_any_base(double a, double b) { return log(a)/log(b); } 30 30

Exercise: Trace functions What is the output of the following program #include <stdio.h> int function1(int x) { x = 2; printf("Out1 = %d\n",x); return(x+1); } int main() int x = 4, y; y = function1(x); printf("Out2 = %d\n",x); printf("Out3 = %d\n",y); return 0; Output Out1 = 2 Out2 = 4 Out3 = 3 31 31

Exercise What is the output of the following program #include <stdio.h> void function2() { printf("In function 2\n"); } void function1() function2(); printf("In function 1\n"); void function3() { printf("In function 3\n"); function2(); } int main() function1(); function3(); return 0; Output In function 2 In function 1 In function 3 32 32

Parameter Passing Call by value Call by reference formal parameter receives the value of the actual parameter function can NOT change the value of the actual parameter (arrays are an exception) Call by reference actual parameters are pointers (ch 5 and 6) function can change the value of the actual parameter 33 33

Scope of a function or variable Scope refers to the portion of the program in which It is valid to reference the function or variable The function or variable is visible or accessible #include <stdio.h> int fact(int n); /* prototype */ int main(void) { int t= 5,s; s = fact(t) + fact(t+1); printf(“result is %d\n”, s); return 0; } int fact(int n) int factres = 1; while(n>1) { factres = factres*n; n--; return(factres); t = 5 s = ? n = 5 factres = 1 34 34

Scope of a function or variable Same variable name can be used in different functions #include <stdio.h> int fact(int n); /* prototype */ int main(void) { int t= 5,s; s = fact(t) + fact(t+1); printf(“result is %d\n”, s); return 0; } int fact(int t) int s = 1; while(t>1) { s = s*t; t--; return(s); t = 5 s = ? s = 1 35 35

Scope Local scope Global scope a local variable is defined within a function or a block and can be accessed only within the function or block that defines it Global scope a global variable is defined outside the main function and can be accessed by any function within the program file. 36 36

Global vs Local Variable #include <stdio.h> int z = 2; void function1() { int a = 4; printf("Z = %d\n",z); z = z+a; } int main() { int a = 3; z = z + a; function1(); return 0; z=2 5 9 12 a=4 a=3 Output Z = 5 Z = 9 37 37

Storage Class - 4 types Storage class refers to the lifetime of a variable automatic - key word auto - default for local variables Memory set aside for local variables is not reserved when the block in which the local variable was defined is exited. external - key word extern - used for global variables Memory is reserved for a global variable throughout the execution life of the program. static - key word static Requests that memory for a local variable be reserved throughout the execution life of the program. The static storage class does not affect the scope of the variable. register - key word register Requests that a variable should be placed in a high speed memory register. 38 38

Initial / default value Storage Specifier Storage place Initial / default value Scope Life auto CPU Memory Garbage value local Within the function only. extern CPU memory Zero Global Till the end of the main program. Variable definition might be anywhere in the C program static Retains the value of the variable between different function calls. register Register memory Within the function

void fun () { int a=6; a = a + 1; printf ("\nInside fun a = %d ", a); } void fun1 () { static int a; a = a + 1; printf ("\nInside fun1 a = %d ", a); } void fun (void); void fun1 (void); void fun2 (void); int count1=20; int main () { int count=5; fun (); fun1 (); fun2 (); printf ("\nIn main count = %d count1 = %d\n\n",count, count1); return 0; } void fun2 () { int count=10; count = count + 1; count1 = count1 + 1; printf ("\nInside fun2 count = %d count1=%d ", count, count1); }

4.4 Random Numbers What is a random number? Tossing a coin (0, 1) Rolling a die (1, 2,…6) Min, Max, Avg, possible outcomes are equally likely or not, Engineering problems require use of random numbers How can you compute the area of an irregular shape? 41 41

Uniform Random numbers All outcomes are equally likely For example fair die, where each outcome has the same probability of 1/6, So we can generate uniform random numbers between 1 and 6 by rolling a die. What if we need random numbers in another range? For example, 1 and 100? 42 42

Uniform Random numbers (cont’d) In Standard C library, we have a function rand() to generate random numbers between 0 and RAND_MAX RAND_MAX is a system dependent constant (e.g., 32,767) defined in stdlib.h What will be the output of the following printf(“%d %d %d\n”,rand(), rand(), rand()); What will be the output, if we re-run the same program? 43 43

Pseudo-random Numbers Computers generate random numbers using a seed number and an algorithm. So, if you give the same seed, you will always get the same sequence of pseudo-random numbers In Standard C library, we have a function srand(int seed) to give a new seed number 44 44

Example: generate 10 RNs #include <stdio.h> #include <stdlib.h> int main(void) { /* Declare variables. */ unsigned int seed; 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"); /* Exit program. */ return 0; } 45 45

RNs in a specified range [a b] Generate a RN between 0 and 7 x = rand() % 8; Generate a RN between 10 and 17 x = 10 + rand() % 8; int rand_int(int a,int b) { return rand()%(b-a+1) + a; } 46 46

Floating-Point RNs in a specified range [a b] x = rand() / RAND_MAX will give a random number between 0.0 and 1.0 x = rand() / RAND_MAX *(b-a) will give a RN between 0.0 and b-a The value is then shifted into range [a b] by adding a double rand_float(double a,double b) { return ((double)rand()/RAND_MAX)*(b-a)+a; } 47 47

Example: HiLo Game /* Write a program that allows a user to play HiLo game. User wins if he/she can guess the number between 1-100 within at most 6 iterations */ #include <stdio.h> #include <stdlib.h> int rand_int(int a,int b); /* prototype */ void playHiLo( int s); int main(void) { unsigned int seed; /* Declare variables */ int secret; printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); while(1){ secret = rand_int(1,100); playHiLo(secret); } return 0; 48 48

int rand_int(int a,int b) { return rand()%(b-a+1) + a; } void playHiLo(int s) int i, guess; for(i=1; i <=6; i++){ printf("Enter your guess : "); scanf("%d", &guess); if (guess > s) printf("It is Higher than secret\n"); else if (guess < s) printf("It is Lower than secret\n"); else { printf("Cong! you won\n"); return; printf("Sorry! Try again\n"); 49 49

Exercise: Another “guess the number game” Computer selects a random number s between [1000 9999] User tries to guess it by entering g Computer tells how many digits are in place, out of place, not in secret number For example, if s is 6234 User enters g as 7436, then computer says 1 digit is in place 2 digits are out of place 1 digit is not in secret number User keeps trying until he finds the secret number 50 50

Random Number Summary #include <stdlib.h> srand(seed); rn = rand(); /* [0 RAND_MAX] (e.g., 32,767) */ int rand_int(int a,int b) { return rand()%(b-a+1) + a; } double rand_float(double a,double b) return ((double)rand()/RAND_MAX)*(b-a)+a; 51 51

4.5 Macros #define macro_name(parameters) macro_text macro_text replaces macro_name in the program Examples #define area_tri(base,height) (0.5*(base)*(height)) #define PI 3.14 z=x * tri(3, 5) + y;  z=x * (0.5*(3)*(5)) + y; k=2*PI*r;  k=2*3.14*r; 52 52

4.6 Recursive Functions A function that invokes itself is a recursive function. int fact(int k) { if (k == 0) return 1; else return k*fact(k-1); } k!=k*(k-1)! 53 53

#include <stdio.h> int fact(int k) { if (k == 0) return 1; else return k*fact(k-1); } int main() int n; int nf; printf("Enter n\n"); scanf("%d",&n); nf = fact(n); printf("Factorial = %d\n", nf); system("pause"); return(0); 54 54

Fibonacci Numbers Sequence {f0,f1,f2,…}. First two values (f0,f1) are 1, each succeeding number is the sum of previous two numbers. 1 1 2 3 5 8 13 21 34 F(0)=1, F(1) = 1 F(i) = F(i-1)+F(i-2) 55 55

Fibonacci Numbers int fibonacci(int k) { int term; term = 1; if (k>1) term = fibonacci(k-1)+fibonacci(k-2); return term; } 56 56

#include <stdio.h> int fibonacci(int k) { int term = 1; if (k>1) term = fibonacci(k-1)+fibonacci(k-2); return(term); } int main() int n; int nfib; printf("Enter n\n"); scanf("%d",&n); nfib = fibonacci(n); printf("Fibonacci = %d\n",nfib); system("pause"); return(0); /* Iterative Version of Fibonacci Function */ int fibonacci(int k) { int a,b,c,i; if (k<=1) return 1; else a = 1; b = 1; i = 2; while (i<=k) c = a + b; a = b; b = c; i = i + 1; } return(c); 57 57

Extra examples 58 58

Exercise Given radius and height of a cylinder. Write a function to compute the surface area. A = 2*pi*r*(r*h) #define PI 3.14 double area(double radius, double height) { return 2*PI*radius*(radius+height); } 59 59

Exercise Given radius and height of a cylinder. Write a function to compute the volume. V = pi*r2*h #define PI 3.14 double volume(double radius, double height) { return(PI*radius*radius*height); } 60 60

Exercise Given radius and height of a cylinder. Write a function to compute the volume. V = pi*r2*h #define PI 3.14 double volume(double radius, double height) { return(PI*radius*radius*height); } 61 61

Exercise Write a function to compute the median of 3 numbers x, y and z. Possible order of numbers x<y<z -> median y x<z<y -> median z y<x<z -> median x y<z<x -> median z z<x<y -> median x z<y<x -> median y 62 62

Solution int median(int x, int y, int z) { if (((x<y) && (y<z)) || ((z<y) && (y<x))) return y; else if (((y<x) && (x<z)) || ((z<x) && (x<y))) return x; else return z; } 63 63

Exercise Assume you have maximum and minimum functions implemented. Use these to find median of 3 numbers a < b < c -> median is b Consider 3 pairs (a,b),(b,c),(a,c) min(a,b) = a min(b,c) = b Max(a,b,a) = b min(a,c) = a 64 64

Exercise Assume you have maximum and minimum functions implemented. Use these to find median of 3 numbers a < b < c -> median is b Consider 3 pairs (a,b),(b,c),(a,c) min(a,b) = a min(b,c) = b Max(a,b,a) = b min(a,c) = a 65 65

Solution int median(int x, int y, int z) { return(max(min(x,y),min(x,z),min(y,z))); } 66 66