0% found this document useful (0 votes)
3 views22 pages

Chapter 5

This chapter discusses functions in C++, defining them as blocks of code that perform specific tasks and return values. It explains the importance of functions for modular programming, software reusability, and ease of maintenance, along with the syntax for function declaration, definition, and calling. Additionally, it covers data transfer protocols between functions, including communication with and without data transfer, and the various methods for parameter passing.
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)
3 views22 pages

Chapter 5

This chapter discusses functions in C++, defining them as blocks of code that perform specific tasks and return values. It explains the importance of functions for modular programming, software reusability, and ease of maintenance, along with the syntax for function declaration, definition, and calling. Additionally, it covers data transfer protocols between functions, including communication with and without data transfer, and the various methods for parameter passing.
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

CHAPTER FOUR

FUNCTIONS
What is function?
Function is group of program statements that can act on data and return a value.
It is a block of instructions that is executed when it is called from some other point of the program.
Every C++ program has at least one function, main ().
When your program starts, main () is called automatically. main ( ) might call other functions, some of which
might call still others.

Why we use functions?


• Is used to write programs in a more modular way
• Small functions promote software reusability
• Programs should be written as collections of small functions
• This makes the programs easier to
– write
– Debug
– Maintain and
– modify

• The following is its format:


type name ( argument1, argument2, ...) statement
• or

type name ( argument1, argument2, ...)


{
statement1
Statement2

}

• Where
– type is the type of data returned by the function
– name is the name by which it will be possible to call the function
– arguments (as many as wanted can be specified)
• Each argument consists of a type of data followed by its identifier like in a variable declaration
(for example, int x)
• The arguments act within the function like any other variables
• They allow passing parameters to the function when it is called
• The different parameters are separated by commas.
– statement is the function's body
• It can be a single instruction or
• a block of instructions in this case it must be delimited by a curly brackets{}

Function Declaration / Prototype Declaration

• As you can’t use variables before declarations (telling the compiler what the variable is),
you can’t use function before telling the compiler what this function is.
• The common approach to declare functions is at the beginning of the program.
The function declaration (function prototype) tells the compiler that later on in the program a function introduced
in the declaration is going to be used.

1
Example
void getnumber( ); this is a function declaration.
Void shows that the function doesn’t have a return type.
Function declaration is terminated with semicolon.
If the function has arguments, then they should be indicated in the declaration.

Function Definition

A function definition consists of two parts: interface and body.


The interface of a function (also called its prototype) specifies how it may be used. It consists of three entities:

• The function name. This is simply a unique identifier.


• The function parameters (also called its signature). This is a set of zero or more typed
identifiers used for passing values to and from the function.
• The function return type. This specifies the type of value the function returns.

A function which returns nothing should have the return type void.
The body of a function contains the computational steps (statements) that contain the function.

Example
void getnumber ( ) function header
{
int x;
cout<< “Enter Number \n”; function body function body
cin>>number;
cout<<”The number you enterd is:”<<number;
}

The function body is placed in one place in memory. But it could be invoked in several places in the program.

Calling functions
Calling functions is invoking it to execute.
The function call involves the function name, followed by parentheses.
The function call is similar to its declaration except that the return type is not mentioned.
The call is terminated by semi colon.
Executing the call statement causes the function to execute, i.e. control is transferred to the function, the statements in the
function definition are executed and then control returns to the statement following the function call.

// the following program demonstrates what we have discussed so far


#include<iostream.h>
#include<conio.h>
void add ( );//function declaretion
void sub ( );//function declaration
void main ()
{ char ch;
cout <<" what do you want ? A: Add, S: subtract \n";
cin>>ch;
switch(ch)
{
case 'A': // A for addition
add ( ) ;//function calling
break;//function calling
2
case 'S' : // S for subtraction
sub ( );
break;
}
}

void add()
{
int a,b,c;
cout<<"enter two numbers \n";
cin>> a>>b; function body or function definition.
c = a + b;
cout <<" the sum is \t "<< c;
}
void sub ( )
{
int a,b,c;
cout<<"Enter two numbers \n";
cin>>a>>b; function body
cout<<"the difference is \t "<<a-b;
}

A Simple Function

The example below shows the definition of a simple function which raises an integer to the
power of another, positive integer.

• The function interface starts with the return type of the function (int in this case).
• The function name appears next followed by its parameter list.
Power has two parameters (base and exponent) which are of types int and unsigned int,
respectively
• Note that the syntax for parameters is similar to the syntax for defining variables: type identifier followed by the
parameter name.
• However, it is not possible to follow a type identifier with multiple comma-separated parameters:

int Power (int base, exponent) // Wrong!

The for-loop raises base to the power of exponent and stores the outcome in [Link], the function returns
result as the return value of the function.
Below, example 2 illustrates how this function is called. The effect of this call is that first the argument values 2 and 8 are,
respectively, assigned to the parameters base and exponent, and then the function body is evaluated.

Example 2:
3
When run, this program will produce the following output:
2 ^ 8 = 256

In general, a function should be declared before its is used.

Example3:

scope of identifiers
Scope: - the scope of identifies is the part of the program in which it is known (for which the compiler
doesn’t say “undefined symbol”).

In a modular working environment there are four scopes


Program/File scopes: An identifier declared outside any function is said to have a file scope.
Global variables and function identifiers are said to have file scope.
Function (Module) scopes: Labels (identifiers followed by a colon) are the only identifiers with function scope.
Labels can be used anywhere in the function in which they appear, but cannot be referenced outside the function body.
Block scopes: Identifiers declared inside a block are said to have a block scope.
Function prototype scopes: The identifiers in the parameter list of a function-prototype are said to have a function
prototype scope.

Structure of scopes
It’s not visible it’s something virtual (in c++)
Note:
• There can only be one program scope
• The program must exist before a fn is created
4
• Cannot put a function within a function (in c++) structure of functions is linear
• Cannot put block on top of the program it’s a allowed only within function.
• Blocks within blocks are allowed. Function and fn. prototype have names from the four scopes

Scope Rules
Rule 1: an identifier is known only within the scope in which it is declared;
and starting from its point of declaration down to the end of the scope.
Does this rule hold for labels whose scope is a function scope?
Rule 2: If an identifier is re-declared within a nested scope, it is the inner declaration that takes precedence
over the outer one.

Eg:
int fact (int n) int x=8; //outer x
{ int compute(int a, int b);
int i, p=f1; void main ( )
for (i=1, i<=n; i++) {
int x=4, y=3; //inner x
p = p * i;
x=y + compute (x, y);//3+(4*3)=12
return p; cout<<x; //and then the outer x
} } which is 8 so 12+3+8=23
void main ( )
{ int compute (int c, int d ) //output
int m,f; { // 23
cout<<”Enter a number:”; int m;
cin>>m;
f=fact (m); m=c*d; //3*4=12 8 x
cout<<”factorial”<<f; x=x+m;//8+12
return x; y 3
}
}

The scope of a variable identifier tells where we can access it,


but it doesn’t tell us exactly the visibility of an identifier.
The visibility of an identifier is within the scope of the identifier but starting from the point of declaration to the end of
the scope.

When a function calls itself, we call it recursion. A recursive function is a self-serving function.
When we are using identifiers we analyze the following:
Identifying the structure of the scope
Which identifier belongs to a given scope?
Determining the scope
Are we using the identifier within its scope?

Inter module communication (IMC)

Function = process + communication

Two types of communication


- communication with data Transfer
o calling
o data transfer
- communication without data transfer
o calling
eg void stpdfn ( )
{
cout << “hell word “;
5
}
Communication with data transfer
Three set of rules of communication
There are three different data transfer protocols(rules) based on the direction of the flow (transfer) of data.
Protocol 1(P1): It is a protocol in which data is transferred from the calling to called (calling called).
It is a one way channel in which the called doesn’t transfer data to the calling.
Protocol 2(P2): It is a protocol from the called to the calling (calling called).
This is also a one way channel in which the calling doesn’t transfer data to the calling.
Protocol 3(P3): It is a protocol both from the calling to the called and from the called back to the calling
(calling called). It is a two way channel in which data security is the least.

Data Transfer Tools in C++


Three tools of communication (Data transfer)
T1: Communication using common variables
T2: Communication using the return statement (i.e Function identifier)
T3: Communication using parameter passing

A. Data Transfer using common variables (T1 in c++)


Two modules can communicate each other through variables, if the variable is accessible to both of the modules, i.e if it is
a commonly accessible memory space. A variable declared as a global variable and that is not declared any where is a
common variable to all other constituting scopes. Potentially, common variables support P3. Practically, a programmer
could use common variables to transfer data from the calling to the called, or from called to the calling or both ways.

M1 M2

Commonly accessible memory space


According to p3 According to p2 According to p1
M1 writes M1 calls m2 M1 writes
M1 calls M2 M2 writes M1 calls M2
M2 reads [m2 dies] M1 reads (But no protection) M2 reads (But no protection)
M1 reads

Eg
int n, p;
void fact ( ) void main ( )
{ {
int i; cout << “enter a natural no”;
p=1; cin >> n; //main writes to n
for ( i = 1; j <= n; i ++)//fact reads n fact ( ); //main calls fact
p = p * i; //fact writes to p cout <<p; //main reads p
} }

________________________________________________________________________________________________
int n; for (i =1; i < = n; i ++)
int fact() p= p * i;
{ return p;
int I, p = 1; }
6
void main ( ) cin >> n;
{ f= fact ( );
int f; cout <<” factorial is ‘’ << f;
cout <<”Enter natural no:”; }

_______________________________________________________________________________________________
int n;
void fact ( )
{
int i, p =1; int i;
for (i= 1; i<= n; i ++) for(i-n-1; i>=; i--)
p= p * i; n = n*i;
n = p;
}
void main ( )
{
cout <<”Enter a natural no”;
cin >> n;
fact ( );
cout <<” factorial is” << n;
}
Note: Loading a variable with two information is obscure.

T1
Possibility Protection
P1 X
P2 X
P3

Note: T1Supports P3

int n;
void fact ( )
{
int i , p = 1;
for (i; =1; i<=n; i++)
p = p* i;
n=p;

}
void main ( )
{
int m;
cout << “enter a natural no’’;
cin >>n;
m=n;
fact ( );
cout <<”the factorial of “<<” is”<< n;
}
Common variables (Global variables)
Inhibits the independency & insulation of functions from each other.
Minizes security.
Frustrating for error tracking
Useful in creating variables & named constants that must be shared
B. Data Transfer through the return statement (T2 in c++)

7
The function identifier acts like a variable to transfer data from the called to the calling only
(if the return type is not a pointer or a reference).
It is a means of returning only one value to the calling function.
Simple types, pointers, struct & Unions are valid return types.

Returning a single value


The called function must provide
• The data type of the returned value
• The actual value being returned

To return a single value it appropriate for a function to use the return statement.
Syntax:
Return <expression>;

When the return statement is encountered


• The expression is evaluated first
• The evaluated value of the expression is then automatically converted to the <returnType>

Failure to match the data type of the return value exactly with the function’s declared data type may not result in an error
when your program is compiled, but it may lead to undesired result, b/c the return value is always converted to the
appropriate type before being sent to the calling function.

Functions can return references, but this can be dangerous.


When returning a reference to a variable decaled in the called function,
the variable should be declared static within that function. Why?
Returning a pointer or a reference to an automatic variable in a called function is a logical error. … results dangling
references . . .

Valid data types of a function’s return value


• Simple (predefined): int, double, char….
• Compound type: int &, double*
• User defined type: Enumeration, class, ….

- the function identifier has two jobs in T2


It is not only used for calling but also for transferring data.
- it is not only using for calling like everywhere else but also for transferring data
- The function identifier acts like variable identifier
- The function identifier is typed ( non – void)
- [conventionally] the memory space reserved for function identifier is read only (RO) accessible for all other
modules except itself ( read & write for itself)
- The only protocol supported by T2 is p2

eg
int n; // p1/ T1
int fact ( )
{ fact()
int i,j, p=1;
for (i = 1; i < = n; i++)
p=p*i;
return p; T1/P1 P2/T2
}
void main()
{ main()
inf f;

8
cout << “enter a natural no’’;
cin>>n;
f = fact ( );
cout < <” factorial of n:” < < ‘’ is” < < f;
}

C. Data Transfer through Parameter (Argument) Passing (T3 in C++)


Argument passing is the process of initializing the storage of a function parameters
with the values of the function call arguments.
Parameter passing can be either by value or by reference.
1. Parameter Passing by value:
It is a passing mechanism in which the copy of the values contained in the arguments of the calling
function are assigned in the corresponding parameters of the called function.
This parameter passing doesn’t have access to the variables used as arguments by the calling function and hence
can’t alter the value stored in one of these variables. P1 is the transfer protocol supported.
Eg. int fact(int n)
{
int i, p=1;
for(i=1; i<=n; i++)
p=p*i;
return p;
}
void main()
{
int n;
cout << “enter a natural no’’;
cin>>n;
cout<<”The fact of ”<<n<<” is”<<fact(n);
}
Note:
Parameter passing by value:
Allows function to be written as independent entities.
Alleviates the concern of altering argument variables.
Parameters can be considered as (in both by value & reference cases)
• Initialized variables, or Variables that will be assigned values when the function is invoked.
The default parameter passing
Could be dis-advantageous if a large data item is being passed, b/c coping that data can take considerable amount
of execution time. In such cases a call by reference is good for efficient performance (both in space & time).
2. Parameter Passing by reference:
It is a means of communication in which the function is allowed to have a direct access (use & change) to the values
of the variables (arguments) defined in the calling function.
C++ provides two ways of parameter passing by reference:
i. Parameter passing with pointer arguments:
Pointers can be used to modify one or more variables in the caller. Pointers and the indirection operator are
used to simulate call with arguments. In this parameter passing mechanism, the address of the arguments is
passed to the parameters of the called function.
Eg.
void fact(int n, int *p)
{
int i;
for(i=1; i<=n; i++)
*p = (*p) * i;
}
void main()
{
int n, p=1;
9
cin>>n;
fact(n, &p);
cout<<”The factorial of “<<n<<” is”<<p;
}
ii. Parameter Passing with reference arguments:
A reference parameter is an alias(assumed name) for its corresponding argument. The ampersand (&) is used
to indicate that the function parameter is passed by reference.

Eg.
void fact(int n, int &p)
{
int i;
for(i=1; i<=n; i++)
p = p * i;
}
void main()
{
int n, p=1;
cout << “enter a natural no’’;
cin>>n;
fact(n, p);
cout<<”The factorial of “<<n<<” is”<<p;
}

#include <iostream.h>
void Foo (int& num);
int main (void)
{
int x = 10; output
Foo(x); x=0
cout << "x = " << x << '\n'; num=0
return 0; //the value in
} //name of num to x
void Foo (int& num)
0
{ num
num = 0;
cout << "num = " << num << '\n' ; x
10
}

10
Note:
Parameter passing by reference
- Allows the called function to have direct access (use & change) the values of the
variables defined in the calling function
- The address of the variable has to be passed to the called function.
- C++ provides two types of address parameters: references & pointers.
- Structures are always passed call-by-value: a copy of the entire structure is passed. But,
to get the performance of a call-by-reference and the protection of call-by-value, we can
use a pointer to a constant data (or a reference to a constant data).
- It is an appropriate parameter passing, when we need to return (to the calling function)
multiple values.
- To specify a reference to a constant, place the ‘const’ qualifier before the type specifier.
- Reference variables must be initialized in their declaration.
- Reference variables can’t be reassigned as aliases to other variables.
Example:
Write a modular program, that can accept a list of integers and displays the average of the
list of items. (Do not use global variables and return statements as a means of data transfer
mechanism)

U InputData

E main average
R

void inputData(int list[], int size){


cout<<”Enter the size of the list”;
cin>>size;
cout<<”Enter the data one by one”;
for(int i=0; i<size; i++)
cin>>list[i];
}
void average(const int list[], int s, int &avg){
int sum = 0;
for(int i = 0; i<s; i++)
sum = sum + list[i];
avg = (float)sum/s;
}
void main(){
int lst[100], s;
float avg;
InputData(lst, s);
average(lst, s, avg);
cout<<”The average of the list is :”<<avg;
}

11
Function Overloading.
What is function overloading?
• Defining multiple functions with the same name is said to be function overloading.
• Two different functions can have the same name if the prototypes of their arguments are different.
• This means that you can give the same name to more than one function if they have either a
different number of arguments or different data types in their arguments.
Example:
void f(int i)
void (float f)
void f(int i,float f)
How C++ manages function overloading?
Name decoration (name managing) is a technique used to solve various problems caused by the
need to resolve unique names for programming entities in many modern programming languages like
C++,java…
Original function name decorated function name
void f(int i) ?f@@YAXH@Z(int i)
void f(float f) ?f@@YAXM@Z(float f)
void f(int i,float f) ?f@@YAXHM@Z(int i,float f)

YAXH,YAXM,YAXHM.
Example
# include<iostream.h>
int devide (int a, int b=2);
int devide(int z, int r, int y);
float devide (float a, float b);

int main()
{
int x=20, y=2;
float n=5.0, m=2.0;
cout<<devide(x,y);
cout<<endl;
cout<<devide(n,m);
cout<<endl;
cout<<devide(n,m,m);
cout<<endl;
return 0;
}
int devide (int a, int b)
{
return a/b;
}
int devide (int a, int b, int c)
{
int w=a/b
return w/c;
}
float devide (float x, float y)
{
return x/y;}

12
In this case we have defined two functions with the same name, but one of them accept two
arguments of type int and the other accepts them of type float the compiler knows which one to
call in each case by examining the type when the function is called.
If it is called with two ints as an argument it calls to the function that has two int arguments in
the prototype
if it is called with two floats it will call to the one which has two floats in its prototype.
For simplicity I have included the same code with both functions, but this is not compulsory.
You can make two functions with the same name but with completely different behavior.

Default arguments
What is Default argument in C++?
Function has argument when it is declared but called without it’s arguments.
In this case all the default arguments will substitute the missed arguments.
The default arguments should be indicated in the function declaration.

If one argument is missed when a function is called, then it is assumed to be the last argument,
it is impossible to leave arguments in the middle. //int add(int x,int y,int z) when it is called
add(a,b) y can’t be left .
In general the missed argument is assumed to be the last arguments. If there are two missed
arguments, then they are last two arguments. int add(int x,int y,int z,int k) when it is called
add(a,b) //the default arguments are the last two.

The following program demonstrates this.


#include<iostream.h>
#include<conio.h>
void nat(int i=1,int j=10);
void main ( )
{
nat ( ); // In the first call to “nat( )” the first 10 natural numbers are displayed cause the cause the 2nd argument j is 10.
nat (5); // In the second call to “nat( )” the natural numbers from 5 to 10 are displayed, since it is assumed that the missed
// argument is the last argument.
nat (1,15);// And in the third call the first 15 natural numbers are displayed. Default arguments make the program more flexible.
getch();
}
void nat (int a, int b)
{
for (int k =a; k<=b; k++)
cout <<k;
cout<<endl;
}

13
Inline Functions
What is an inline functions?
A type of function whose code gets inserted ,instead of jump to the function at the place where
there is a function call is known as an inline function.
Syntax:
inline type name ( )

inline int Abs (int n)


{
return n > 0 ? n : -n;
}
The effect of this is that when Abs is called, the compiler, instead of generating code to call
Abs, expands and substitutes the body of Abs in place of the call.
While essentially the same computation is performed, no function call is involved and hence no
stack frame is allocated.
Because calls to an inline function are expanded, no trace of the function itself will be left in the
compiled code. Therefore, if a function is defined inline in one file, it may not be available to
other files. Consequently, inline functions are commonly placed in header files so that they can
be shared.
Like the register keyword, inline is a hint which the compiler is not obliged to observe.
Generally, the use of inline should be restricted to simple, frequently used functions.
A function which contains anything more than a couple of statements is unlikely to be a good
candidate. Use of inline for excessively long and complex functions is almost certainly ignored
by the compiler.
Example
# include<iostream.h>
inline int Abs (int n)
{
return (n > 0 ? n : -n);
}

int main()
{
int n= -3, m=4;
cout<<Abs(n);
cout<<Abs(m);
}
Recursion function
A function which calls itself is said to be recursive.
Take the factorial problem, for instance, which is defined as:
• Factorial of 0 is 1.
• Factorial of a positive number n is n times the factorial of n-1.
The second line clearly indicates that factorial is defined in terms of itself and hence can be expressed as a
recursive function:

int Factorial (unsigned int n)


{

14
return n == 0 ? 1 : n * Factorial(n-1);
}

For n set to 3, the table below provides a trace of the calls to Factorial.
The stack frames for these calls appear sequentially on the runtime stack, one after the other.

A recursive function must have at least one termination condition which can be satisfied.
Otherwise, the function will call itself indefinitely until the runtime stack overflows.
The Factorial function, for example, has the termination condition n==0 which, when satisfied,
causes the recursive calls to fold back. (Note that for a negative n this condition will never be
satisfied and Factorial will fail).

As a general rule, all recursive functions can be rewritten using iteration. In situations where the
number of stack frames involved may be quite large, the iterative version is preferred. In other
cases, the elegance and simplicity of the recursive version may give it the [Link] factorial, for
example, a very large argument will lead to as many stack frames. An iterative version is
therefore preferred in this case:

# include<iostream.h>
int Factorial (unsigned int n);
int main()
{
int n;
cout<<"Enter a +ve number";
cin>>n;
cout<<"!"<<n<<"=:"<<Factorial(n);
return 0;
}
int Factorial (unsigned int n)
{
if (n = = 0)
return 1;
else
return (n*(factorial(n-1));
}

15
End of function.

Exercises

1. Write appropriate calls for the following functions to accomplish the specified task.

float add ( float , float ); // returns the sum of two numbers


float subtract ( float , float ); // returns the deference of two
numbers
void display ( float ); // displays a number on the screen

Tasks:
i) add 12.5 and 3
ii) display the result of 23.5 – 12 + 34,5
iii) display the result of 23 + 12.9 + 99 + 10.5
iv) display the sum of all numbers stored in an array

1. Rewrite the following program using different functions. All inter-modular


communication is to be done using only the return statement (No Global variables).
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

int key,input,nTrial=0,score;

void main()
{
clrscr();

randomize();
key=random(10)+1;
cout<<key<<endl;

do{
cout<<"\nMake your guess : ";
cin>>input;
nTrial++;

if(input==key)
{
cout<<"\nCorrect \n";
switch(nTrial)
{
case 1: score = 10; break;
case 2: score = 7; break;
case 3: score = 3; break;
}

16
}
else
cout<<"\nNot correct";

}while( nTrial<3 && input!=key );

cout<<"\nSCORE = "<<score<<endl;

getch();
}

1. Given the following definition of a Swap function


void Swap (int x, int y)
{
int temp = x;
x = y;
y = temp;
}
what will be the value of x and y after the following call:
x = 10;
y = 20;
Swap(x, y);

2. What will the following program output when executed?


#include <iostream.h>
int str = 15;
void Print (int str)
{
cout << str << '\n';
cout << ::str << '\n';
}
int main (void)
{
Print(50);
return 0;
}
3. Write a function which outputs all the prime numbers between 2 and a given
positive integer n:

void Primes (unsigned int n);


A number is prime if it is only divisible by itself and 1.

4. Define an enumeration called Month for the months of the year and use it to define a function which
takes a month as argument and returns it as a constant string.

5. Define an inline function called IsAlpha which returns nonzero when its argument is a letter, and
zero otherwise.

6. Write a function which draws a line of n asterisks, n being passed as a parameter to the function.
Write a driver program (a program that calls and tests the function) which uses the function to output
an mxn block of asterisks, m and n entered by the user.

17
7. Write a function which converts a sum of money given as an integer number of pence into a floating
point value representing the equivalent number of pounds. For example 365 pence would be 3.65
pounds.

8. Define a recursive version of the Power function

9. Define a recursive function for a Fibonacci series

10. # include<iostream.h>
void sum( int a, int b);
void main()
{
int x,y;
cin>>x>>y;
sum(x,y);
}
void sum ( int a, int b)
{
int sum=a+b;
cout<<"the sum="<<sum;
}
10.1 modify the function definition and the declaration of “sum()” in the above
problem if the main function is changed to

void main()
{
sum();
}
10.2 modify the main () function above if the in the above problem if the sum () is
modified as follow
float sum( float a, int b)
{
return (a+b);
}

18
// passing parameters by reference x=2, y=6, z=14
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int&


c)
{
a*=2;
b*=2;
c*=2;
}

int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y <<
", z=" << z;
return 0;
}

To explain it in another way, we associate a, b


// declaring functions prototypes Type a number (0 to exit): 9
#include <iostream> Number is odd.
using namespace std; Type a number (0 to exit): 6
Number is even.
void odd (int a); Type a number (0 to exit): 1030
void even (int a); Number is even.
Type a number (0 to exit): 0
int main () Number is even.
{
int i;
do {
cout << "Type a number (0 to
exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}

void odd (int a)


{
if ((a%2)!=0) cout << "Number is
odd.\n";
else even (a);
}

void even (int a)


{
if ((a%2)==0) cout << "Number is
even.\n";

19
else odd (a);
}

This illustrates the technique used to pass arguments by value to a function.

#include <iostream>
#include <string>
using namespace std;

string GetName()
{
string FirstName, LastName, FN;

cout << "Employee's First Name: ";


cin >> FirstName;
cout << "Employee's Last Name: ";
cin >> LastName;

FN = FirstName + " " + LastName;

return FN;
}

int main()
{
string FullName;
double Hours;

double GetHours(string FullName);

FullName = GetName();

Hours = GetHours(FullName);

cout << "\nEmployee's Name: " << FullName;


cout << "\nWeekly Hours: " << Hours << " hours\n\n";

return 0;
}

double GetHours(string FullName)


{
double Mon, Tue, Wed, Thu, Fri, TotalHours;

cout << endl << FullName << "'s Weekly Hours\n";


cout << "Monday: ";
cin >> Mon;
cout << "Tuesday: ";
cin >> Tue;
cout << "Wednesday: ";
cin >> Wed;
cout << "Thursday: ";
cin >> Thu;
cout << "Friday: ";
cin >> Fri;

TotalHours = Mon + Tue + Wed + Thu + Fri;

20
return TotalHours;
}
#include <iostream>
using namespace std;

int GCD(int a, int b)


{
int Remainder;

while( b != 0 )
{
Remainder = a % b;
a = b;
b = Remainder;
}

return a;
}

int main()
{
int x, y;

cout << "This program allows calculating the GCD\n";


cout << "Value 1: ";
cin >> x;
cout << "Value 2: ";
cin >> y;

cout << "\nThe Greatest Common Divisor of "


<< x << " and " << y << " is " << GCD(x, y) << endl;

return 0;
}
#include <iostream>
using namespace std;
21
int GCD(int a, int b)
{
while( 1 )
{
a = a % b;
if( a == 0 )
return b;
b = b % a;

if( b == 0 )
return a;
}
}

int main()
{
int x, y;

cout << "This program allows calculating the GCD\n";


cout << "Value 1: ";
cin >> x;
cout << "Value 2: ";
cin >> y;

cout << "\nThe Greatest Common Divisor of "


<< x << " and " << y << " is " << GCD(x, y) << endl;

return 0;
}

22

You might also like