0% found this document useful (0 votes)
56 views

Functions Lectr01

The document discusses functions in programming. Some key points: - Functions allow programmers to break problems into smaller, more manageable parts and reuse code. They take in parameters and return values. - Functions are invoked through function calls that specify the name and pass arguments. They allow for modularity and code reuse. - Function definitions specify the return type, name, parameters, and body. They can take in data, perform operations, and return results. - Built-in functions like square root are provided by languages to perform common tasks more efficiently. Functions can also call themselves recursively to break problems into simpler sub-problems.

Uploaded by

huzi malix
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)
56 views

Functions Lectr01

The document discusses functions in programming. Some key points: - Functions allow programmers to break problems into smaller, more manageable parts and reuse code. They take in parameters and return values. - Functions are invoked through function calls that specify the name and pass arguments. They allow for modularity and code reuse. - Function definitions specify the return type, name, parameters, and body. They can take in data, perform operations, and return results. - Built-in functions like square root are provided by languages to perform common tasks more efficiently. Functions can also call themselves recursively to break problems into simpler sub-problems.

Uploaded by

huzi malix
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/ 25

Functions

Dr. Muhammad Hanif


Functions
• A function is simply a “chunk” of code that you can use over and over
again
• Functions enable programmers to break down or decompose a
problem into smaller parts, each of which performs a particular task.
• It combine many instructions into a single line of code
Functions
• Divide and conquer !!!

• Construct a program from smaller pieces or components


• Each piece more manageable than the original program
Functions
• Functions are invoked by a function call
• A function call specifies the function name and provides information
(as arguments) that the called function needs
• Boss to worker analogy:

• A boss (the calling function or caller) asks a worker (the called


function) to perform a task and return (i.e., report back) the
results when the task is done.
Functions
• Most programming languages provide many built in functions that
would otherwise require many steps to accomplish.
• Example: computing the square root of a number. In general, we
don't care how a function does what it does, only that it "does it“!
• When a function is "called" the program "leaves" the current section
of code and begins to execute the first line inside the function
• Thus, a function is a block of organized, reusable code that is used to
perform a single, related action
Functions
• Functions provide better modularity for application and a high degree
of code reusing.
• You have already seen various functions like Cin, Cout and main().
• These are called built-in functions provided by the language itself, but
we can write our own functions as well.
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
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 )
{ Example:
declarations and statements int square( int y)
} {
return y * y;
}
Function Definitions
• Function prototype
• Function name
• Parameters
• Information the function takes in
• Return type
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing
• Only needed if function definition comes after the function call in the program
• Example:
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int
Function: Syntax and Components
• The general syntax of a function is as follows:
• return_type function_name( arg_type argument, ... )
• {
• local_variable_type local_variables;
• executable statement(s); Example:
• return return_value; int add( int a, int b )
{
• } int sum;
sum = a + b;
return sum;
}
Function: Syntax and Components
• The "return type" indicates what kind of data this function will return
• The function name is an identifier by which this function will be known.
• It obeys the same naming rules as applied to variable names
( Alphanumeric characters, beginning with alpha, maximum 31 significant
characters, etc.)
• Arguments (formal parameters), receive the data passed to the function
• If a function takes no parameters, the parameters may be left empty.
• The body of the function is enclosed within curly {} braces, just as the
"main" function.
• It contains the instructions that will be executed when this function is
called
Example: 01
3 #include <iostream>
4
Notice how parameters and
5 using std::cout;
6 using std::endl;
return value are declared.
7
8 int square( int ); // function prototype
9
10 int main()
11 {
12 for ( int x = 1; x <= 10; x++ ) Output:
13 cout << square( x ) << " ";
14
1 4 9 16 25 36 49 64 81 100
15 cout << endl;
16 return 0;
17 }
18
19 // Function definition
20 int square( int y )
21 {
22 return y * y;
23 }
Example: 02
3 #include <iostream> 25 // Function maximum definition
26 // x, y and z below are parameters to
5 using std::cout;
27 // the maximum function definition
6 using std::cin; 28 int maximum( int x, int y, int z )
29 {
7 using std::endl; 30 int max = x;
31
9 int maximum( int, int, int ); // function prototype
32 if ( y > max )
11 int main() 33 max = y;
34
12 { 35 if ( z > max )
36 max = z;
13 int a, b, c;
37
15 cout << "Enter three integers: "; 38 return max;
39 }
16 cin >> a >> b >> c;
20 cout << "Maximum is: " << maximum( a, b, c ) << endl; Enter three integers: 22 85 17
Maximum is: 85

22 return 0; Enter three integers: 92 35 14


23 } Maximum is: 92

Enter three integers: 45 19 98


Maximum is: 98
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
Functions
• Function arguments can be
– Constants
sqrt( 4 );
– Variables
sqrt( x );
– Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
Recursion Function
• A function that calls itself is known as a recursive function
• Technique is known as recursion
• Provides a way to break complicated problems down into simple
problems which are easier to solve
• Recursion is the process of defining a problem (or the solution to a
problem) in terms of (a simpler version of) itself

• The recursion continues until some condition is met to prevent it


• if...else statement (or similar approach) can be used where one
branch makes the recursive call, and other doesn't
Recursion Function
• Example, we can define the operation "find your way home" as:

• If you are at home, stop moving.


• Take one step toward home.
• "find your way home".
Example:
Sum of Natural Numbers Using Recursion
Example:
Sum of Natural Numbers Using Recursion
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)


Example Using Recursion: The Fibonacci Series

• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...


• Each number sum of two previous ones
• Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)

• C++ code for fibonacci function


long fibonacci( long n )
{
if ( n == 0 || n == 1 ) // base case
return n;
else return fibonacci( n - 1 ) + fibonacci( n – 2 );
}
Example Using Recursion: The Fibonacci Series

• Diagram of Fibonnaci function


f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0
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)
Recursion: Advantage vs Disadvantage
• Recursion makes program elegant
• However, if performance is vital, use loops instead as recursion is
usually much slower.
Functions with Empty Parameter Lists

• Empty parameter lists


• Either writing void or leaving a parameter list empty indicates that the function
takes no arguments
void print();
or
void print( void );
• Function print takes no arguments and returns no value

You might also like