Академический Документы
Профессиональный Документы
Культура Документы
Programming (functions
part 1
BJ Furman
27FEB212
Learning !"#ecti$es
Parameters
1&)2
Easier to read
main(7
9ser4defined functions
x x x f
11 is ) 2 (
11 3 4 4 3 ) 2 ( 2 ) 2 ( ) 2 (
2
f
f
+ + + +
f(2)? is What
) ( x f
2 11
X
Function
Returned
value
Functions 4 <efinition .tructure
Function =&eader=
>ame
<escripti$e
+rguments (or
parameter list7
.tatements
;aria"le declaration
!perations
state!ents?
"
double product(double x, double y)
{
double result;
result = x * y;
return result;
}
+ function t&at calculates t&e product of t(o num"ers
Functions 4 E%ample
Function prototype
>ote semicolon@@
Function definition
Function return
if return expression;
Function call
1rite a function
named =sum=
sums t(o
integers
2 min, on )our
o(n
.&are (it&
neig&"or
#teps
1. Function header
A return data t)pe
A function name
A argument list (it& data t)pes
2. Statements in function definition
A $aria"le declaration
A operations
A return $alue
Function 4 sum(7
int sum,int(int x, int y)
{
int result;
result = x - y;
return result;
}
Functions t&at do not return a $alue
Practice
&app)Bface(7
sadBface(7
1or- in pairs
Pseudocode $irst%%
Pseudocode
1, <eclare and initialiFe $aria"les
2, 13:LE user input not eEual to E +>< not eEual to D
17 .(itc& on user input to
27 'ase =7/:
call &app)Bface(7?
"rea-?
57 'ase =(/:
call sadBface(7?
"rea-?
G7 'ase /E0:
77 'ase /D0:
&rea';
H7 'ase /0:
I7 <efault:
re4prompt for user input
Program 4 Faces code
.tructuring ' Programs
ModulariFation
:nstead of:
oneB"igBprogram,c
"rea- into groupings of &eader files (,&7 and source code (,c7 files:
module,#.h
module,#.c
etc.
*ationale
<eclaration of constants
Function protot)pes
Pertinent comments
*e$ie(
.tructured Programming
.eEuence
:F
:F4EL.E
.1:5'3
13:LE
<!413:LE
F!*
.tructure of a ' program
E%, !ree,!all,d,"s,time.c
' 'ode for <K< L,15c
(rogra!!er)s &loc'
(re*processor directive
+eclare and initiali,e
varia&les
-.ile loop
(repetition structure)
/ain $unction (state!ents go &et0een " )
return state!ent
+rit&metic (it& :ntegers and Mi%ed <ata 5)pes
*esult is an integer
1M1 44N 2
OJ2 44N 2
E%ample in '&
char a = 5;
si6eo!(a);
double b=$;
si6eo!(b);
print!((a-b == )l! and needs )d bytes*n (, a-b,
si6eo!(a-b));
*eferences
mat&,&
&ttp:JJ(((,opengroup,orgJonlinepu"sJ7
IH7IIJ%s&Jmat&,&,&tml