0% found this document useful (0 votes)
10 views13 pages

Chapter 4 Handout...

Chapter Four discusses functions in C++, defining them as blocks of code designed to solve specific problems and emphasizing their importance in program modularity and reusability. It outlines the basics of functions, including their declaration, definition, and calling, as well as the advantages they offer, such as code optimization and reduced repetition. The chapter also differentiates between library functions and user-defined functions, and explains techniques for passing arguments to functions.

Uploaded by

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

Chapter 4 Handout...

Chapter Four discusses functions in C++, defining them as blocks of code designed to solve specific problems and emphasizing their importance in program modularity and reusability. It outlines the basics of functions, including their declaration, definition, and calling, as well as the advantages they offer, such as code optimization and reduced repetition. The chapter also differentiates between library functions and user-defined functions, and explains techniques for passing arguments to functions.

Uploaded by

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

Chapter Four

Functions

4. What is a function?

 A function provides a convenient way of packaging a computational recipe, so that it can


be used as often as required.
 Therefore, a function is a block of code designed to tackle a specific problem.
 A function is a group of statement that is executed when it is called.
 Functions are building blocks of the programs.
 They make the programs more modular and easy to read and manage.
 All C++ programs must contain the function main( ).
 The execution of the program starts from the function main( ).
Reasons for function?
 To make the program dev’t more manageable
 To remove repetition of codes
 For software reusability purpose
4.1. Basics of Function
 One of the best ways to tackle a problem is to start with the overall goal, then divide this
goal into several smaller tasks. You should never lose sight of the overall goal, but think
also of how individual pieces can fit together to accomplish such a goal.
 If your program does a lot, break it into several functions. Each function should do only
one primary task.
C++ function has the following rules
1. Every function has a name
2. Function name can be assigned by a programmer following the same rule as naming
variables
3. Its name has one set of parenthesis
4. Every function has a body following the parentheses
4.2 Advantage of functions in C++
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. Therefore, we do not need to write
the same code repeatedly.
2). Code optimization
It makes the code optimized; we do not need to write much code. Suppose, you have to check 3
numbers (n1, n2 and n3) whether it is prime number or not. Without using function, you need to
write the prime number logic 3 times. Therefore, there is repetition of code. However, if you use
functions, you need to write the logic only once and you can reuse it several times.

Choose the best answer on the provided space


1. A collection of items of different data types is ___________________
A. Pointer B. Array C. Structure D. Functions
2. The instance of the structure is__________
A. Structure definition C. Structure variable
B. Structure operator D. Structure array
3. ________________is a variable that holds the address of some other variable.
A. Pointer C. Structure D. File
B. Function management
4. ___________________is the address of a storage location with a defined type.
A. Pointer B. Structure C. Array D. Variable
5. ________________supports files for simultaneous input and output.
A. Fstream B. Oftsream C. Ifstream D. Ostream
6. ________________returns the current get position in a stream
A. Tellp B. Tellg C. Seekp D. seekg
7. Which one can be considered as the name of a variable of type istream.
A. Cout B. Cin C. Close D. Open
8. A file that contains information in the same format as it is held in memory is __________
A. Text files B. Binary files C. Bit D. bytes
9. Open file for reading only
A. ios::in B. ios::out C. ios::app D. ios::ate
10. Information is accessed in a chronological order in _____________
A. Random file access. C. Non sequential file
B. Alphabetical order D. Sequential file
11. All are true, except
A. Structure do not have concept of Pointer internally.
B. In case of array the input data stored in contiguous memory allocation.
C. Array is a type of data structure used as container which can hold variables of different types.
D. Structure is a data structure used as container which can hold variables of different types.
12. Which one is legal statement for pointers?
A. *pi = 4; B. int *pi; C. void *P; D. all
13. A memory address is ____________
A. a data type B. a variable C. a number D. a string
14. Which one is true about structure?
A. defined with the struct keyword D. All
B. a user-defined data type in C++
C. a collection of items of different data
types
15. What is meaning of following declaration? int(*p[5])();
A. p is pointer to function.
B. p is array of pointer to function
C. p is pointer to such function which return type is array.
D. p is pointer to array of function. View Answer
16. Void pointer can point to which type of objects?
A. int
B. float
C. double
D. all
17. By default, all the files in C++ are opened in _________ mode.
A. Binary
B. Video teleconference
C. Text
D. ASCII
18. Which of the following correctly declares an array in C++?
A. array{10};
B. array array[10];
C. int array;
D. int array[10];
19. The operator used for dereferencing or indirection is ____
A. *
B. &
C. ->
D. –>>
20. Which one of the following is not a possible state for a pointer?
A. hold the address of the specific object
B. point one past the end of an object
C. zero
D. point to a type
Types of Functions
There are two types of functions in C programming:
1. Library Functions (Built in functions): are the functions which are declared in the C++ header
files such as strcmp(), strlen(), sqrt(),pow(),.. etc.
2. User-defined functions: are the functions that are created by the C++ programmer, so that he/she
can use it many times. It reduces complexity of a big program and optimizes the code.
4.3. Declaring, defining and calling functions
4.3.1. Declaring function:
 The interface of a function (also called its prototype) specifies how it may be used. It consists
of three entities:
 The function return type. This specifies the type of value the function returns. A function
which returns nothing should have a return type void.
 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.
Syntax: Function Declaration
 return_type function_name(parameter list) ;
 A function declaration is made by declaring the return type of the function, name of the
function and the data types of the parameters of the function.
 Always terminated by semicolon.
 The return type specifies the type of the data the function returns.
 The parameter list could be empty .
 The parameter list should contain both data type and name of the variable. For example, int
factorial(int n, float j)
Function Prototypes
The function prototype is a statement, which means it ends with a semicolon. It consists of the
function's return type, name, and parameter list. The parameter list is a list of all the parameters
and their types, separated by commas.
Function Prototype Syntax:
return_type function_name ( [type [parameterName1] type [parameterName2]]...);

4 C++ function
The function prototype and the function definition must agree exactly about the return type, the
name, and the parameter list. If they do not agree, you will get a compile-time error.
• Note, however, that the function prototype does not need to contain the names of the
parameters, just their types. A prototype that looks like this is perfectly legal:
Exampel: double area(int, int);
i.e function heading without the body of the function
4.3.2. Defining a function:
 A function definition consists of two parts: interface (prototype) & body. The brace of a
function contains the computational steps (statements) that computerize the function. The
definition consists of a line called the decelerator.
 The header is exactly like the function prototype, except that the parameters must be named,
and there is no terminating semicolon.
 The body of the function is a set of statements enclosed in braces.
 If function definition is done before the main function, then there is no need to put the
prototype, otherwise the prototype should be scripted before the main function starts.
Function Definition Syntax
 return_type function_name ( [type parameterName1], [type parameterName2]...)
{ statements; }
 Function can be:
 Value Returning function: fu/n that has return type and it uses return statement to return
value.
 Void function: function that don’t have return type
4.3.3. Calling the function:
 Using a function involves ‘calling’ it.
 Calling a function means making the instruction of the function to be executed.
 A function call consists of the function name followed by the call operator brackets ‘()’, inside
which zero or more comma-separated arguments appear. The number and type of arguments
should match the number of function parameters. Each argument is an expression whose type
should match the type of the corresponding parameter in the function interface.
 When a function call is executed, the arguments are first evaluated and their resulting values
are assigned to the corresponding parameters. The function body is then executed. Finally the
return value (if any) is passed to the caller.

5 C++ function
 A function call in C++ is like a detour on a highway. Imagine that you are traveling along the
“road” of the primary function called main(). When you run into a function-calling statement,
you must temporarily leave the main() function and execute the function that was called. After
that function finishes (its return statement is reached), program control returns to main(). In
other words, when you finish a detour, you return to the “main” route and continue the trip.
Control continues as main() calls other functions.
Syntax: function name(parameter list);
Function call can be done by either 1. By Value 2. Call by Reference
Function Parameter and Argument
Function Arguments
 Arguments contain the actual value which is to be passed to the function when it is called.
 The sequence of the arguments in the call of the function should be same as the sequence of the
parameters in the parameter list of the declaration of the function.
 When a function call is made arguments replace the parameters of the function.
Function Parameter: - is list of variables used by the function to perform its task.
 It is the means used for a function to share information with the block containing the call
Parameter vs. argument
 Argument: Always appear in a function call within the calling block.
 Sometimes we call it as actual parameter
 Parameter: Always appear in the function heading, or function prototype. Sometimes we
call it as formal parameter
 NB: The parameter and Argument should have a clear correspondence
Example 1.
#include<iostream.h>
int addition(int a,int b) //function defin/ function header
{ //function body
int r; Parameter
R=a+b;
return (r);
}
int main() //main function
{
int z; Argument/actual Parameter
Z=addition(10,20); //calling fu/n
Cout<<“The result is”<<z;
return 0;
}

6 C++ function
Example 2
#include<iostream.h>
#include<conio.h>
void starLine(); //prototype of the function with a name starLine
int main() {
starLine(); //Calling the function with a name starLine
cout<< “Data type Range” << endl;
starLine();
cout<< “char -128 to 127” <<endl
<< “short -32,768 to 32,767” <<endl
<< “ int system dependent” <<endl
<< “long -2,147,483,648 to 2,147,483,647” << endl;
starLine();
return 0;
}
void starLine() {
for(int j=0;j<45;j++) // definition of the function with a name starLine
cout<< “*”;
cout<<endl;
}

 Given the next program, which function is the calling function and which is the called
function?
#include<iostream.h>
#include<conio.h>
void nextMsg()
int main() {
cout<< “Hello!\n”;
nextMsg();
return 0;
}
void nextMsg() {
cout<< “GoodBye!\n”;
return ;
}
Example 3
Function with Parameters
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);// num1 and num2 are signatures(parameters)
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);

7 C++ function
cout << "Max value is : " << ret << endl;
return 0; }
int max(int num1,int num2){//function returning the max number
int result; // local variable declaration
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

When you compile and run the above program it will give you the following result
Max value is: 200
Example 4

#include <iostream>
using namespace std;
int sum(int a, int b = 20) {
int result;
result = a + b;
return (result);
}
int main () {
int a = 100; // local variable declaration:
int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b); // we change the value of b and called sum()
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum(a);// the default values is used, b have 20 values here
cout << "Total value is :" << result << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120

8 C++ function
4.4. Techniques of calling/passing argument
1. Calling/passing by value
 A value parameter receives a copy of only the value of the argument passed to it. as result, if
the function makes any changes to the parameter, this will not affect the argument.
 Copies of the arguments are created .
 The parameters are mapped to the copies of the arguments created.
 The changes made to the parameter do not affect the arguments.
 In this parameter passing method, values of actual parameters are copied to function’s
formal parameters and the two types of parameters are stored in d/t memory locations. So
any changes made inside functions are not reflected in actual parameters of the caller.
Example 5:
#include<iostream>
Void message(int num)//function definition 4th
{
num=0; //function body 5th
Cout<<“num=“<<num<<“\n”; 6th
}
Int main() //main function 1st
{ Output
Int x=10; 2nd Num=0
Message(x);// fu/n call 3rd X=10
Cout<<“x=“<<x<<“\n”; 7th
getch();
}
NB: even if num reinitialize to 0 the value of x is as it is since it is calling by value.
Example 6
#include<iostream>
int add(int n); //fun prototype
int main() fun //main Initial value of number 5
{ Final value of number 5
int number,result; //declaration Result is 105
number=5;
cout << “ initial value of number : " << number << endl;
result=add(number); //fun call
cout << " final value of number : " << number << endl;
cout << " result is : " << result << endl;
return(0);
}
int add(int number) //fun defin
{ //fun body
number=number+100;
return(number);
}

9 C++ function
2. Passing by Reference
 It receives the argument passed to it and it works on it directly. any change made by the fu/n to
a reference parameter is in effect directly applied to the argument.
 The address of the argument is copied into the parameter.
 The changes made to the parameter affect the arguments.
 Call by reference use & symbol.
 Both the actual and formal parameters refer to the same locations, so any changes made
inside the function are actually reflected in actual parameters of the caller.
Example 7:
#include<iostream>
Void message(int &num)//function definition 4th
{ Output
Num=0; //function body 5th Num=0
Cout<<“num=“<<num<<“\n”; 6th X=0
}
int main() //main function 1st
{ int x=10; 2nd
rd
message(x);// fu/n call 3
Cout<<“x=“<<x<<“\n”; 7th
return 0;}
Since num is a reference parameter, any change made to num will affect the argument x also.
#include<iostream.h>
#include<conio.h>
void swap(int &a,int &b)
{
int t=a;
a=b;
b=t; }
int main()
{
int m=1,n=2;
cout<<"Value of m before swaping\t"<<m<<endl;
cout<<"Value of n before swaping\t"<<n<<endl;
swap(m,n);
cout<<"Value of m after swaping\t"<<m<<endl;
cout<<"Value of n after swaping\t"<<n<<endl;
getch(); }

10 C++ function
// Example 8 call by value
#include <iostream> // Example 9 call by reference
using namespace std; #include <iostream>
void change(int data); using namespace std;
int main() void change(int &data);
{ int main()
int data = 3; {
change (data); int data = 3;
cout << "\n before changed: " <<data<< endl; change(data);
return 0; cout << "\n Orginal data value :: " <<data<< endl;
} return 0;
void change(int data) }
{ void change(int &data)
data =data+1; {
cout<<"After changed:"<<data; data =data+1;
} cout<<"after the data value changed "<<data;
Out put }
after changed:4 Out put
before changed: 3 after the data value chenged : 4
Orginal data value : 4

Self Test Exercise


1. Identify function declaration, function call and function definition for the following code
Answer
#include<iostream>
using namespace std;
void message(int &num) //reference parameter or function definition
{
num=0; //function body
cout<<"num="<<num<<"\n"; //num=0
} int main() //main function
{ int x=10;
message(x); //function calling
cout<<"x="<<x<<"\n"; //x=0, if we remove & symbol, x=10,i.e calling by value or calling by reference
}
11 C++ function
2. Write the output of the following code and function prototype, main function, function
declaration, function call, function definition and function body.
#include<iostream>
using namespace std;
int add(int n); //function prototype
int main() //main function
{
int number, result; //variable declaration
number=5;
cout<<"The initial value of a number is: "<<number<<endl;
result=add(number); //function call
cout<<"The final value of number is:"<<number<<endl;
cout<<"The result number is :"<<result<<endl; return 0;}
int add(int number) //function definition
{ number=number+100;
return(number); //function body
}
Answer
Initial value=5 Final value=5 Result number =105
Worksheet Four
1. Write an int function cube () that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two formal
parameters h and w, where h is the height and w is the length of the bases of the triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle using its two
float formal parameters h and w, where h is the height and w is the width of the rectangle.
4. Write a program that accepts a positive integer from the user and displays the factorial of the given
number. You should use a recursive function called factorial () to calculate the factorial of the
number.
5. Write another program that accepts a number from the user and returns the Fibonacci value of that
number. You should use recursion in here.
6. Write a function called is Prime() that accepts a number and determine whether the number is
prime or not.

12 C++ function
7. Write a function called is Even() that uses the remainder operator(%) to determine whether an
integer is even or not.

13 C++ function

You might also like