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

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

Embed Size (px)

Citation preview

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

Engineering Problem Solving with C

Fundamental Concepts

Chapter 4Modular Programming with

Functions

Page 2: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Modularity

Page 3: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Modularity

• 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

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

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.

Page 5: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Programmer Defined Functions

Page 6: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Categories of Functions

Functions

Library FunctionProgrammer Defined

Functions

Math I/O Others

Functions thatDo not return any

infoFunction that return

One valueFunction that return More than one value

Page 7: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Functions

• Defined to– return a single value to the calling function– perform a task– change the value of the function arguments

(call by reference)

Page 8: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Functions

• Pre-defined– standard libraries

• Programmer defined

Page 9: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Pre-defined FunctionsExample

#include <stdio.h>#include <math.h>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

Page 10: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Function Definition

return_type Function_name (parameter_declaration)

{

declarations;

statements;

}

Also, function should include return statement

return expression ;

Page 11: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Programmer Defined FunctionsTerminology

• Function Prototype– describes how a function is called

• Function Definition

• Function Call

Page 12: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Programmer Defined FunctionsTerminology

• 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

Page 13: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Example:To find max number

#include <stdio.h>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 definition

Page 14: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 15: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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;

}

Page 16: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 17: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Function Definition

• Example:

• Float x,float y: parameters that will be passed to the function.

• All function should include a statement

return (expression);

Page 18: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 19: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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

Page 20: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Function prototype - prototype can be included with

preprocessor directives, or with variable declarations.

#include <stdio.h>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

Page 21: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Calling a function - the value returned by a function can be assigned to a variable, printed, or used in an expression#include <stdio.h>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

Page 22: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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)

Page 23: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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;

}

Page 24: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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)

Page 25: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Example #include <stdio.h>#include <math.h>#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;

elsereturn sin(PI*x)/(PI*x);

}/*-----------------------------------------------------------------------------------*/

Function Prototype

Statements from main that refer to function

Definition of function sinc

Function Header

Page 26: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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;

elsereturn sin(PI*x)/(PI*x);

}

Page 27: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Parameter List:continue

• Thus:

• Variable x formal parameter

• new_x actual parameter

• Lastly, value returned by sinc function, will be printed.

Page 28: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 29: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Parameter List: Continue

• Let say: new_x = 9.0;

9.0 9.0New_x xActual Parameter Formal Parameter

Page 30: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

PracticeConsider 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?

Page 31: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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

Page 32: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 33: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 34: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 35: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 36: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Random Numbers

• Sequences of random numbers can be generated by experiments:

Tossing coin

Rolling die

Selecting numbered balls

Computer can generate sequence random numbers

Page 37: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Random integer sequence

• Use rand() function

• #include<stdlib.h>

• Generate random integer 0-RAND_MAX(typically 32767)

• Rand function has no input arguments and is referenced by rand( ).

Page 38: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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.

Page 39: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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<stdlib.h>

Page 40: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

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

Page 41: Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions

Floating-Point sequence

• Generate floating-point sequence values

• ((double)rand()/RAND_MAX)*(b-a)+a

for interval [a,b]