SlideShare a Scribd company logo
1
Chapter 1
Functions in C++
Computer Programming II (Seng-2021)
2
Objectives
After studying this chapter, students should be able to:
 Learn about Introduction to function in C++
 Learn about overview of component of function
 Learn about overview of function calling
 Learn about type of function
3
Introduction to Function in C++
 A program can be thought of as consisting of subparts, such as obtaining the input
data, calculating the output data, and displaying the output data.
 C++, like most programming languages, has facilities to name and code each of these
subparts separately. In C++ these subparts are called functions.
Top-Down Design
 A good plan of attack for designing the algorithm is to break down the task to be
accomplished into a few subtasks, decompose each of these subtasks into smaller
subtasks.
 the subtasks become so small that they are trivial to implement in C++. This
method is called top-down design.
 (The method is also sometimes called stepwise refinement, or more graphically,
divide and conquer.)
 Using the top-down method, you design a program by breaking the program’s task into subtasks
and solving these subtasks by subalgorithms.
4
Cont.
 A function is a group of statements that together perform a task.
 Every C++ program has at least one function, which is main, and all the most trivial
programs can define additional functions.
 You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is so each
function performs a specific task.
 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.
5
Cont.
Built-in Functions
• C++ comes with libraries of predefined functions that you can use in your programs
• C++ language is shipped with a lot of functions which are known as standard functions
• These built-in functions are groups in different libraries which can be included in the C++
program, e.g.
• Math functions are declared in <math.h> library
• Character-manipulation functions are declared in <ctype.h> library
• C++ is shipped with more than 100 standard libraries, some of them are very popular such as
<iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g.
<limits.h> and <largeInt.h>
6
Cont.
 Input/Output Functions:

cin: Used for reading input from the user.

cout: Used for displaying output to the console.

getline: Reads a line of text from the input.
 Mathematical Functions:
 abs: Returns the absolute value of a number.
 sqrt: Calculates the square root of a number.

pow: Raises a number to a specified power.

sin, cos, tan: Trigonometric functions.
 String Functions:

strlen: Returns the length of a string.

strcpy, strncpy: Copies one string to another.

strcmp, strncmp: Compares two strings.
 strcat, strncat: Concatenates strings.
 Memory Functions:
• malloc, calloc: Allocate memory dynamically.
• free: Deallocates memory allocated dynamically.
• memcpy, memmove: Copies blocks of memory.
• memset: Sets blocks of memory with a specific value.
 Conversion Functions:
• atoi, atol, atof: Converts a string to an integer, long, or
float, respectively.
• itoa, ltoa, ftoa: Converts an integer, long, or float to a
string, respectively.
 Time Functions:
• time: Returns the current time as the number of seconds
since January 1, 1970.
• ctime: Converts a time value to a string representation.
• localtime, gmtime: Converts a time value to a structure
representing local time or UTC time.
7
Cont.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "You entered: " << num << endl;
double squareRoot = sqrt(num);
cout << "Square root of " << num << "
is: " << squareRoot << endl;
return 0;
}
Function calling
the_root = sqrt(9.0);
function call
A function call is an expression consisting of the
function name followed by arguments enclosed in
parentheses. If there is more than one argument, the
arguments are separated by commas.
A function call is an expression that can be used like any other expression of the type specified for the value returned
by the function.
syntax
Function_Name(Argument_List) where the Argument_List is a comma-separated list of arguments:
Argument_1, Argument_2, . . . , Argument_Last
examples
side = sqrt(area);
cout << "2.5 to the power 3.0 is "
<< pow(2.5, 3.0);
8
Cont.
#include <iostream>
#include <string>
using namespace std;
int main() {
string message = "Hello, World!";
int length = message.length();
cout << "Message: " << message << endl;
cout << "Length of the message: " << length <<
endl;
return 0;
}
boss to worker
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.
9
User-Defined functions
 Standard function may not be enough to
satisfy all users need

E.g, to find largest of two numbers
 C++ provides its users with a way to define
their own functions
 Structure of user-defined function
 Function prototyping
 Function definition
 Functions are invoked by function call
 Its where execution of the function begins
Function prototype
Tells compiler argument type and return type of
function
• Format for function prototyping
return-type function-name(argu-type1, argu-
type2, ...);
if function returns nothing, return type void
For example
int square(int);
Function takes an int and returns an int
int square(int a);
Optional to specify parameters’ names
10
Function Definition
 Format for function definition
return-value-type function-name(parameter-list)
{
… declarations and statements
}

Parameter-list (type par1, type par2, …)

Comma separated list of arguments

Data type needed for each argument

If no arguments, use void or leave blank
Return-value-type
Data type of result returned (use void if
nothing returned)
For example
int square(int y)
{
return y * y;
}
return keyword
Returns data, and control goes to function’s caller
Function prototype must match function definition
Function prototype
int maximum(int, int, int);
Function definition
int maximum(int x, int y, int z)
{
…
}
Functions cannot be defined inside other functions
11
Function Calling
 Declared functions are not executed immediately.
 They are "saved for later use", and will be executed later, when they are called.
 To call a function,
 write the function's name
 followed by two parentheses () and a semicolon ;
 In the following example, myFunction() is used to print a text (the action), when it is called
//Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
12
Cont.
 A function can be called multiple times:
Example
void myFunction() {
cout << "I just got executed!n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
13
Function Declaration and Definition
 A C++ function consist of two parts:
 Declaration:

the return type,

the name of the function, and

parameters (if any)
 Definition: the body of the function (code to be executed)
void myFunction() { // declaration
// the body of the function
(definition)
}
14
Cont.
 Note: If a user-defined
function, such as myFunction()
is declared after the main()
function, an error will occur:
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got
executed!";
}
// Error
 However, it is possible to separate the declaration and
the definition of the function - for code optimization.
 You will often see C++ programs that have function
declaration above main(), and function definition
below main().
 This will make the code better organized and easier to
read:
Example
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the
function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got
executed!";
}
15
C++ Function Parameters
 Parameters and Arguments

Information can be passed to functions as a parameter. Parameters act as variables inside the
function.

Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2
, parameter3) {
// code to be executed
}
• The following example has a function that takes a string called fname as parameter.
• When the function is called, we pass along a first name, which is used inside the
function to print the full name:
16
Cont.
Example
void myFunction(string fname) {
cout << fname << " Refsnesn";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the function, it is called an argument.
So, from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.
17
C++ Default Parameters
Default Parameter Value
 You can also use a default
parameter value, by using the
equals sign (=).

If we call the function without
an argument, it uses the
default value ("Norway"):
Example
void myFunction(string country
= "Norway") {
cout << country << "n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter".
From the example above, country is an optional parameter and "Norway" is the
default value.
18
C++ Multiple Parameters
 Inside the function, you can add as many parameters as you want:
Example
void myFunction(string
fname, int age) {
cout << fname << " Refsnes. " <<
age << " years old. n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
Note that when you are working with multiple parameters, the function call must have the
same number of arguments as there are parameters, and the arguments must be passed in
the same order.
19
C++ The Return Keyword
 The void keyword, used in the previous examples, indicates that the function should
not return a value.
 If you want the function to return a value, you can use a data type (such as int, string,
etc.) instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
This example returns the sum of a function with
two parameters:
Example
int myFunction(int x, int y
) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
20
C++ Functions - Pass By Reference
 In the examples from
the previous page, we
used normal variables
when we passed
parameters to a function.
 You can also pass a
reference to the
function.
 This can be useful when
you need to change the
value of the arguments:
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "n";
cout << firstNum << secondNum << "n";
// Call the function, which will change the values of
firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "n";
cout << firstNum << secondNum << "n";
return 0;
}
22
Example 2
//Function to add two numbers and return the sum
#include<iostream>
using namespace std;
#include<math.h>
int addition (int , int ); // function prototype
int main ( )
{
int a, b, c;
cout<<"Enter the value of a and b? ";
cin>>a>>b;
c = addition (a, b); // function calling
cout << "The sum is "<<c;
}
// function definition
int addition (int x, int y)
{
int z;
z= x + y;
return (z);
}
23
Example 3
// Function to find the square of an integers between 1 and 10
#include<iostream>
using namespace std;
#include<math.h>
int square ( int ); // function prototype
int main ( )
{
for (int x = 1; x <= 10; x++)
cout<<square (x)<<" "; // function call
}
int square ( int y ) // function definition
{
return y * y;
}
24
Cont.
Functions with empty parameter lists
void or leave parameter list empty
Indicates function takes no arguments
For example
void print(void); // or
Optional to specify void in the
parameter list
void print( );
Function print takes no arguments
and returns no value
// Function with void return type and
empty parameter list
#include<iostream>
using namespace std;
void printmessage ( ); // function
prototype
int main ( )
{
printmessage ( ); // function
calling
}
void printmessage ( ) // function
definition
{
cout << "I'm a function!";
}
25
Example 5
//Function taking parameter list but with no
return type
#include<iostream>
using namespace std;
void addition (int , int ); // function prototype
int main ( )
{
int a, b, c;
cout<<"Enter the value of a and b? ";
cin>>a>>b;
addition (a, b); // function calling
}
// function definition
void addition (int x, int y)
{
int z;
z= x + y;
cout << "The sum is "<<z;
}
26
Scope of Variables
 The scope of a variable defines where it can be accessed/referenced in a
program
 Local variables
 All variables declared in the body of a function
 Only accessed by the function declared it
 All variables declared in main () are local variables
 Global variables

Declared outside of all functions, before main ( )
 Accessed by all functions, including main ( )
27
Example 6
// local variables
#include<iostream>
using namespace std;
void update ( ); // function prototype
int main ( )
{
int x=5; // declare x local
variable to main ()
cout<<"The value of x local in
main () is: "<<x<<endl;
update ( ); // function
calling
cout<<"nThe value of x local
in main () is: "<<x<<endl;
update ( ); // function
calling
}
void update ( )
{
// x is not declared in
update (), can be accessed anywhere
cout <<"The value of x on
entering update () is: "<< x<<endl;
x = x*10;
cout <<"The value of x on
exiting update () is: "<< x<<endl;
}
28
Example 7
// global variables
#include<iostream>
using namespace std;
void update ( ); // function prototype
int x=5; // declare x as global variable
int main ( )
{
// x is not declared in main
(), can be accessed anywhere
cout<<"The value of x in main
() is: "<<x;
update ( ); // function calling
cout<<"nThe value of x is:
"<<x;
}
// update ( ) modifies global variable x
during each call
void update ( )
{
// x is not declared in
update (), can be accessed anywhere
cout <<"The value of x on
entering update () is: "<< x<<endl;
x = x*10;
cout <<"The value of x on
exiting update () is: "<< x<<endl;
}
29
Example 8
// local variable and global variable having the same name
#include<iostream>
void update ( ); // function prototype
int x=5; // declare x as global variable
int main ( )
{
update ( ); // function calling
}
void update ( )
{
int x=25; // declare x local variable to update ()
cout<<"The value of x is: "<<x<<endl;
}
30
Scope Resolution Operator (: :)
• When global variable have same name with local variable in function

By default, local variable accessed in function
 Unary scope resolution operator (::)

Access global variable in function, if local variable has same name
 Format ::variable_name;
 For example

Cout<<::x;

y = ::x + 3;
31
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
32
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 0
Global variables are automatically
initialized to 0
33
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 0
void main()
{
x = 4;
fun();
cout << x << endl;
}
1
34
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x ????
3
35
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
3
36
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
4
37
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
5
38
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
6
39
Example of Defining and Using Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
7
40
Example 9
// Using the unary scope resolution
operator
#include<iostream.h>
void update ( ); // function prototype
int x=1; // declare x as global
variable
int main ( )
{
int x=5; // declare x local
variable to main ()
cout<<“ The value of local x
is ”<<x;
cout<<“ The value of global x
is ”<<::x; // access global x in
main ()
//update ( ); // function
calling
void update ( )
{
int x=25; // declare x
local variable to update ()
cout<<“The value of local
x is ”<<x;
cout<<“The value of global
x is ”<<::x; // access global x in
update ()
}
41
Storage Classes
 Storage class determines the period during which a variable exists in
memory
 Automatic variables

Variable created when program enters its block

Variable destroyed when program leaves block
 For example

By default, local variables of functions

keyword auto explicitly declares automatic

auto int x;
Static variables
Created at which the program begins execution
Initialized once, when declared
Existed for the duration of the program execution
For example
By default, global variables are static
Local variables declared with keyword static
static int x=20;
Retains its value between function
calls
Reference to variable is local in the
function
42
Passing Arguments to Function
 There are two ways to pass arguments to function

Passing by value

Copies of argument value passed to function parameters

Changes made to the function parameters have no effect on the values of arguments

Prevent unwanted side effects

Passing by reference

Copies of argument address passed to function parameters

Any changes made to the function parameters affects or modify the values of arguments
43
Example 1
// Passing arguments by value to function
#include<iostream>
using namespace std;
int squareByValue (int ); // function prototype
int main ( )
{
int x = 2;
cout<<"x before squareByValue (): "<<x<<endl;
cout<<"Value returned by squareByValue (): "<<squareByValue (x);
cout <<"nx after squareByValue (): "<<x;
}
int squareByValue( int number )
{
number = number * number;
return number;
}
44
Cont’d…
 There are two ways to pass arguments by
reference
 Pass by reference with reference arguments
 Pass by reference with pointer arguments
 To pass by reference with reference arguments
 Reference variable is used in function parameter

Alias for argument in function call
 Passes parameter by reference

Use & after data type in prototype

void myFunction(int &data);
 Read “data is a reference to an
int”

Function call format is the same
Reference variable
Alias for another variable
Contains the address of a variable (like a pointer)
A pointer constant, de-referenced
implicitly
Must be initialized when it is declared
Format to create a reference variable
type &reference-name =
referrer-name;
& indicates reference variable
Reference variable refer to variable of same type
Can be used within a function
45
Cont’d…
 For example
 int x=5; //declare x as integer variable

int &y=x; //create y as an alias for x

cout<<x;

cout<<y;
 Both output 5
 int x=5;
 int &y; // error
 y=x;

Must be initialized when it is declared
46
Example 2
// References must be initialized when declared
#include<iostream.h>
int main ( )
{
int x = 3;
int &y = x; // y refers to (is an alias for) x
cout<<"x = "<< x <<endl;
cout<<"y = "<< y <<endl;
y = 7;
cout<<"nx = "<<x<<endl;
cout<<"y = "<<y<<endl;
}
47
Example 3
// Pass argument by reference with reference argument
#include<iostream>
using namespace std;
void squareByReference( int & ); // function prototype
int main ( )
{
int z = 4;
cout<<"z before squareByReference (): "<<z << endl;
squareByReference (z);
cout <<"z after squareByReference (): "<<z;
}
void squareByReference( int &numberRef )
{
numberRef = numberRef *numberRef;
}
48
Cont’d…
 To pass by reference with pointer arguments

Pointer variable is used in function parameter

Use * after data type in prototype

void myFunction(int *data);

& used to pass address of argument in fun. calling

myFunction(&value);

Arrays not passed with &

Because array name is already a pointer
49
Example 4
// Pass argument by reference with pointer argument
#include<iostream.h>
void cubeByReference ( int * ); // function prototype
void main ( )
{
int number = 5;
cout<<"The original value of number is "<< number;
// pass address of number to cubeByReference
cubeByReference (&number );
cout << "nThe new value of number is " << number << endl;
}
void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr;
}
50
Passing Array to Function
 Specify name without brackets
 To pass array myArray to myFunction

int myArray[24];

myFunction(myArray,24);
 Array size usually passed, but not required

Useful to iterate over all elements
 Arrays passed by reference
 Functions can modify original array data
 Value of name of array is address of first
element

Function knows where the array is
stored
 Individual array elements passed by value
 Like regular variables
 square(myArray[3]);
 Functions taking arrays
 Function prototype for 1D array

void modifyArray(int [],
int);
 No need for array size between brackets

Ignored by compiler
51
Cont’d…
 If declare array parameter as const

Cannot be modified (compiler error)

void doNotModify(const
int []);
 Function prototypes for 2D arrays
 Must specify sizes of subscripts

First subscript not necessary,
as with single-scripted arrays
 void printArray(int[][3]);
//passing array to function
#include<iostream>
void printarray (int [ ], int ) ; // function prototype
void main ( )
{
int firstarray [ ] = {5, 10, 15};
int secondarray [ ] = {2, 4, 6, 8, 10};
printarray (firstarray, 3); // function
calling
printarray (secondarray, 5);
}
// function definition
void printarray (int array [ ], int size)
{
for (int i=0; i<size; i++)
cout<<array [i]<<" ";
cout << "n";
}
52
Example 6
// Effects of passing entire array by reference
#include<iostream.h>
void modifyArray ( int [ ], int );
void main ( )
{
const int arraySize = 5;
int a [arraySize]= { 0, 1, 2, 3, 4 };
cout <<"Effects of passing entire array by
reference"<<endl;
cout<<"nThe values of a before modifyArray ():
";
// output original array
for (int i = 0; i < arraySize; i++ )
cout <<a[ i ]<<" ";
// pass array a to modifyArray by reference
modifyArray (a, arraySize );
cout<<"nnThe values of a after modifyArray (): ";
// output modified array
for ( int j = 0; j< arraySize; j++ )
cout<<a[j]<<" ";
}
// in function modifyArray, "b" points to the original array
"a" in memory
void modifyArray( int b[ ], int sizeOfArray)
{
for ( int k = 0; k < sizeOfArray; k++ )
b[k] = b[k] * 2;
}
53
Example 7
// Effects of passing individual array element by
value
#include<iostream.h>
void modifyElement( int );
void main ( )
{
const int arraySize = 5;
int a [arraySize]= { 0, 1, 2, 3, 4 };
cout<<"Effects of passing individual array
element by value "<<endl;
cout<<"nThe value of a[3] before
modifyElement (): "<<a[3]<<endl;
// pass array element a[3] by value
modifyElement (a[3]);
// output value of a[ 3 ]
cout<<" nThe value of a[3] after modifyElement ():
"<<a[3];
}
// in function modifyElement, "e" is a local copy of array
element a[ 3 ] passed from main
void modifyElement( int e )
{
e = e * 2 ;
cout <<"nValue in modifyElement is: "<<e<<endl;
}
54
Example 8
// passing multidimensional arrays to function by
reference
#include <iostream.h>
void printArray (int [ ] [3]); // function prototype
void main ( )
{
int array1 [2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2 [2][3] = { 1, 2, 3, 4, 5 };
cout<<"Values in array1 by row are:"<<endl;
printArray (array1);
cout<<"nValues in array2 by row are:"<<endl;
printArray (array2 );
}
// function to output array with two rows and three
columns
void printArray (int a[ ][3])
{
for (int i = 0; i < 2; i++ )
{
for (int j = 0; j < 3; j++ ) // output column
values
cout<<a[ i ][ j ]<<" ";
cout<<endl;
}
}
55
Recursive Functions
 Recursive functions
 Functions that call themselves
 Can only solve a base case
 If not base case
 Break problem into smaller problem(s)
 Launch new copy of function to work on the smaller problem (recursive call/recursive step)

Slowly converges towards base case

Function makes call to itself inside the return statement
 Eventually base case gets solved

Answer works way back up, solves entire problem
56
Cont’d…
 For example, factorial of an integer n

n! = n * (n – 1) * (n – 2) * … * 1

Recursive relationship, n! = n * (n – 1)!

5! = 5 * 4!

4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1

Base case, 1! = 0! = 1
57
Example 11
// Using recursive function to find the factorial of an
integer
#include<iostream.h>
long factorial ( long );
void main ( )
{
long number;
cout<<"Enter a number: ";
cin>>number;
cout<<number << "! = "<<factorial
(number);
}
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
58
Inline Function
 Each time a function called, the compiler must do the followings:
 Remember where to return when the function eventually ends
 Provide memory for the function’s variables
 Provide memory for any value returned by the function
 Pass control to from function calling to the function called
 Pass control back to the calling function
 This extra activity constitutes the overhead, or cost of doing business, involved in
calling a function
59
Cont’d…
 Inline function
 Keyword inline before function
 Asks the compiler to copy code into program instead of making function call
 Appropriate argument substitutions made
 Reduce function call overhead
 Good for small, often-used functions
 Appears prior to the main(), which calls it
Any inline function must precede any function that calls it, which eliminates the need
for prototyping in the calling function
For example
inline double cube(double s)
{
return s * s * s;
}
60
Example 12
// Using inline function to calculate the volume of a cube
#include<iostream.h>
inline double cube (double side )
{
return (side * side * side);
}
void main ( )
{
double sideValue;
cout <<"Enter the side length of your cube: ";
cin>>sideValue;
cout <<"Volume of cube is "<<cube (sideValue );
}
61
Overloaded Functions
 Function overloading
 Functions having same name, but with different
set of parameters (type, number, and order)
 For example
 Function to square ints and function to square
floats
 int square(int x)
{
return x * x;
}
float square(float x)
{
return x * x;
}
• Compiler selects proper function to execute based
on number, types and order of arguments in the
function call.
• Commonly used to create several functions of the
same name that perform similar tasks, but on
different data types.
• Function can not be overloaded by its return type
62
Example 12
// using overloaded functions
#include<iostream.h>
int square ( int x );
double square ( double y );
void main ( )
{
int x;
x= square (7); // calls int version of square
double y;
y = square(7.5 );
// calls double version of square
cout <<"nThe square of integer 7 is
"<<x<<endl;
cout<< "nThe square of double 7.5 is "<<y;
}
// function square for int values
int square ( int x )
{
cout <<"Called square with int argument:
"<<x<<endl;
return x * x;
}
// function square for double values
double square( double y )
{
cout <<"Called square with double
argument: "<<y <<endl;
return y * y;
}
63
Building User-defined Libraries
• It is a good practice to group related functions into separate files, &
build your own libraries
 W/c can be then included in many files
 To build user-defined libraries,
 How to create header files to store function prototype
 How to create implementation files to store function definition, and link with the header file
 How to include the header file to your program to use your user-defined functions
64
How to Create Header Files
 The C++ header files must have name with .h extension
 Like string.h, math.h,… etc
 The contents of header file should have ff structure:
 #ifndef compiler directive
 #define compiler directive

May include some other header files

All functions prototype with some comments

Definitions of data types and constants
 #endif compiler directive
65
Cont’d…
 The header file is usually expected to reside in the same folder as the program file,
otherwise
 A full or relative path to it should be specified
 By default, all C++ standard header files are located in the C:TCWIN45INCLUDE
folder
 To include header files in your program file
 Standard library header files

#include<math.h>
 User-defined header files

#include "myheader.h"
66
Create taxrules.h Header File
#ifndef _TAXRULES_
#define _TAXRULES_
#include "taxrules.cpp"
double getIncome(char [ ]);
// purpose -- to get the employee income
// input -- a string prompt to be displayed to the user
// output -- a double value representing the income
67
Cont’d…
double computeTaxes(double);
// purpose -- to compute the taxes for a given income
// input -- a double value representing the income
// output -- a double value representing the taxes
void printTaxes(double);
// purpose -- to display taxes to the user
// input -- a double value representing the taxes
// output -- None
#endif
68
Create taxrules.cpp Implementation File
#include <iostream.h>
#include "taxrules.h "
double computeTaxes(double income)
{
if (income<5000)
return 0.0;
else
return 0.07*(income-5000.0);
}
double getIncome(char prompt [ ])
{
cout<<prompt;
double income;
cin>>income;
return income;
}
void printTaxes(double taxes)
{
cout<<"The taxes is $"<<taxes<<endl;
}
69
Include taxrules.h in Program File
#include<iostream.h>
#include "taxrules.h"
void main ( )
{
// get the income
double income;
income = getIncome ("Please enter the employee income: ");
// compute taxes
double taxes = computeTaxes(income);
// print employee taxes
printTaxes(taxes);
}
70
Worksheet
 What is the drawbacks of procedure-oriented programming?
 Write a program that generate random number using rand()?
 Write a program to find the Fibonacci Series of a given number using recursive
function?
Ad

More Related Content

Similar to Chapter 1 (2) array and structure r.pptx (20)

unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Functions
FunctionsFunctions
Functions
Lakshmi Sarvani Videla
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
Bharath904863
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in
divyamth2019
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
Sowri Rajan
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
BoomBoomers
 
Introduction to C Programming -Lecture 4
Introduction to C Programming -Lecture 4Introduction to C Programming -Lecture 4
Introduction to C Programming -Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Lecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptxLecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C language
FCSCJCS
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in
divyamth2019
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
BoomBoomers
 
Lecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptxLecture_5_-_Functions_in_C_Detailed.pptx
Lecture_5_-_Functions_in_C_Detailed.pptx
Salim Shadman Ankur
 
Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
MalligaarjunanN
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C language
FCSCJCS
 

Recently uploaded (20)

Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Ad

Chapter 1 (2) array and structure r.pptx

  • 1. 1 Chapter 1 Functions in C++ Computer Programming II (Seng-2021)
  • 2. 2 Objectives After studying this chapter, students should be able to:  Learn about Introduction to function in C++  Learn about overview of component of function  Learn about overview of function calling  Learn about type of function
  • 3. 3 Introduction to Function in C++  A program can be thought of as consisting of subparts, such as obtaining the input data, calculating the output data, and displaying the output data.  C++, like most programming languages, has facilities to name and code each of these subparts separately. In C++ these subparts are called functions. Top-Down Design  A good plan of attack for designing the algorithm is to break down the task to be accomplished into a few subtasks, decompose each of these subtasks into smaller subtasks.  the subtasks become so small that they are trivial to implement in C++. This method is called top-down design.  (The method is also sometimes called stepwise refinement, or more graphically, divide and conquer.)  Using the top-down method, you design a program by breaking the program’s task into subtasks and solving these subtasks by subalgorithms.
  • 4. 4 Cont.  A function is a group of statements that together perform a task.  Every C++ program has at least one function, which is main, and all the most trivial programs can define additional functions.  You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.  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.
  • 5. 5 Cont. Built-in Functions • C++ comes with libraries of predefined functions that you can use in your programs • C++ language is shipped with a lot of functions which are known as standard functions • These built-in functions are groups in different libraries which can be included in the C++ program, e.g. • Math functions are declared in <math.h> library • Character-manipulation functions are declared in <ctype.h> library • C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>
  • 6. 6 Cont.  Input/Output Functions:  cin: Used for reading input from the user.  cout: Used for displaying output to the console.  getline: Reads a line of text from the input.  Mathematical Functions:  abs: Returns the absolute value of a number.  sqrt: Calculates the square root of a number.  pow: Raises a number to a specified power.  sin, cos, tan: Trigonometric functions.  String Functions:  strlen: Returns the length of a string.  strcpy, strncpy: Copies one string to another.  strcmp, strncmp: Compares two strings.  strcat, strncat: Concatenates strings.  Memory Functions: • malloc, calloc: Allocate memory dynamically. • free: Deallocates memory allocated dynamically. • memcpy, memmove: Copies blocks of memory. • memset: Sets blocks of memory with a specific value.  Conversion Functions: • atoi, atol, atof: Converts a string to an integer, long, or float, respectively. • itoa, ltoa, ftoa: Converts an integer, long, or float to a string, respectively.  Time Functions: • time: Returns the current time as the number of seconds since January 1, 1970. • ctime: Converts a time value to a string representation. • localtime, gmtime: Converts a time value to a structure representing local time or UTC time.
  • 7. 7 Cont. #include <iostream> #include <cmath> using namespace std; int main() { int num; cout << "Enter a number: "; cin >> num; cout << "You entered: " << num << endl; double squareRoot = sqrt(num); cout << "Square root of " << num << " is: " << squareRoot << endl; return 0; } Function calling the_root = sqrt(9.0); function call A function call is an expression consisting of the function name followed by arguments enclosed in parentheses. If there is more than one argument, the arguments are separated by commas. A function call is an expression that can be used like any other expression of the type specified for the value returned by the function. syntax Function_Name(Argument_List) where the Argument_List is a comma-separated list of arguments: Argument_1, Argument_2, . . . , Argument_Last examples side = sqrt(area); cout << "2.5 to the power 3.0 is " << pow(2.5, 3.0);
  • 8. 8 Cont. #include <iostream> #include <string> using namespace std; int main() { string message = "Hello, World!"; int length = message.length(); cout << "Message: " << message << endl; cout << "Length of the message: " << length << endl; return 0; } boss to worker 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.
  • 9. 9 User-Defined functions  Standard function may not be enough to satisfy all users need  E.g, to find largest of two numbers  C++ provides its users with a way to define their own functions  Structure of user-defined function  Function prototyping  Function definition  Functions are invoked by function call  Its where execution of the function begins Function prototype Tells compiler argument type and return type of function • Format for function prototyping return-type function-name(argu-type1, argu- type2, ...); if function returns nothing, return type void For example int square(int); Function takes an int and returns an int int square(int a); Optional to specify parameters’ names
  • 10. 10 Function Definition  Format for function definition return-value-type function-name(parameter-list) { … declarations and statements }  Parameter-list (type par1, type par2, …)  Comma separated list of arguments  Data type needed for each argument  If no arguments, use void or leave blank Return-value-type Data type of result returned (use void if nothing returned) For example int square(int y) { return y * y; } return keyword Returns data, and control goes to function’s caller Function prototype must match function definition Function prototype int maximum(int, int, int); Function definition int maximum(int x, int y, int z) { … } Functions cannot be defined inside other functions
  • 11. 11 Function Calling  Declared functions are not executed immediately.  They are "saved for later use", and will be executed later, when they are called.  To call a function,  write the function's name  followed by two parentheses () and a semicolon ;  In the following example, myFunction() is used to print a text (the action), when it is called //Inside main, call myFunction(): // Create a function void myFunction() { cout << "I just got executed!"; } int main() { myFunction(); // call the function return 0; } // Outputs "I just got executed!"
  • 12. 12 Cont.  A function can be called multiple times: Example void myFunction() { cout << "I just got executed!n"; } int main() { myFunction(); myFunction(); myFunction(); return 0; } // I just got executed! // I just got executed! // I just got executed!
  • 13. 13 Function Declaration and Definition  A C++ function consist of two parts:  Declaration:  the return type,  the name of the function, and  parameters (if any)  Definition: the body of the function (code to be executed) void myFunction() { // declaration // the body of the function (definition) }
  • 14. 14 Cont.  Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will occur: Example int main() { myFunction(); return 0; } void myFunction() { cout << "I just got executed!"; } // Error  However, it is possible to separate the declaration and the definition of the function - for code optimization.  You will often see C++ programs that have function declaration above main(), and function definition below main().  This will make the code better organized and easier to read: Example // Function declaration void myFunction(); // The main method int main() { myFunction(); // call the function return 0; } // Function definition void myFunction() { cout << "I just got executed!"; }
  • 15. 15 C++ Function Parameters  Parameters and Arguments  Information can be passed to functions as a parameter. Parameters act as variables inside the function.  Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma: Syntax void functionName(parameter1, parameter2 , parameter3) { // code to be executed } • The following example has a function that takes a string called fname as parameter. • When the function is called, we pass along a first name, which is used inside the function to print the full name:
  • 16. 16 Cont. Example void myFunction(string fname) { cout << fname << " Refsnesn"; } int main() { myFunction("Liam"); myFunction("Jenny"); myFunction("Anja"); return 0; } // Liam Refsnes // Jenny Refsnes // Anja Refsnes When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
  • 17. 17 C++ Default Parameters Default Parameter Value  You can also use a default parameter value, by using the equals sign (=).  If we call the function without an argument, it uses the default value ("Norway"): Example void myFunction(string country = "Norway") { cout << country << "n"; } int main() { myFunction("Sweden"); myFunction("India"); myFunction(); myFunction("USA"); return 0; } // Sweden // India // Norway // USA A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.
  • 18. 18 C++ Multiple Parameters  Inside the function, you can add as many parameters as you want: Example void myFunction(string fname, int age) { cout << fname << " Refsnes. " << age << " years old. n"; } int main() { myFunction("Liam", 3); myFunction("Jenny", 14); myFunction("Anja", 30); return 0; } // Liam Refsnes. 3 years old. // Jenny Refsnes. 14 years old. // Anja Refsnes. 30 years old. Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
  • 19. 19 C++ The Return Keyword  The void keyword, used in the previous examples, indicates that the function should not return a value.  If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function: Example int myFunction(int x) { return 5 + x; } int main() { cout << myFunction(3); return 0; } // Outputs 8 (5 + 3) This example returns the sum of a function with two parameters: Example int myFunction(int x, int y ) { return x + y; } int main() { cout << myFunction(5, 3); return 0; } // Outputs 8 (5 + 3)
  • 20. 20 C++ Functions - Pass By Reference  In the examples from the previous page, we used normal variables when we passed parameters to a function.  You can also pass a reference to the function.  This can be useful when you need to change the value of the arguments: Example void swapNums(int &x, int &y) { int z = x; x = y; y = z; } int main() { int firstNum = 10; int secondNum = 20; cout << "Before swap: " << "n"; cout << firstNum << secondNum << "n"; // Call the function, which will change the values of firstNum and secondNum swapNums(firstNum, secondNum); cout << "After swap: " << "n"; cout << firstNum << secondNum << "n"; return 0; }
  • 21. 22 Example 2 //Function to add two numbers and return the sum #include<iostream> using namespace std; #include<math.h> int addition (int , int ); // function prototype int main ( ) { int a, b, c; cout<<"Enter the value of a and b? "; cin>>a>>b; c = addition (a, b); // function calling cout << "The sum is "<<c; } // function definition int addition (int x, int y) { int z; z= x + y; return (z); }
  • 22. 23 Example 3 // Function to find the square of an integers between 1 and 10 #include<iostream> using namespace std; #include<math.h> int square ( int ); // function prototype int main ( ) { for (int x = 1; x <= 10; x++) cout<<square (x)<<" "; // function call } int square ( int y ) // function definition { return y * y; }
  • 23. 24 Cont. Functions with empty parameter lists void or leave parameter list empty Indicates function takes no arguments For example void print(void); // or Optional to specify void in the parameter list void print( ); Function print takes no arguments and returns no value // Function with void return type and empty parameter list #include<iostream> using namespace std; void printmessage ( ); // function prototype int main ( ) { printmessage ( ); // function calling } void printmessage ( ) // function definition { cout << "I'm a function!"; }
  • 24. 25 Example 5 //Function taking parameter list but with no return type #include<iostream> using namespace std; void addition (int , int ); // function prototype int main ( ) { int a, b, c; cout<<"Enter the value of a and b? "; cin>>a>>b; addition (a, b); // function calling } // function definition void addition (int x, int y) { int z; z= x + y; cout << "The sum is "<<z; }
  • 25. 26 Scope of Variables  The scope of a variable defines where it can be accessed/referenced in a program  Local variables  All variables declared in the body of a function  Only accessed by the function declared it  All variables declared in main () are local variables  Global variables  Declared outside of all functions, before main ( )  Accessed by all functions, including main ( )
  • 26. 27 Example 6 // local variables #include<iostream> using namespace std; void update ( ); // function prototype int main ( ) { int x=5; // declare x local variable to main () cout<<"The value of x local in main () is: "<<x<<endl; update ( ); // function calling cout<<"nThe value of x local in main () is: "<<x<<endl; update ( ); // function calling } void update ( ) { // x is not declared in update (), can be accessed anywhere cout <<"The value of x on entering update () is: "<< x<<endl; x = x*10; cout <<"The value of x on exiting update () is: "<< x<<endl; }
  • 27. 28 Example 7 // global variables #include<iostream> using namespace std; void update ( ); // function prototype int x=5; // declare x as global variable int main ( ) { // x is not declared in main (), can be accessed anywhere cout<<"The value of x in main () is: "<<x; update ( ); // function calling cout<<"nThe value of x is: "<<x; } // update ( ) modifies global variable x during each call void update ( ) { // x is not declared in update (), can be accessed anywhere cout <<"The value of x on entering update () is: "<< x<<endl; x = x*10; cout <<"The value of x on exiting update () is: "<< x<<endl; }
  • 28. 29 Example 8 // local variable and global variable having the same name #include<iostream> void update ( ); // function prototype int x=5; // declare x as global variable int main ( ) { update ( ); // function calling } void update ( ) { int x=25; // declare x local variable to update () cout<<"The value of x is: "<<x<<endl; }
  • 29. 30 Scope Resolution Operator (: :) • When global variable have same name with local variable in function  By default, local variable accessed in function  Unary scope resolution operator (::)  Access global variable in function, if local variable has same name  Format ::variable_name;  For example  Cout<<::x;  y = ::x + 3;
  • 30. 31 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; }
  • 31. 32 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 0 Global variables are automatically initialized to 0
  • 32. 33 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 0 void main() { x = 4; fun(); cout << x << endl; } 1
  • 33. 34 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x ???? 3
  • 34. 35 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 3
  • 35. 36 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 4
  • 36. 37 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 5
  • 37. 38 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 6
  • 38. 39 Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } x 4 void main() { x = 4; fun(); cout << x << endl; } 7
  • 39. 40 Example 9 // Using the unary scope resolution operator #include<iostream.h> void update ( ); // function prototype int x=1; // declare x as global variable int main ( ) { int x=5; // declare x local variable to main () cout<<“ The value of local x is ”<<x; cout<<“ The value of global x is ”<<::x; // access global x in main () //update ( ); // function calling void update ( ) { int x=25; // declare x local variable to update () cout<<“The value of local x is ”<<x; cout<<“The value of global x is ”<<::x; // access global x in update () }
  • 40. 41 Storage Classes  Storage class determines the period during which a variable exists in memory  Automatic variables  Variable created when program enters its block  Variable destroyed when program leaves block  For example  By default, local variables of functions  keyword auto explicitly declares automatic  auto int x; Static variables Created at which the program begins execution Initialized once, when declared Existed for the duration of the program execution For example By default, global variables are static Local variables declared with keyword static static int x=20; Retains its value between function calls Reference to variable is local in the function
  • 41. 42 Passing Arguments to Function  There are two ways to pass arguments to function  Passing by value  Copies of argument value passed to function parameters  Changes made to the function parameters have no effect on the values of arguments  Prevent unwanted side effects  Passing by reference  Copies of argument address passed to function parameters  Any changes made to the function parameters affects or modify the values of arguments
  • 42. 43 Example 1 // Passing arguments by value to function #include<iostream> using namespace std; int squareByValue (int ); // function prototype int main ( ) { int x = 2; cout<<"x before squareByValue (): "<<x<<endl; cout<<"Value returned by squareByValue (): "<<squareByValue (x); cout <<"nx after squareByValue (): "<<x; } int squareByValue( int number ) { number = number * number; return number; }
  • 43. 44 Cont’d…  There are two ways to pass arguments by reference  Pass by reference with reference arguments  Pass by reference with pointer arguments  To pass by reference with reference arguments  Reference variable is used in function parameter  Alias for argument in function call  Passes parameter by reference  Use & after data type in prototype  void myFunction(int &data);  Read “data is a reference to an int”  Function call format is the same Reference variable Alias for another variable Contains the address of a variable (like a pointer) A pointer constant, de-referenced implicitly Must be initialized when it is declared Format to create a reference variable type &reference-name = referrer-name; & indicates reference variable Reference variable refer to variable of same type Can be used within a function
  • 44. 45 Cont’d…  For example  int x=5; //declare x as integer variable  int &y=x; //create y as an alias for x  cout<<x;  cout<<y;  Both output 5  int x=5;  int &y; // error  y=x;  Must be initialized when it is declared
  • 45. 46 Example 2 // References must be initialized when declared #include<iostream.h> int main ( ) { int x = 3; int &y = x; // y refers to (is an alias for) x cout<<"x = "<< x <<endl; cout<<"y = "<< y <<endl; y = 7; cout<<"nx = "<<x<<endl; cout<<"y = "<<y<<endl; }
  • 46. 47 Example 3 // Pass argument by reference with reference argument #include<iostream> using namespace std; void squareByReference( int & ); // function prototype int main ( ) { int z = 4; cout<<"z before squareByReference (): "<<z << endl; squareByReference (z); cout <<"z after squareByReference (): "<<z; } void squareByReference( int &numberRef ) { numberRef = numberRef *numberRef; }
  • 47. 48 Cont’d…  To pass by reference with pointer arguments  Pointer variable is used in function parameter  Use * after data type in prototype  void myFunction(int *data);  & used to pass address of argument in fun. calling  myFunction(&value);  Arrays not passed with &  Because array name is already a pointer
  • 48. 49 Example 4 // Pass argument by reference with pointer argument #include<iostream.h> void cubeByReference ( int * ); // function prototype void main ( ) { int number = 5; cout<<"The original value of number is "<< number; // pass address of number to cubeByReference cubeByReference (&number ); cout << "nThe new value of number is " << number << endl; } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; }
  • 49. 50 Passing Array to Function  Specify name without brackets  To pass array myArray to myFunction  int myArray[24];  myFunction(myArray,24);  Array size usually passed, but not required  Useful to iterate over all elements  Arrays passed by reference  Functions can modify original array data  Value of name of array is address of first element  Function knows where the array is stored  Individual array elements passed by value  Like regular variables  square(myArray[3]);  Functions taking arrays  Function prototype for 1D array  void modifyArray(int [], int);  No need for array size between brackets  Ignored by compiler
  • 50. 51 Cont’d…  If declare array parameter as const  Cannot be modified (compiler error)  void doNotModify(const int []);  Function prototypes for 2D arrays  Must specify sizes of subscripts  First subscript not necessary, as with single-scripted arrays  void printArray(int[][3]); //passing array to function #include<iostream> void printarray (int [ ], int ) ; // function prototype void main ( ) { int firstarray [ ] = {5, 10, 15}; int secondarray [ ] = {2, 4, 6, 8, 10}; printarray (firstarray, 3); // function calling printarray (secondarray, 5); } // function definition void printarray (int array [ ], int size) { for (int i=0; i<size; i++) cout<<array [i]<<" "; cout << "n"; }
  • 51. 52 Example 6 // Effects of passing entire array by reference #include<iostream.h> void modifyArray ( int [ ], int ); void main ( ) { const int arraySize = 5; int a [arraySize]= { 0, 1, 2, 3, 4 }; cout <<"Effects of passing entire array by reference"<<endl; cout<<"nThe values of a before modifyArray (): "; // output original array for (int i = 0; i < arraySize; i++ ) cout <<a[ i ]<<" "; // pass array a to modifyArray by reference modifyArray (a, arraySize ); cout<<"nnThe values of a after modifyArray (): "; // output modified array for ( int j = 0; j< arraySize; j++ ) cout<<a[j]<<" "; } // in function modifyArray, "b" points to the original array "a" in memory void modifyArray( int b[ ], int sizeOfArray) { for ( int k = 0; k < sizeOfArray; k++ ) b[k] = b[k] * 2; }
  • 52. 53 Example 7 // Effects of passing individual array element by value #include<iostream.h> void modifyElement( int ); void main ( ) { const int arraySize = 5; int a [arraySize]= { 0, 1, 2, 3, 4 }; cout<<"Effects of passing individual array element by value "<<endl; cout<<"nThe value of a[3] before modifyElement (): "<<a[3]<<endl; // pass array element a[3] by value modifyElement (a[3]); // output value of a[ 3 ] cout<<" nThe value of a[3] after modifyElement (): "<<a[3]; } // in function modifyElement, "e" is a local copy of array element a[ 3 ] passed from main void modifyElement( int e ) { e = e * 2 ; cout <<"nValue in modifyElement is: "<<e<<endl; }
  • 53. 54 Example 8 // passing multidimensional arrays to function by reference #include <iostream.h> void printArray (int [ ] [3]); // function prototype void main ( ) { int array1 [2][3] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2 [2][3] = { 1, 2, 3, 4, 5 }; cout<<"Values in array1 by row are:"<<endl; printArray (array1); cout<<"nValues in array2 by row are:"<<endl; printArray (array2 ); } // function to output array with two rows and three columns void printArray (int a[ ][3]) { for (int i = 0; i < 2; i++ ) { for (int j = 0; j < 3; j++ ) // output column values cout<<a[ i ][ j ]<<" "; cout<<endl; } }
  • 54. 55 Recursive Functions  Recursive functions  Functions that call themselves  Can only solve a base case  If not base case  Break problem into smaller problem(s)  Launch new copy of function to work on the smaller problem (recursive call/recursive step)  Slowly converges towards base case  Function makes call to itself inside the return statement  Eventually base case gets solved  Answer works way back up, solves entire problem
  • 55. 56 Cont’d…  For example, factorial of an integer n  n! = n * (n – 1) * (n – 2) * … * 1  Recursive relationship, n! = n * (n – 1)!  5! = 5 * 4!  4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1  Base case, 1! = 0! = 1
  • 56. 57 Example 11 // Using recursive function to find the factorial of an integer #include<iostream.h> long factorial ( long ); void main ( ) { long number; cout<<"Enter a number: "; cin>>number; cout<<number << "! = "<<factorial (number); } long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); }
  • 57. 58 Inline Function  Each time a function called, the compiler must do the followings:  Remember where to return when the function eventually ends  Provide memory for the function’s variables  Provide memory for any value returned by the function  Pass control to from function calling to the function called  Pass control back to the calling function  This extra activity constitutes the overhead, or cost of doing business, involved in calling a function
  • 58. 59 Cont’d…  Inline function  Keyword inline before function  Asks the compiler to copy code into program instead of making function call  Appropriate argument substitutions made  Reduce function call overhead  Good for small, often-used functions  Appears prior to the main(), which calls it Any inline function must precede any function that calls it, which eliminates the need for prototyping in the calling function For example inline double cube(double s) { return s * s * s; }
  • 59. 60 Example 12 // Using inline function to calculate the volume of a cube #include<iostream.h> inline double cube (double side ) { return (side * side * side); } void main ( ) { double sideValue; cout <<"Enter the side length of your cube: "; cin>>sideValue; cout <<"Volume of cube is "<<cube (sideValue ); }
  • 60. 61 Overloaded Functions  Function overloading  Functions having same name, but with different set of parameters (type, number, and order)  For example  Function to square ints and function to square floats  int square(int x) { return x * x; } float square(float x) { return x * x; } • Compiler selects proper function to execute based on number, types and order of arguments in the function call. • Commonly used to create several functions of the same name that perform similar tasks, but on different data types. • Function can not be overloaded by its return type
  • 61. 62 Example 12 // using overloaded functions #include<iostream.h> int square ( int x ); double square ( double y ); void main ( ) { int x; x= square (7); // calls int version of square double y; y = square(7.5 ); // calls double version of square cout <<"nThe square of integer 7 is "<<x<<endl; cout<< "nThe square of double 7.5 is "<<y; } // function square for int values int square ( int x ) { cout <<"Called square with int argument: "<<x<<endl; return x * x; } // function square for double values double square( double y ) { cout <<"Called square with double argument: "<<y <<endl; return y * y; }
  • 62. 63 Building User-defined Libraries • It is a good practice to group related functions into separate files, & build your own libraries  W/c can be then included in many files  To build user-defined libraries,  How to create header files to store function prototype  How to create implementation files to store function definition, and link with the header file  How to include the header file to your program to use your user-defined functions
  • 63. 64 How to Create Header Files  The C++ header files must have name with .h extension  Like string.h, math.h,… etc  The contents of header file should have ff structure:  #ifndef compiler directive  #define compiler directive  May include some other header files  All functions prototype with some comments  Definitions of data types and constants  #endif compiler directive
  • 64. 65 Cont’d…  The header file is usually expected to reside in the same folder as the program file, otherwise  A full or relative path to it should be specified  By default, all C++ standard header files are located in the C:TCWIN45INCLUDE folder  To include header files in your program file  Standard library header files  #include<math.h>  User-defined header files  #include "myheader.h"
  • 65. 66 Create taxrules.h Header File #ifndef _TAXRULES_ #define _TAXRULES_ #include "taxrules.cpp" double getIncome(char [ ]); // purpose -- to get the employee income // input -- a string prompt to be displayed to the user // output -- a double value representing the income
  • 66. 67 Cont’d… double computeTaxes(double); // purpose -- to compute the taxes for a given income // input -- a double value representing the income // output -- a double value representing the taxes void printTaxes(double); // purpose -- to display taxes to the user // input -- a double value representing the taxes // output -- None #endif
  • 67. 68 Create taxrules.cpp Implementation File #include <iostream.h> #include "taxrules.h " double computeTaxes(double income) { if (income<5000) return 0.0; else return 0.07*(income-5000.0); } double getIncome(char prompt [ ]) { cout<<prompt; double income; cin>>income; return income; } void printTaxes(double taxes) { cout<<"The taxes is $"<<taxes<<endl; }
  • 68. 69 Include taxrules.h in Program File #include<iostream.h> #include "taxrules.h" void main ( ) { // get the income double income; income = getIncome ("Please enter the employee income: "); // compute taxes double taxes = computeTaxes(income); // print employee taxes printTaxes(taxes); }
  • 69. 70 Worksheet  What is the drawbacks of procedure-oriented programming?  Write a program that generate random number using rand()?  Write a program to find the Fibonacci Series of a given number using recursive function?

Editor's Notes

  • #55: It is useful for many tasks, like sorting or calculate the factorial of numbers.