Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views32 pages

CSC3301 Lecture 03 Function

Uploaded by

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

CSC3301 Lecture 03 Function

Uploaded by

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

5/8/2024

CSC 3301: STRUCTURAL PROGRAMMING


Lecture-04
Function

REVIEW OF STRUCTURED
PROGRAMMING

• Structured programming is a problem solving strategy and a


programming methodology that includes the following
guidelines:
• The program uses only the sequence, selection, and repetition control structures.
• The flow of control in the program should be as simple as possible.
• The construction of a program embodies top-down design.

1
5/8/2024

REVIEW OF TOP-DOWN DESIGN

• Involves repeatedly decomposing a problem into smaller problems


• Eventually leads to a collection of small problems or tasks each of which can be easily
coded
• The function construct in C is used to write code for these small, simple problems.

INTRODUCTION

• To make large programs manageable and less complicated


• they are broken down into subprograms
• providing a hierarchy of sub-programs

• These subprograms are called functions


• this provides well-structured programs
• each functions performs a limited and well defined task

• The basic principle of functions is DIVIDE AND CONQUER


• using functions we can divide a larger task into smaller subtasks
that are manageable

2
5/8/2024

WHAT IS A FUNCTION?

• A function is a self contained block of statements


• it may have its own variables and constants
• It is designed to do a well defined task
• it has a particular job to perform
• It has a name
• can be invoked by the name given to it
• It may have return type

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

• Choose a name CREATE YOUR FUNCTION


• Function should perform a single well defined task
• If you can’t find a concise descriptive name, you may have too many jobs for the function
• Define a contract
• Inputs
• Arguments – choose type
• None should be noted as void
• Will the function change the parameter’s value?
• Output
• Only one ; by convention, 0 means good

• 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 square ( int y ); // function prototype SAMPLE FUNCTION


// function main begins program execution

int main ( void )

{ int x; // counter

for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time

printf ( "%d ", square ( x ) ); // function call

puts (""); // add a blank line

// square function returns the square of its parm

int square ( int y ) // y is a copy of the x sent

return y * y; // returns square of y as an int

D From Deitel C How to Program

RETURN

• return serves two purposes:


– It tells the computer the value to return as the result
– It tells the computer to leave the function immediately and return the calling function (or the
main program).

• 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

• Why write functions?


• modularity
• re-use
• maintenance / testing

7
5/8/2024

WHY USE FUNCTION?

• Functions are a structured way to programming


• larger programs get divided into smaller manageable units

• If a specific block of statements has to be executed multiple times


• redundancy in writing the same piece of code multiple times is avoid

• Functions help to easily:


• code larger program
• reduces the debugging effort

FUNCTION DEFINITIONS

• Create customized functions to


• Take in data
• Perform operations
• Return the result
• Format for function definition:
return-value-type function-name( parameter-list )
{
declarations and statements
}
• Example:
int square( int y)
{
return y * y;
}

8
5/8/2024

HOW FUNCTION WORKS

 A function is a block of code which only runs


when it is called. You can pass data, known as
parameters, into a function.
 Functions are used to perform certain actions,
and they are important for reusing code:
 Define the code once, and use it many times

HOW FUNCTION WORKS CONTD


• The program contains three functions
• main() function, function1(), function2()
• The program execution begins with main()
• all the statements inside main() get executed
• A function gets called:
• when the function name is followed by a semicolon
• A function is defined:
• when function name is followed by a pair of braces in which one or more
statements may be present

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).

WHERE DO THE VARIABLES LIVE?

• On Stack: (lives and dies with function)


• Local – created in the function – automatic – on stack
• Argument – same as local
• On Heap: (lives with program life)
• Use keyword static
• static int x = 1;
• When you return to the function it will retain old value
• Global
• declare outside a function block

11
5/8/2024

FUNCTION CALL STACK

• Pile like one of dishes


• Access from the top
• Call a function – push it on the stack
• Execute function
• Push on other functions from within function
• Variables created in the stack
• Finish executing a function – pop it off the stack
• supports the creation, maintenance and destruction of each called function’s automatic
variables (local variables, parameters)

FUNCTIONS

• A C program is made up of one or more functions, one of which is main( ).


• Execution always begins with main( ), no matter where it is placed in the
program. By convention, main( ) is located before all other functions.
• When program control encounters a function name, the function is called
(invoked).
• Program control passes to the function.
• The function is executed.
• Control is passed back to the calling function.

12
5/8/2024

SAMPLE FUNCTION CALL


#include <stdio.h>

int main ( ) printf is the name of a predefined


{ function in the stdio library

printf (“Hello World!\n”) ; this statement is


return 0 ; is known as a
} function call
this is a string we are passing
as an argument (parameter) to
the printf function

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

MATH LIBRARY FUNCTIONS

• Math library functions


• Allow the programmer to perform common mathematical
calculations
• Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)

• 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

MATH LIBRARY FUNCTIONS

• Function arguments can be


• Constants
sqrt( 4 );

• Variables
sqrt( x );

• Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );

14
5/8/2024

EXAMPLE: MATH LIBRARY FUNCTIONS

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.}

GOOD PROGRAMMING PRACTICE


• Notice the function header comment before the definition of function
printMessage.

• This is a good practice and is required by the 104 C Coding Standards.

• Your header comments should be neatly formatted and contain the following
information:
• function name

• function description (what it does)

• a list of any input parameters and their meanings

• a list of any output parameters and their meanings

• a description of any special conditions

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.

COMMONLY USED HEADER FILES

Header File Contains Function Prototypes for:


<stdio.h> standard input/output library functions
and information used by them
<math.h> math library functions
<stdlib.h> conversion of numbers to text, text to
numbers, memory allocation, random
numbers, and other utility functions
<time.h> manipulating the time and date
<ctype.h> functions that test characters for certain
properties and that can convert case
<string.h> functions that manipulate character strings
others see Chapter 5 of text

16
5/8/2024

USER DEFINED FUNCTIONS


• These are the functions other than the Standard Library
Functions

• These are created by the users

• The user has the flexibility to choose the function:


• name
• the statements that will be executed
• the parameters that will be passed to the function
• the return type of the function

USER DEFINED FUNCTIONS CONTD

• Any program using functions will have the following three


necessary things:
• function prototype or function declaration
• It is the name of the function along with its return-type and parameter list

• 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

USER DEFINED FUNCTIONS CONTD


• The general syntax definition of function is as follows:
return-type name(parameter_List)

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

USER DEFINED FUNCTIONS CONTD

• The function body contains:


• the code that performs the function’s action
• the return statement that specifies the value that the
function sends back to the place where it was called
usually main()

• Example
int square(int x)
{
return x*x; //returns square of x
}

18
5/8/2024

USER DEFINED FUNCTIONS CONTD


• Local variables in functions
• are variables that are declared inside a function definition
• Its only local to the function
• It cannot be used anywhere out side the function
• They exist only when the function is executing

• 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

USER DEFINED FUNCTIONS CONTD

• Function Prototypes:
• The general syntax of a function prototype is
return-type function-name(parameter_list);

• Following are some examples function declaration


float area(float length, float breadth);
float perimeter(float side1, float side2);
• The parameter names are optional in a function declaration
• they are simply dummy variables
float sum_angle(int, int, int);

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. }

COPY-PASTE CODING (BAD)


1. int main() {
2. int threeExpFour = 1;
3. for (int i = 0; i < 4; i = i + 1) {
4. threeExpFour = threeExpFour * 3;
5. }
6. cout << "3^4 is " << threeExpFour << endl;
7. int sixExpFive = 1;
8. for (int i = 0; i < 5; i = i + 1) {
9. sixExpFive = sixExpFive * 6;
10. }
11. cout << "6^5 is " << sixExpFive << endl;
12. int twelveExpTen = 1;
13. for (int i = 0; i < 10; i = i + 1) {
14. twelveExpTen = twelveExpTen * 12;
15. return 0;
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.}

WHY DEFINE YOUR OWN FUNCTIONS?


• Readability:
• defining a function is clearer than copy-pasting in an algorithm
• Maintainability:
• to change the algorithm, just change the function (vs changing it everywhere you ever
used it)
• Code reuse:
• lets other people use algorithms you’ve implemented
• Note:
• You don’t actually need to implement “raiseToPower” and “squareRoot” yourself;
• Cmath (<math.h>) contains functions pow and sqrt

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; }

• Program chooses function by signature


• signature determined by function name and parameter types
• Can have the same return types

FUNCTION OVERLOADING

• Also called Function Polymorphism


• the same function name can be used to create multiple function
definitions to perform different tasks

• 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

• A function can have more than one parameter:


int functionA( int a, int b, float c )
• When the function is invoked, the parameters can be a variable, constant,
or expression:
result = functionA( 7, 3 + a, dollars);
• The value 7 is put into to local variable a, 3 + a is put into local variable b,
and a copy of the value in dollars is put into c in this example.

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
}

void printMessage (int counter)


{
int i ;
for ( i = 0; i < counter; i++ )
{
printf (“Have a nice day!\n”) ;
}
}

23
5/8/2024

USING PARAMETERS (CONT’D)

• 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 OVERLOADING CONTD


//function declarations
int multiply(int m, int n);
int multiply(int m, int n, int p);
double multiply(double m , double n);
double multiply(double m , int n);
double multiply(int m, double n);

//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 OVERLOADING CONTD

//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);
}

WHAT ARE REFERENCE PARAMETERS?

• Reference parameters do not copy the value of the parameter.


• Instead, they give the function being called a copy of the address at which the data is
stored. This way, the function works with the original data.
• We call this passing by reference because we are making references to the parameters.

25
5/8/2024

PASS BY VALUE VS BY REFERENCE

• There are two ways in which a function can be called, they


are:
• Call by value
• Call by reference

• 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

REFERENCES AND REFERENCE


PARAMETERS
• Call by value
• Copy of data passed to function
• Changes to copy do not change original
• Used to prevent unwanted side effects
• Call by reference
• Function can directly access data
• Changes affect original
• Reference parameter alias for argument
• & is used to signify a reference
void change( int &variable )
{ variable += 3; }
• Adds 3 to the variable inputted
int y = &x.
• A change to y will now affect x as well

26
5/8/2024

Before call to increment ()


main function scope increment function scope

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

PASS BY REFERENCE CONTD


• Pass by reference
• if you want to modify the original variable as opposed to
making a copy
• i.e, change the value of the parameter passed to it

• pass the variable by reference


• use (int &a) instead of (int a)
• Now the argument is read-write instead of read-only

• any change to the local variable inside the function will


cause the same change to the argument that was passed
to it

PASS BY REFERENCE CONTD


//pass-by-reference
void increment(int &a)
{
a = a + 1;
cout <<"a in increment"<<a<<endl;
}
int main()
{
int q = 3;
increment(q); //works
cout <<"q in main"<<q<<endl;
}

Output
a in increment 4
q in main 4

28
5/8/2024

PASS BY REFERENCE CONTD


Before call to increment ()
main function increment function
scope scope
q=3 a
When call is made to the
increment ()
main function increment function
scope scope
q=3 a
Value after call to the increment ()
main function increment function
scope scope
q=4 q=4

PASSING REFERENCE PARAMETERS

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

WHEN TO USE VALUE AND REFERENCE


PARAMETERS
• We use value parameters when:
– We are not going to change the parameters’ value
– We may change it but the main program should not know about it

• When we are simply printing the value


– We use reference parameters when:
– We are going to change the parameter’s value and the main program MUST know
about it.
– We are reading in a new value

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

RECURSION VS. ITERATION

• 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

You might also like