0% found this document useful (0 votes)
3 views35 pages

2.functions Updated

The document discusses the importance of modular programming in C, emphasizing the use of functions to break down large programs into manageable modules. It outlines the benefits of using functions, such as simpler code, code reuse, and easier maintenance, and provides examples of predefined functions in the C Standard Library. Additionally, it covers function definitions, prototypes, and the significance of data type promotion in function arguments.

Uploaded by

lanaalkhtib8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

2.functions Updated

The document discusses the importance of modular programming in C, emphasizing the use of functions to break down large programs into manageable modules. It outlines the benefits of using functions, such as simpler code, code reuse, and easier maintenance, and provides examples of predefined functions in the C Standard Library. Additionally, it covers function definitions, prototypes, and the significance of data type promotion in function arguments.

Uploaded by

lanaalkhtib8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

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 manageable than the original program.
Modules are written as functions in C.
Introduction

 A module is a group of statements that exists for the purpose


of performing a specific task within a program.
 Modules in C called Functions
 Most programs are large enough to be broken down into
several subtasks.
 Divide and conquer: It’s easier to tackle smaller tasks
individually.

1-2
Introduction

Benefits of using functions (modules)


 Simpler code
 Small modules easier to read than one large one
 Code reuse
 Can call modules many times
 Better testing
 Test separate and isolate then fix errors
 Faster development
 Reuse common tasks
 Easier facilitation of teamwork
 Share the workload
 Easier Maintenance
 Smaller, simpler code is easier to maintain

1-3
Hierarchical boss function/worker function relationship
OBJECTIVES
 To construct programs modularly from small pieces called
functions.
 The common math functions available in the C Standard
Library.
 How to create new functions.
 The mechanisms used to pass information between functions.
 How to write and use recursive functions, i.e., functions that
call themselves.
Predefined Functions
 In C, a function is similar to that of a function in algebra
 It has a name

 It does some computation

 Some of the predefined mathematical functions are:


sqrt(x)
pow(x, y)
floor(x)

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 8


Predefined Functions (cont'd.)
 Predefined functions are organized into separate libraries
 I/O functions are in stdio.h header

 Math functions are in math.h header

 To use predefined functions, you must include the header file


using an include statement

C++ Programming: From Problem Analysis to Program Design, Seventh Edition 9


Predefined Functions (cont'd.)
 Format for calling functions
 FunctionName( argument );
 If multiple arguments, use comma-separated list

 Ex:

 Calls function sqrt, which returns the square root of its argument
Predefined Functions (cont'd.)
 Function sqrt as a “Black Box”
Predefined Functions (cont'd.)
 Ex: If w is 9.0, the assignment statement
z = 5.7 + sqrt(w);
is evaluated as follows:
1. w is 9.0, so function sqrt computes the
square root of 9.0, or 3.0.
2. The values 5.7 and 3.0 are added together.
3. The sum, 8.7, is stored in z.

 Ex: printf( "%f", sqrt( 900.0 ) );


 Pass the result of function sqrt to the printf

function
 Arguments may be constants, variables, or expressions
Commonly used math library functions
Function Description Example
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0

exp( x ) exponential function ex exp( 1.0 ) is 2.718282


exp( 2.0 ) is 7.389056
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
(base e)
log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
fabs( x ) absolute value of x fabs( 5.0 ) is 5.0
fabs( 0.0 ) is 0.0
fabs( -5.0 ) is 5.0
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
integer not less than x
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
integer not greater than x
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128.0
pow( 9, .5 ) is 3.0
fmod( x, y ) remainder of x/y as a fmod( 13.657, 2.333 ) is
1.992
floating point number
sin( x ) trigonometric sine of x sin( 0.0 ) is 0.0
(x in radians)
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0.0
(x in radians)
Some of the standard library header
Standard library header Explanation
<assert.h> Contains macros and information for adding diagnostics that aid program
debugging.
<ctype.h> Contains function prototypes for functions that test characters for certain
properties, and function prototypes for functions that can be used to
convert lowercase letters to uppercase letters and vice versa.
<errno.h> Defines macros that are useful for reporting error conditions.
<float.h> Contains the floating point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<locale.h> Contains function prototypes and other information that enables a pro-
gram to be modified for the current locale on which it is running. The
notion of locale enables the computer system to handle different conven-
tions for expressing data like dates, times, dollar amounts and large
numbers throughout the world.
<math.h> Contains function prototypes for math library functions.
<setjmp.h> Contains function prototypes for functions that allow bypassing of the
usual function call and return sequence.
<signal.h> Contains function prototypes and macros to handle various conditions that
may arise during program execution.
<stdarg.h> Defines macros for dealing with a list of arguments to a function whose
number and types are unknown.
<stddef.h> Contains common definitions of types used by C for performing certain
calculations.
<stdio.h> Contains function prototypes for the standard input/output library func-
tions, and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text and text
to numbers, memory allocation, random numbers, and other utility
functions.
<string.h> Contains function prototypes for string processing functions.
<time.h> Contains function prototypes and types for manipulating the time and
date.
Random Number Generation
 rand function
 Load <stdlib.h>

 Returns "random" number between 0 and RAND_MAX (at least 32767)

i = rand();
 Pseudorandom
 Preset sequence of "random" numbers

 Same sequence for every function call

 Scaling
 To get a random number between 1 and n

1 + ( rand() % n ) // 0  n-1
 rand() % n returns a number between 0 and n-1
 Add 1 to make random number between 1 and n
1 + ( rand() % 6)
 number between 1 and 6
 General rule: low + rand()%(high-low+1)
 Random from 5 to 100 is: 5 + rand()%(100-5+1)
OBJECTIVES
 To construct programs modularly from small pieces called
functions.
 The common math functions available in the C Standard
Library.
 How to create new functions.
 The mechanisms used to pass information between functions.
 How to write and use recursive functions, i.e., functions that
call themselves.
Tips
• In programs containing many functions, main is
often implemented as a group of calls to functions
that perform the bulk of the program’s work.

• Each function should be limited to performing a


single, well-defined task, and the function name
should effectively express that task.
Function Definitions float computeAvg(int a, int b, int c)
{
float sum;
 Function definition format float average;
return-value-type function-name( parameter-list ) sum=a+b+c;
{ average = sum/3;
declarations and statements average;
} }
 Function-name: any valid identifier
 Return-value-type: data type of the result (default int)
 void – indicates that the function returns nothing
 Parameter-list: comma separated list, declares parameters
 A type must be listed explicitly for each parameter unless, the parameter is
of type int
 Definitions and statements: function body (block)
 Variables can be defined inside blocks (can be nested)
 Functions can not be defined inside other functions
 Returning control
 If nothing returned
 return;
 or, until reaches right brace
 If something returned return
 return expression;
Functions
 Functions
 All variables defined inside functions are local variables

 Known only in function defined

 Never been seen outside the function

 Removed from the memory after the function completed its task

(end of the function)

 Parameters
 Communicate information between functions

 Are considered as Local variables


1 /* Fig. 5.3: fig05_03.c
2 Creating and using a programmer-defined function */
3 #include <stdio.h>
4
5 int square( int y ); /* function prototype */
 fig05_03.c
6
7 /* function main begins program execution */
8 int main( void ) Function prototype indicates function will
9 { be defined later in the program
10 int x; /* counter */
11
12 /* loop 10 times and calculate and output square of x each time */
13 for ( x = 1; x <= 10; x++ ) {
14 printf( "%d ", square( x ) ); /* function call */
15 } /* end for */
16
Call to square function
17 printf( "\n" );
18
19 return 0; /* indicates successful termination */
20
21 } /* end main */
22
23 /* square function definition returns square of parameter */
24 int square( int y ) /* y is a copy of argument to function */
Function definition
25 {
26 return y * y; /* returns square of y as an int */
27
28 } /* end function square */

1 4 9 16 25 36 49 64 81 100
Function Prototypes
 Function prototype
 Function name

 Parameters – what the function takes in

 Return type – data type function returns (default int)

 Used to validate functions

 Prototype only needed if function definition comes after use

in program
 The function with the prototype

int maximum( int x, int y, int z );


 Takes in 3 ints
 Returns an int
 Promotion rules and conversions
 Converting to lower types can lead to errors
1 /* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3 #include <stdio.h>
4
5 int maximum( int x, int y, int z ); /* function prototype */
6
7 /* function main begins program execution */ Function prototype
8 int main( void )
9 {
10 int number1; /* first integer */
 fig05_04.c
11
12
int number2; /* second integer */
int number3; /* third integer */ (1 of 2 )
13
14 printf( "Enter three integers: " );
15 scanf( "%d%d%d", &number1, &number2, &number3 ); Function call
16
17 /* number1, number2 and number3 are arguments
18 to the maximum function call */
19 printf( "Maximum is: %d\n", maximum( number1, number2, number3 ) );
20
21 return 0; /* indicates successful termination */
22
23 } /* end main */
24
25 /* Function maximum definition */
26 /* x, y and z are parameters */
27 int maximum( int x, int y, int z ) Function definition
28 {
29 int max = x; /* assume x is largest */
30
31 if ( y > max ) { /* if y is larger than max, assign y to max */  fig05_04.c
32 max = y;
33 } /* end if */ (2 of 2 )
34
35 if ( z > max ) { /* if z is larger than max, assign z to max */
36 max = z;
37 } /* end if */
38
39 return max; /* max is largest value */
40
41 } /* end function maximum */

Enter three integers: 22 85 17


Maximum is: 85

Enter three integers: 85 22 17


Maximum is: 85

Enter three integers: 22 17 85


Maximum is: 85
Notice!
• A function prototype tells the compiler:
 the type of data return by the function
 the number of parameters the function expects to receive
 the types of the parameters, and
 the order in which these parameters are expected
 Prototype only needed if function definition comes after use in program
• By default, the compiler assumes the function returns an int, and nothing is
assumed about the arguments.
• Omitting the return-value-type in a function definition is a syntax error if
the function prototype specifies a return type other than int.
• Forgetting to return a value from a function that is supposed to return a
value can lead to unexpected errors. The C standard states that the result of
this omission is undefined.
• Returning a value from a function with a void return type is a syntax
error.
• The function prototype, function header and function calls should all agree
in the number, type, and order of arguments and parameters, and in the
type of return value.
Promotion for Data Types in C
 As we perform some calculations on some variables with
different data types:
 the operands are converted to the more general type int x=10;
float y=3;
(i.e. they are converted to the data type of the operand that float result=x/y; // 3.33
can contain the larger maximum value). (please see the
next slide about promotion hierarchy)
 Sometimes we may concern with some side-effects (loss
int x=10;
of precision or unexpected value) in the result. int y=3;
Regardless the data-type of the result! float result=x/y; // 3.0
 Solution:

 Casting (Type Casting): is to force a variable or

expression to behave like a specific data type. The cast


operator is performed by placing the (desired data type)
in parenthesis, just prior to the target variable or
expression. int x=10;
int y=3;
 Another solution is to multiply at least x or y by 1.0
float result=(float)x/y; // 3.33
Promotion Hierarchy for Data Types

printf conversion scanf conversion


Data type
specification specification
High
Long double %Lf %Lf
double %f %lf
float %f %f
Unsigned long int %lu %lu
long int %ld %ld

unsigned int %u %u
int %d %d
Low
unsigned short %hu %hu
short %hd %hd
char %c %c
OBJECTIVES
 To construct programs modularly from small pieces called
functions.
 The common math functions available in the C Standard
Library.
 How to create new functions.
 The mechanisms used to pass information between functions.
 How to write and use recursive functions, i.e., functions that
call themselves.
Calling Functions: Call by Value and Call by Reference
 Call by value
 Copy of argument passed to function

 Changes in function do not effect original

 Use when function does not need to modify argument

 Avoids accidental changes

 Call by reference
 Passes original argument

 Changes in function effect original

 Only used with trusted functions

 For now, we focus on call by value


Storage Classes
 Storage class specifiers
 Storage duration – how long a variable exists in memory

 Scope – where a variable can be referenced in program


Storage Classes
 Static storage
 Variables exist for entire program execution

 Default value of zero

 static: is a local variables defined in functions.


 Keeps (Maintains) its value after function ends

 Only known in their own function


Scope Rules
 File scope (global scope)
 Identifier (variable or constant) defined outside function,

and be above all functions

 Function scope (local scope)


 Can only be referenced inside a function body
Scope Rules
 Block scope
 Identifier declared inside a block { }

 Block scope begins at definition, ends at right brace


 Used for variables, function parameters (local variables of
function)
 Outer blocks "hidden" from inner blocks if there is a
variable with the same name in the inner block
1 /* Fig. 5.12: fig05_12.c
2 A scoping example */
3 #include <stdio.h>
4
5 void useLocal( void ); /* function prototype */
 fig05_12.c
6
7
void useStaticLocal( void ); /* function prototype */
void useGlobal( void ); /* function prototype */
(1 of 4 )
8
9 int x = 1; /* global variable */
10 Global variable with file scope
11 /* function main begins program execution */
12 int main( void )
13 {
14 int x = 5; /* local variable to main */ Variable with block scope
15
16 printf("local x in outer scope of main is %d\n", x );
17
18 { /* start new scope */
19 int x = 7; /* local variable to new scope */ Variable with block scope
20
21 printf( "local x in inner scope of main is %d\n", x );
22 } /* end new scope */
23
24 printf( "local x in outer scope of main is %d\n", x );
25
26 useLocal(); /* useLocal has automatic local x */
27 useStaticLocal(); /* useStaticLocal has static local x */
28 useGlobal(); /* useGlobal uses global x */
29
30
useLocal(); /* useLocal reinitializes automatic local x */
useStaticLocal(); /* static local x retains its prior value */
 fig05_12.c
31
32
useGlobal(); /* global x also retains its value */ (2 of 4 )
33 printf( "\nlocal x in main is %d\n", x );
34
35 return 0; /* indicates successful termination */
36
37 } /* end main */
38
39 /* useLocal reinitializes local variable x during each call */
40 void useLocal( void )
41 {
42 int x = 25; /* initialized each time useLocal is called */
43
Variable with block scope
44 printf( "\nlocal x in useLocal is %d after entering useLocal\n", x );
45 x++;
46 printf( "local x in useLocal is %d before exiting useLocal\n", x );
47 } /* end function useLocal */
48
49 /* useStaticLocal initializes static local variable x only the first time
50 the function is called; value of x is saved between calls to this
51 function */
52 void useStaticLocal( void )
53
54
{
/* initialized only first time useStaticLocal is called */
 fig05_12.c
55
56
static int x = 50;
Static variable with block scope (3 of 4 )
57 printf( "\nlocal static x is %d on entering useStaticLocal\n", x );
58 x++;
59 printf( "local static x is %d on exiting useStaticLocal\n", x );
60 } /* end function useStaticLocal */
61
62 /* function useGlobal modifies global variable x during each call */
63 void useGlobal( void )
64 {
65 printf( "\nglobal x is %d on entering useGlobal\n", x );
66 x *= 10;
67 printf( "global x is %d on exiting useGlobal\n", x );
Global variable
68 } /* end function useGlobal */
local x in outer scope of main is 5
local x in inner scope of main is 7
local x in outer scope of main is 5

local x in useLocal is 25 after entering useLocal


local x in useLocal is 26 before exiting useLocal

local static x is 50 on entering useStaticLocal


local static x is 51 on exiting useStaticLocal
 fig05_12.c
global x is 1 on entering useGlobal
global x is 10 on exiting useGlobal
(4 of 4 )
local x in useLocal is 25 after entering useLocal
local x in useLocal is 26 before exiting useLocal

local static x is 51 on entering useStaticLocal


local static x is 52 on exiting useStaticLocal

global x is 10 on entering useGlobal


global x is 100 on exiting useGlobal

local x in main is 5
OBJECTIVES
 To construct programs modularly from small pieces called
functions.
 The common math functions available in the C Standard
Library.
 How to create new functions.
 The mechanisms used to pass information between functions.
 Review

You might also like