t06AFunctionsDeclarations Pps
t06AFunctionsDeclarations Pps
CSCI 230
Functions
Declarations
Dale Roberts, Lecturer
IUPUI
[email protected]
Dale Roberts
Programmers
Trivial
1
Small
1-3
Medium
2-5
Large
5-25
Very Large
25-100
Extremely Large > 100
Duration
Size of Code
1-2 weeks
Few Weeks
Few Months
1 - 3 years
3 - 5 years
> 5 years
Dale Roberts
Program Modules in C
Functions
Modules in C
Programs combine user-defined functions with library functions
C standard library has a wide variety of functions
Math function, I/O, string function, such as printf(), scanf()
Function calls
Invoking functions
Provide function name and arguments (data)
Function performs operations or manipulations
Function returns results
Write function once and call it many times
Dale Roberts
Dale Roberts
Functions
Functions
Modularize a program
All variables declared inside functions are local variables
Known only in function defined
Parameters
Communicate information between functions
Local variables
Benefits of functions
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new programs
Abstraction - hide internal details (library functions)
Function Definitions
Function definition format
return-value-type function-name( parameter-list )
{
declarations and statements
}
Function-name: any valid identifier
Return-value-type: data type of the result (default int)
void indicates that the function returns nothing
An unspecified return-value-type is always assumed by the compiler to be int
Returning control
If nothing returned
return;
or, until reaches right brace
If something returned
return expression;
Dale Roberts
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, int, int );
Takes in 3 ints
Returns an int
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* function prototype */
1. Function prototype
(3 parameters)
int main()
{
int a, b, c;
printf( "Enter three integers: " );
scanf( "%d%d%d", &a, &b, &c );
printf( "Maximum is: %d\n", maximum( a, b, c ) );
2. Input values
3. Call function
return 0;
}
4. Function definition
Program Output
Dale Roberts
Examples
float plus1(float
x,y)
{
float sum;
sum = x + y;
return sum;
}
plus2(int x,y)
{
int sum;
sum = x + y;
return sum;
}
Acknowledgements
Some examples were obtained from the course
textbook.
Dale Roberts