Presentation is loading. Please wait.

Presentation is loading. Please wait.

Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.

Similar presentations


Presentation on theme: "Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions."— Presentation transcript:

1 Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

2 Modularity

3 Execution of a program begins in the main function The main function can call other functions –Functions defined in the same file –Function defined in other files or libraries Functions are also referred to as modules A module is a set of statements that performs a task or computes a value

4 Advantages of using modules Modules can be written and tested separately Large projects can be developed in parallel Reduces length of program, making it more readable Promotes the concept of abstraction, can reduce software development time while increase its quality.

5 Programmer Defined Functions

6 Categories of Functions Functions Library Function MathI/OOthers Programmer Defined Functions Functions that Do not return any info Function that return One value Function that return More than one value

7 Functions Defined to –return a single value to the calling function –perform a task –change the value of the function arguments (call by reference)

8 Functions Pre-defined –standard libraries Programmer defined

9 Pre-defined Functions Example #include int main(void) { double angle; printf( “input angle in radians: \n“); scanf(“%lf”, &angle); printf( “\nthe sine of the angle is %f\n“,sin(angle) ); return 0; }//end main

10 Function Definition return_type Function_name (parameter_declaration) { declarations; statements; } Also, function should include return statement return expression ;

11 Programmer Defined Functions Terminology Function Prototype –describes how a function is called Function Definition Function Call

12 Programmer Defined Functions Terminology Actual parameter –used in the function call Formal Parameters –used in function definition Formal parameters must match with actual parameters in order, number and data type

13 Example:To find max number #include float findMax(float x, float y); int main() { float firstnum,secnum,maxnum; printf("enter your first number:\n"); scanf("%f",&firstnum); printf("enter your second number:\n"); scanf("%f",&secnum); maxnum = findMax(firstnum,secnum); printf("maximum number is :%f\n",maxnum); /* exit program*/ return 0; } /*-------------------------------------------*/ /*---------- function max--------------*/ float findMax(float x,float y) { float maxnum; if(x>=y) maxnum=x; else maxnum=y; return(maxnum); } Function Prototype The Function is called here Function Header Variable declaration Find the Max number Return the value Function definitionFunction definition

14 Function Prototype From example ; float findMax(float x,float y); It informs the compiler that the main function will reference a function named findMax. findMax function expect float parameters and that the findMax function returns a float value.

15 Function Definition Function consists of definition statement followed by declaration statements /*-------------------------------------------*/ /*---------- function max--------------*/ float findMax(float x,float y) { float maxnum; if(x>=y) maxnum=x; else maxnum=y; return(maxnum); } General Form; return_type function_name(parameter declarations) { Declarations; Statements; }

16 Function Definition Parameter declaration: represents the info passed to the function. If there are no input parameters (arguments), then the parameter declaration should be void. Additional variables used by a function are defined in the braces. The declaration and statements within function are enclosed in braces.

17 Function Definition Example: Float x,float y: parameters that will be passed to the function. All function should include a statement return (expression);

18 Function Definition The expression specifies value to be returned to the statement that referenced the function. The expression type should match the return type indicated in the function definition to avoid errors.

19 Example - factorial function /*function definition n! = n*(n-1)*(n-2)*…*1, 0! = 1 by definition - fact returns n! assumes n is non-negative integer */ int fact(int n) { int fact = 1; while(n>1) { fact = fact*n; n--; }//end while block return(fact); }//end fact Function Definition

20 Function prototype - prototype can be included with preprocessor directives, or with variable declarations. #include int main(void) { /* Declare variables and function prototypes. */ int n; int fact(int n); printf(“Enter a positive integer\n”); scanf("%i”, &n); if(n>=0) printf(“%i! is %i\n“, n, fact(n) ); return 0; } Note: In this example the function fact is called in the printf statement. Function is called here Function Prototype

21 Calling a function - the value returned by a function can be assigned to a variable, printed, or used in an expression #include int fact(int n); int main() { /*Declare variables and function prototypes */ int n,factorial; printf("enter positive integer\n"); scanf("%d",&n); if(n>=0) { factorial = fact(n); printf("%i! is %i\n", n, factorial); } return 0; } /*--------------------------------------------*/ /* function Factorial */ int fact(int n) { int fact = 1; while (n>1) { fact=fact*n; n--; } return (fact); } Function is called here

22 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 if a return; statement is used (no return value)

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

24 Parameter Passing Call by value –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 (pointers will be discussed in chapter 6)

25 Example #include #define PI 3.141593 int main(void) { /*declare variables*/ int k; double a, b, x_incr, new_x; double sinc(double x); /*get interval endpoints from the user*/ printf("enter endpoints a and b (a<b): \n"); scanf("%lf %lf", &a,&b); x_incr = (b-a)/20; /* compute and print table of sinc(x) */ printf("x and sinc(x)\n"); for(k=0;k<=20;k++) { new_x = a + k * x_incr; printf("%f %f\n", new_x, sinc(new_x)); } /* Exit program*/ return 0; } /*-----------------------------------------------------------------------------------*/ /*This function evaluates the sinc function */ double sinc(double x) { if (fabs(x) < 0.0001) return 1.0; else return sin(PI*x)/(PI*x); } /*-----------------------------------------------------------------------------------*/ Function Prototype Statements from main that refer to function Definition of function sinc Function Header

26 Parameter List When the reference to the sinc function in the printf statement is executed, The value in the actual parameter is copied to the formal parameter, and the steps in the sinc function are executed using the new value in x. printf("%f %f\n", new_x, sinc(new_x)); double sinc(double x) { if (fabs(x) < 0.0001) return 1.0; else return sin(PI*x)/(PI*x); }

27 Parameter List:continue Thus: Variable x  formal parameter new_x  actual parameter Lastly, value returned by sinc function, will be printed.

28 Parameter List: continue From example, the function reference is call- by-value reference. When a function is made, the value of the actual parameter is passed to the function and is used as the value of the corresponding formal parameter. Note: the value in the formal parameter is not moved back to the actual parameter when the function is completed.

29 Parameter List: Continue Let say: new_x = 9.0; 9.0 New_xx Actual Parameter Formal Parameter

30 Practice Consider the following function: int positive(double a, double b, double c) { int count; count=0; if(a>=0) count++; if(b>=0) count++; if(c>=0) count++; return count; } Assume that the function is referenced with the following statements: x=25; total =positive(x,sqrt(x),x-30); 1.Show the memory snapshot of the actual parameters and the formal parameters. 2.What is the new value of total?

31 Storage Class and Scope Scope refers to the portion of the program in which it is valid to reference a function or a variable or Scope refers to the region in which a declaration is active. Storage class refers to the lifetime of a variable

32 Scope Local 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. Thus, local scope/variables includes formal parameters and any other variables declared in the function. A local variable can be accessed ONLY in the function that defines it. A local variable has a value when its function is being executed, but its value is not retained when the function is completed.

33 Scope Global scope - a global variable is defined outside the main function The definition of a global variable is outside of all functions so, it can be accessed by any function within the program.

34 Storage Class - 4 types 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.

35 Random Numbers A sequence of random numbers is not defined by an equation; instead it has certain characteristics that define it. Characteristics include minimum and maximum values also, average. Also, indicate whether the possible values are equally likely to occur or whether some values are more likely to occur than others.

36 Random Numbers Sequences of random numbers can be generated by experiments:  Tossing coin  Rolling die  Selecting numbered balls  Computer can generate sequence random numbers

37 Random integer sequence Use rand() function #include Generate random integer 0- RAND_MAX(typically 32767) Rand function has no input arguments and is referenced by rand( ).

38 Random integer sequence To generate and print a sequence of two random numbers, we could use statements: Printf(“random numbers: %i %i \n”,rand(),rand()); Each time executed, the same two values are printed  pseudo-random.

39 Random –number seed In order to generate a new sequence of random values each time that it is executed, need to give a new random- number seed to the random number generator. Use srand() function Input argument is unsigned integer #include

40 Random number-specific range Example 1, number between 0and7 x=rand()%8; Example 2, number between -25 and 25 y=rand()%51-25; Formula, between a and b (b-a+1)+a

41 Floating-Point sequence Generate floating-point sequence values ((double)rand()/RAND_MAX)*(b-a)+a for interval [a,b]


Download ppt "Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions."

Similar presentations


Ads by Google