Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Roshan Gunathilake

378179
Subroutines : introduction
 In computer programming, a subroutine is a
sequence of program instructions that performs a
specific task, packaged as a unit.
 This unit can then be used in programs wherever
that particular task should be performed.
 Prevents code repeatetion and improves
reusability.
Subroutines in different languages
 In different programming languages, a subroutine
may be called :
 a procedure
 a function
 a routine
 a method
 or a subprogram
 The generic term callable unit is sometimes used.
Components of a Subroutine
 Body : The content of a subroutine is its body,
which is the piece of program code that is executed
when the subroutine is called or invoked.
 Header : Contains name, return type and
parameter list
Subroutine : Example
public int total(int n1,int n2){ // header
int tot=n1+n2;
return tot; // return statement
}

//Invoking a subroutine :

int y=total (4,5);


Parameter Passing
 Values are passed to the subroutine parameters
during the invocation. Those values are called
arguments.
 Eg : total (4,5);
 4 and 5 are arguments
Call by value and Call by reference
 Call by value : A value or a variable name directly
passed into the parameter
 Call by Reference : method of passing arguments
to a function copies the reference of an argument
into the formal parameter. Inside the function, the
reference is used to access the actual argument
used in the call.
 Call by reference in not supported by java, but
languages like C,C++ does.
Call by Reference : Example
Declaration :

void swap(int &x, int &y);

Calling :

Int a=100;
Int b=200;
swap(a, b);
References
 https://en.wikipedia.org/wiki/Subroutine
 www.tutorialspoint.com

You might also like