CSC3301 Lecture 03 Function
CSC3301 Lecture 03 Function
REVIEW OF STRUCTURED
PROGRAMMING
1
5/8/2024
INTRODUCTION
2
5/8/2024
WHAT IS A FUNCTION?
FUNCTIONS
• Functions
• Allow the programmer to modularize a program
• Local variables
• Known only in the function in which they are defined
• All variables declared in function definitions are local variables
• Parameters
• Local variables passed when the function is called that provide the function
with outside information
3
5/8/2024
MATH
• #include <math.h>
• Use any math function
• If c1 = 13.0, d = 3.0 and f = 4.0, then the statement
printf( "%.2f", sqrt( c1 + d * f ) );
4
5/8/2024
• Write prototype
• Looks like function header but has ;
• int square( int y );
• Tells compiler what is valid input and output
• Forces type conversion
• Write body
• Call the function
5
5/8/2024
#include <stdio.h>
{ int x; // counter
for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time
RETURN
• Void return:
– Ex: void printit ( int x );
– You can still return to leave, but without a value
6
5/8/2024
PROTOTYPES
• Looks like function header but has ;
• int square( int y );
• Forces type conversion
• Tells compiler what is valid input and output
• Placement
• Applies to all functions appearing within the top level braces (or all if outside
all braces)
• Can put into its own .h file and then include without <>
• #include “myfunctions.h” (no semicolon)
• No Overloading
• Every function name can have only one contract
FUNCTIONS
7
5/8/2024
FUNCTION DEFINITIONS
8
5/8/2024
9
5/8/2024
TYPES OF FUNCTION
• Functions are of two types
• Built-in functions
• User defined functions
• Built-in Functions:
• These are the functions that are already present
• i.e. predefined in the system
• as the name suggests it is a Library of functions
• have been written, compiled and placed in libraries under header files
• Example
• setw() is compiled and placed in the header file <iomanip.h>
NOTES ON FUNCTIONS
• The convention for naming functions is the same as for variables. A function name
must start with a letter, should be meaningful, should not use the name of an existing
function, and should not be excessively long.
• It is important that you give meaningful variable names to variables inside a function
that you write, so that you and others can understand what the function does.
• Comments become extremely important in functions. Comments help both you and
anyone who might use the function to understand what it does.
10
5/8/2024
NOTES ON VARIABLES
• Variables that are created inside of a user-defined function may only be accessed from
inside of that function. They are referred to as local variables.
• After the function completes its operations, the local variables are deleted from memory.
• The only variable that appears in the workspace is the output, if any, of the function.
• Conversely, functions cannot access variables from the workspace (with the exception of
any input parameters they might have or “global variables”---see MATLAB help on this
matter).
11
5/8/2024
FUNCTIONS
12
5/8/2024
FUNCTIONS (CON’T)
• We have used three predefined functions so far:
• printf
• scanf
• getchar
• There are 3723 predefined functions on the
gl system. Don’t worry, nobody knows them
all!
13
5/8/2024
• Example
cout << sqrt( 900.0 );
• Calls the sqrt (square root) function. The preceding statement
would print 30
• The sqrt function takes an argument of type double and returns a
result of type double, as do all functions in the math library
• Variables
sqrt( x );
• Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
14
5/8/2024
1. #include <iostream.h>
2. using namespce std;
3. #include<math.h>
4. int main()
5. {
6. cout<<"Number"<<"\tSquare Root\n";
7. for(int i=1;i<=10;i++)
8. {
9. cout<<i<<"\t"<<sqrt(i)<<endl;
10. }
11. return 0;
12.}
• Your header comments should be neatly formatted and contain the following
information:
• function name
15
5/8/2024
HEADER FILES
• Header files contain function prototypes for all of the functions found in the specified
library.
• They also contain definitions of constants and data types used in that library.
16
5/8/2024
• function call
• any function name inside the main() followed by semicolon (;) is a Function Call
• function definition
• a function name followed by a pair of parenthesis {} including one or more statements
17
5/8/2024
statements;
return value;
}
• The function head tells the compiler about three things:
• name of the function
• its return-type
• i.e type of value to be returned by the function
• its parameter list
• Example
int square(int x)
{
return x*x; //returns square of x
}
18
5/8/2024
• Formal arguments
• are variables in the parameter list of function definition
• they are also local variables
• exist only for the duration of the function execution
• Actual arguments
• are the variable being passed to a function
• Function Prototypes:
• The general syntax of a function prototype is
return-type function-name(parameter_list);
19
5/8/2024
1. #include <iostream.h>
2. using namespace std;
EXAMPLES
3. int square(int m); //Function Prototype
4. int main()
5. {
6. int num, sqr=0;
7. cout<<"\nEnter number to find its Square"<<"\t ";
8. cin>>num;
9. sqr=square(num); //Function call
10. cout<<"\nSquare of "<<num<<" = " <<sqr;
11. return 0;
12. }
13. int square(int x) //Function definition
14. {
15. return x*x; //returns square of x:
16. }
20
5/8/2024
1.
WITH A FUNCTION
int main() {
2. int threeExpFour = raiseToPower(3, 4);
3. cout << "3^4 is " << threeExpFour << endl;
4. int sixExpFive = raiseToPower(6, 5);
5. cout << "6^5 is " << sixExpFive << endl;
6. int twelveExpTen = raiseToPower(12, 10);
7. cout << "12^10 is " << twelveExpTen << endl;
8. return 0;
9. }
10.int raiseToPower(int base, int exp) //Function def.
11.{
12. int result = 1;
13. for (int i = 0; i < exp; i = i + 1) {
14. result = result * base;
15. }
16. return result //returns exponential of a number
17.}
21
5/8/2024
FUNCTION OVERLOADING
• Function overloading
• Having functions with same name and different parameters
• Should perform similar tasks ( i.e., a function to square ints, and function to
square floats).
int square( int x) {return x * x;}
float square(float x) { return x * x; }
FUNCTION OVERLOADING
• It means that we can have a set of functions that have the same
name but different signatures.
• a function signature includes its return type and parameter list
22
5/8/2024
PARAMETER LIST
USING PARAMETERS
void printMessage (int counter) ;
int main ( void )
{
int num;
printf (“Enter an integer: “) ;
scanf (“%d”, &num) ;
printMessage (num) ; one argument matches the one formal parameter
return 0 ; of type int of type int
}
23
5/8/2024
• In this example, we do not know in advance what the user will enter for the value of
num, however, it is copied into the variable counter in the function printMessage( ).
• Both the variables counter and i are considered to be local variable, because they are
only visible inside (or local to) the function printMessage( ).
//function calls
int mul = multiply(10, 20);
int mul = multiply(10, 20,3);
double mul = multiply(2.5, 3.5);
double mul = multiply(1.2, 3);
double mul = multiply(2, 3.5);
24
5/8/2024
//function definitions
int multiply(int m, int n)
{
return (m*n);
}
int multiply(int m, int n, int p)
{
return (m*n*p);
}
double multiply(double m , double n)
{
return (m*n);
}
25
5/8/2024
• Pass by value
• So far we’ve been passing everything by value
• makes a copy of the variable
• changes to the variable within the function don’t occur
outside the function
• i.e, changes made to the formal parameters do not change
the actual parameters
26
5/8/2024
q=3 a
When call is made to the increment ()
PASS BY VALUE
main function scope increment function scope
q=3 a=3
Value after call to the increment ()
main function scope increment function scope
q=3 q=4
PASS BY VALUE
//pass-by-value
void increment(int a)
{
a = a + 1;
cout<<"a in increment"<<a<<endl;
}
int main()
{
int q = 3;
increment(q); //does nothing
cout<<"q in main"<<q<<endl;
}
Output
a in increment 4
q in main 3
27
5/8/2024
Output
a in increment 4
q in main 4
28
5/8/2024
Any data
number 4.0 y intended for y
in the
function goes
to the
location of
number in the
main
program
29
5/8/2024
RECURSIVE FUNCTIONS
• A recursive function is one which calls itself
• It is a function being executed where one of the instructions is to
"repeat the process“
• The Syntax is as follows: void recursive();
int main()
{
recursive();
return 0;
}
void recursive()
{
recursive();
}
30
5/8/2024
RECURSION
• Recursive functions
• Are functions that calls themselves
• Can only solve a base case
• If not base case, the function breaks the problem into a slightly smaller, slightly
simpler, problem that resembles the original problem and
• Launches a new copy of itself to work on the smaller problem, slowly converging
towards the base case
• Makes a call to itself inside the return statement
• Eventually the base case gets solved and then that value works its way back up
to solve the whole problem
RECURSION
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
• Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
• Base case (1! = 0! = 1)
31
5/8/2024
• Repetition
• Iteration: explicit loop
• Recursion: repeated function calls
• Termination
• Iteration: loop condition fails
• Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good software engineering (recursion)
32