Lecture 09
Lecture 09
Lecture 09:
Functions (Part II)
• Advantages
– It's easier to debug a structured program. If
your program has a bug (something that
causes it to work improperly), a structured
design makes it easy to isolate the problem to
a specific section of code (a specific function).
Structured Programming
• Advantages
– Time saving: You can easily use a function
you wrote in another program that needs to
do the same task. Even if the new program
needs to do a slightly different task, you can
modify the function, that is easier than writing
a new one from scratch: Consider the two
functions printf() and scanf(). If your
functions have been created to perform a
single task, using them in other programs is
much easier
Planning a Structured Program
globalVar += localVar;
return (paramVar + localVar);
}
int main()
{
int localVar = 5;
return 0;
}
Example: scope.c
int globalVar = 0; Global variable declaration
int increment ( int paramVar )
{
int localVar = 2;
globalVar += localVar;
return (paramVar + localVar);
}
int main()
{
int localVar = 5;
return 0;
}
Example: scope.c
int globalVar = 0;
int main()
{
int localVar = 5;
return 0;
}
Example: scope.c
int globalVar = 0;
int main()
{
int localVar = 5;
return 0;
}
Example: scope.c
int globalVar = 0;
globalVar += localVar;
return (paramVar + localVar);
}
int main()
{
int localVar = 5;
return 0;
}
Variable Scope – “Do”s and
“Don’t”s
• DO use local variables for items such as
loop counters
• DON'T use global variables if they aren't
needed by a majority of the program's
functions
• DO use local variables to isolate the
values the variables contain from the rest
of the program
Prototyping of Functions
int imax(int,int);
int main(void)
{
printf("The maximum of %d and %d is %d.\n", 3, 5, imax(3,5));
return 0;
}
1
y= 1 +
1 + 1
1 + ... 1
1 + n
Example: Continuing Fraction
1
y= 1 +
1 + n
1
= 1 +
1 + 2
1.33333
Example: Continuing Fraction
1
y= 1 +
1 + 1
1 + ... 1
1 + n
Fraction(n, terms)
Example: Continuing Fraction
1
1 + 1
1 + ... 1
1 + n
Sum(n, terms)
Example: Continuing Fraction
1 + 1
1 + ... 1
1 + n
Fraction(n, terms - 1)
Example: Continuing Fraction
Last term:
1
1 + n
Sum(n, 1)