You are on page 1of 51

Kombolcha Institute of Technology

College of Informatics
Department Computing and Engineering
Fundamental Programming 2

KIOT@SEMarch 2017 Workie


by Ashenafi
Chapter One

Function in c++

Department Information System

Prepared by. Ashenafi Workie

KIOT@SE by Ashenafi Workie


Get started to Function
Function is group of program statements that can act on
data and return a value. 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.
The reason why we use functions is
 To aid modularization of a program.
 To reduces program size.
 Any fragments of code that are needed frequently in a
program are best candidates to be written as a function.
 A function provides a convenient way of packaging
computational steps, so that it can be used as often as
required.
KIOT@SE by Ashenafi Workie 3
C++ Functions

 C++ allows the use of both internal (user-


defined) and external functions.
 External functions (e.g., abs, ceil, rand, sqrt,
etc.) are usually grouped into specialized
libraries (e.g., iostream, stdlib, math, etc.)
 internal (user-defined) that we declare
 And call when ever we want. Eg add(a,b)

KIOT@SE by Ashenafi Workie 4


User-Defined Functions

C++ programs usually have the following form:

// include statements
// function prototypes(declaration)
// main() function
//{
//function calling
//}
// function definitions

KIOT@SE by Ashenafi Workie 5


Here are all the parts of a function

 The return type :is the data type of the value


the function returns. Some functions perform
the desired operations without returning a
value which is called void. E.g. float ,int, void
and double etc.
 Function Name: This is the actual name of
the function. The function name and the
parameter list together constitute the function
signature.
add, sum,fact,fabo,product,etc.but must fulfill
rule of identifier.
KIOT@SE by Ashenafi Workie 6
Cont.…d

Parameters: A parameter is like a


placeholder. When a function is invoked, you
pass a value to the parameter. This value is
referred to as actual parameter or argument.
The parameter list refers to the type, order,
and number of the parameters of a function.
E.g. (int x , int y), (int y)
NB:Parameters are optional; that is, a function
may contain no parameters. E.g. ()

KIOT@SE by Ashenafi Workie 7


Function (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.
Example
void getnumber( ); this is a function declaration.

KIOT@SE by Ashenafi Workie 8


cont....d
Void shows that the function doesn’t have a
return type. Function declaration is terminated with
semicolon.
float add(int x,int y);
function name parameter list

Return type function declaration end in semicolon


Common errors:
 Missing semicolon at end of function declaration
 Use the one data type for different arguments
 eg .(int x,y)

KIOT@SE by Ashenafi Workie 9


Cont...d

KIOT@SE by Ashenafi Workie 10


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 comprise the function.
KIOT@SE by Ashenafi Workie 11
Cont.…d

float add(int x,int y) {


//function body
}

KIOT@SE by Ashenafi Workie 12


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.
KIOT@SE by Ashenafi Workie 13
Cont.…d

 The function call is similar to its declaration


except that the return type is not
mentioned.
add(x,y); semicolon is mandatory
parameters without data type
function name
If the value is given it possible to call function
like
add(5,2); value x is 5 and value x is 2

KIOT@SE by Ashenafi Workie 14


Example 1 Simple function
to display message hello function

outputs

KIOT@SE by Ashenafi Workie 15


Example 2 function with argument and return value
write c++ program to add two integer number?

outputs

KIOT@SE by Ashenafi Workie 16


Example 3 function with no argument and no return value
write c++ program to add two integer number?

outputs

KIOT@SE by Ashenafi Workie 17


Example 4 function with no argument and but has return value
write c++ program to add two integer number?

outputs

KIOT@SE by Ashenafi Workie 18


Example 5 function with argument but no return value
write c++ program to find power of number?

outputs

KIOT@SE by Ashenafi Workie 19


Example 6 c++ program thas multiple function

KIOT@SE by Ashenafi Workie 20


Function declaration with function definition at the top

outputs

KIOT@SE by Ashenafi Workie 21


Pass parameter call by value
Example 1
#include <iostream.h>
#include<conio.h>
B ) void print(int &num);
void main ()
{
outputs
int x = 0;
x++;
print(x);
cout << "x = " << x << '\n';
getch();
}
void print (int &num)
{
num = 0;
cout << "num = " << num << '\n';
}
KIOT@SE by Ashenafi Workie 22
Parameters and Arguments

 C++ supports two styles of parameters: value


and reference. A value parameter receives
a copy of the value of the argument passed
to it. As a result, if the function makes any
changes to the parameter, this will not affect
the argument. For example, in the following
simple program,

KIOT@SE by Ashenafi Workie 23


Example 2 call pass by value

outputs

KIOT@SE by Ashenafi Workie 24


Example 1 call by reference.
Example 1
#include <iostream.h>
#include<conio.h> outputs
void Foo (int &num);
void main ()
{
int x = 10;
Foo(x);
cout << "x = " << x << '\n';
getch();
}
void Foo (int &num)
{
num = 0;
cout << "num = " << num << '\n';
}

KIOT@SE by Ashenafi Workie 25


Example 2 call by reference.

outputs

KIOT@SE by Ashenafi Workie 26


Example 2 by address/pointer.

outputs

KIOT@SE by Ashenafi Workie 27


Global and Local Scope
Everything defined at the program scope level (i.e., outside functions) is
said to have a global scope. Thus the sample functions we have seen so far
all have a global scope. Variables may also be defined at the global scope:

KIOT@SE by Ashenafi Workie 28


Default Arguments

void Error (char message, int severity = 0);


here, severity has a default argument of 0; both
the following calls are therefore valid:
Error( ‘x’, 3); // severity set to 3
Error( ‘R’); // severity set to 0
Eg 2 int divide ( int a, int b = 7 );
Variable b will have value 7 if not specified
when calling function.

KIOT@SE by Ashenafi Workie 29


Global and Local Scope

 Everything defined at the program scope


level (i.e., outside functions) is said to have a
global scope. Thus the sample functions we
have seen so far all have a global scope.
Variables may also be defined at the global
scope:
 Variables inside parenthesis of functions
declarations have local level access.

KIOT@SE by Ashenafi Workie 30


Global (scope)

outputs

KIOT@SE by Ashenafi Workie 31


Use global scope using(:: operator)

outputs

KIOT@SE by Ashenafi Workie 32


Local Scope

outputs

KIOT@SE by Ashenafi Workie 33


Function Overloading

 If two or more different functions can have


the same name and the prototype e of their
arguments are different. That means that you
can give the same name to more than one
function . Function overloading used when.
 if they have the same data type but a
different number of arguments .
 The same number argument but different
data types .

KIOT@SE by Ashenafi Workie 34


KIOT@SE by Ashenafi Workie 35
Cont...d

KIOT@SE by Ashenafi Workie 36


Inline Functions

Suppose that a program frequently requires to find


the absolute value of an integer quantity. For a
value denoted by n, this may be expressed as:
(n > 0 ? n : -n) //However, instead of replicating
this expression in many places in the program, it is
better to define it as a function:
int Abs (int n)
{
return n > 0 ? n : -n;
}

KIOT@SE by Ashenafi Workie 37


Example for inline function

KIOT@SE by Ashenafi Workie 38


E.g. write program to find out factorial of number

KIOT@SE by Ashenafi Workie 39


Recursion function
 A function which calls itself is said to be
recursive. Recursion is a general programming
technique applicable to problems which can be
defined in terms of themselves. 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:

KIOT@SE by Ashenafi Workie 40


Factorial as recursion technique

outputs

KIOT@SE by Ashenafi Workie 41


Enumerations

 An enumeration of symbolic constants is introduced


by an enum declaration. This is useful for declaring a
set of closely-related constants. For example,
enum {north, south, east, west};
 introduces four enumerators which have integral
values starting from 0 (i.e., north is 0, south is 1, etc.)
Unlike symbolic constants, however, which are read-
only variables, enumerators have no allocated
memory.
 The default numbering of enumerators can be
overruled by explicit initialization:enum {north = 10,
south, east = 0, west}; Here, south is 11 and west is 1
KIOT@SE by Ashenafi Workie 42
Cont.…d

outputs

KIOT@SE by Ashenafi Workie 43


Exercises
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);
KIOT@SE by Ashenafi Workie 44
Cont.…d
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; }
KIOT@SE by Ashenafi Workie 45
Cont...d
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.

KIOT@SE by Ashenafi Workie 46


Cont.…d

KIOT@SE by Ashenafi Workie 47


KIOT@SE by Ashenafi Workie 48
Cont.…ed

KIOT@SE by Ashenafi Workie 49


Cont.…d

KIOT@SE by Ashenafi Workie 50


Any ambiguous

Questions

KIOT@SE by Ashenafi Workie 51

You might also like