Transcript Title

Engineering Problem Solving
with C
Fundamental Concepts
Chapter 4
Modular Programming with
Functions
Modularity
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
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.
Programmer Defined Functions
Categories of Functions
Functions
Programmer Defined
Functions
Library Function
Math
I/O
Others
Functions that
Do not return any
info
Function that return
One value
Function that return
More than one value
Functions
• Defined to
– return a single value to the calling function
– perform a task
– change the value of the function arguments
(call by reference)
Functions
• Pre-defined
– standard libraries
• Programmer defined
Pre-defined Functions
Example
#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
Function Definition
return_type Function_name (parameter_declaration)
{
declarations;
statements;
}
Also, function should include return statement
return expression ;
Programmer Defined Functions
Terminology
• Function Prototype
– describes how a function is called
• Function Definition
• Function Call
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
Example:To find max number
Function Prototype
#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);
F
u
n
c
t
i
o
n
d
e
f
i
n
i
t
i
o
n
maxnum = findMax(firstnum,secnum);
printf("maximum number is :%f\n",maxnum);
The Function is called here
/* exit program*/
return 0;
}
/*-------------------------------------------*/
/*---------- function max--------------*/
float findMax(float x,float y)
{
float maxnum;
if(x>=y)
maxnum=x;
else
maxnum=y;
Variable declaration
Find the Max number
return(maxnum);
}
Function Header
Return the value
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.
Function Definition
•
Function consists of definition statement followed by declaration statements
/*-------------------------------------------*/
/*---------- function max--------------*/
General Form;
float findMax(float x,float y)
{
float maxnum;
if(x>=y)
maxnum=x;
else
maxnum=y;
return(maxnum);
}
return_type function_name(parameter declarations)
{
Declarations;
Statements;
}
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.
Function Definition
• Example:
• Float x,float y: parameters that will be
passed to the function.
• All function should include a statement
return (expression);
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.
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
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;
Function Prototype
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;
Function is called here
}
Note: In this example the function fact is called in the printf statement.
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)
{
Function is called here
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);
}
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)
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;
}
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)
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);
*/
Function Prototype
/*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));
}
Statements from main that
refer to function
/* Exit program*/
return 0;
}
/*-----------------------------------------------------------------------------------*/
/*This function evaluates the sinc function
*/
double sinc(double x)
Function
{
if (fabs(x) < 0.0001)
return 1.0;
else
return sin(PI*x)/(PI*x);
Header
}
/*-----------------------------------------------------------------------------------*/
Definition of function sinc
Parameter List
• When the reference to the sinc function
in the printf statement is executed,
printf("%f %f\n", new_x, sinc(new_x));
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.
double sinc(double x)
{
if (fabs(x) < 0.0001)
return 1.0;
else
return sin(PI*x)/(PI*x);
}
Parameter List:continue
•
•
•
•
Thus:
Variable x  formal parameter
new_x  actual parameter
Lastly, value returned by sinc function,
will be printed.
Parameter List: continue
• From example, the function reference is callby-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.
Parameter List: Continue
• Let say: new_x = 9.0;
Actual Parameter
New_x
9.0
Formal Parameter
x
9.0
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?
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
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.
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.
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.
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.
Random Numbers
• Sequences of random numbers can be
generated by experiments:
Tossing coin
Rolling die
Selecting numbered balls
Computer can generate sequence
random numbers
Random integer sequence
• Use rand() function
• #include<stdlib.h>
• Generate random integer 0RAND_MAX(typically 32767)
• Rand function has no input arguments
and is referenced by rand( ).
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.
Random –number seed
• In order to generate a new sequence of
random values each time that it is
executed, need to give a new randomnumber seed to the random number
generator.
• Use srand() function
• Input argument is unsigned integer
• #include<stdlib.h>
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
Floating-Point sequence
• Generate floating-point sequence
values
• ((double)rand()/RAND_MAX)*(b-a)+a
for interval [a,b]