Session 8 Functions

You might also like

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

Functions

In Java, functions are called methods


What is a function
• A function is a group of statements that
together perform a task.
• So far all the programs that we have written
have had one function, the “main”
• No program needs more than one main
function.
• However as you write more complex and
sophisticated programs you see that your main
function becomes extremely long.
• Note that the compiler does not care whether
your main function is too long or not.
Function Cont.
• You should care, as a main function continues
for pages it’s difficult to understand or fix
errors if they arise.
• An analogy is a book of several hundreds of
pages are broken into chapters and
subchapters.
• You can divide your code into functions, how
it should be divided depends on you.
• But it should be done such that each function
performs specific task
Function Cont.
• There are other advantages of dividing your
codes into functions in addition to making your
code easier to read and understand.
• Example if a function performs specific task
such as sending output to printer, which is
performed several times in the program
• You only need to write in a function once, and
call it when needed.
Definition and Calling a Function
• Employing a function • Consider the program
in addition to the # include <iostream>
main function involves Using namespace std;
two steps int main ()
a. Defining the function {
b. Calling the function cout << “Hello world”;
return 0;
}
• A function body must
contain a return type
unless the return type is
Function Cont.
• int main () is the The main function
function header. This is int main()
not a statement so it {
not followed by cout<<“Hello World”;
semicolon
return 0 ;
• The header contains:
}
1. A return type
2. A function name and
The data type int
3. An argument list preceding main is the
return type
main is the function name
The parenthesis which is The function header and
empty this time but not body together are
always may contain the referred to the function
argument list. definition.
A function header always A function cannot
is followed by open and execute unless it is first
closed curly brace. Which defined.
contains the body of the Once defined it executes
function when called.
There may be other open The main function is
and closed curly brace called automatically
within the first open and when a program runs
closed curly brace
Example
#include <iostream>
using namespace std;
int main()
{ Will this program
//calling printMessage run yes/no: why?
printMessage();
return 0;
}
//function declaration
void printMessage()
{
cout<<"Hello world";
#include <iostream> The program did not
using namespace std; run because the
function is called by
int main() main before its
{ definition.
//calling printMessage This means that main
printMessage(); return 0; does not know of:
} 1. The function name;
//function declaration 2. Return type and
void printMessage() 3. Argument list.
{
cout<<"Hello world";
}
Function Cont.
There are two ways of correcting it.
1. Define all the function above main. Or
2. Declare a prototype.
i.e. copying the function definition and placing it
above main but, it should be terminated with a
semicolon (prototype).
Example void printMessage();
The void attachment means that there is no
return type or the function does not return a
variable.
Method 1 Method 2
#include <iostream> #include <iostream>
using namespace std; using namespace std;
//function declaration //prototype
void printMessage() void printMessage();
{ int main()
{
cout<<"Hello world";
printMessage();
}
return 0;
int main()
}
{
//function declaration
// calling printMessage void printMessage()
printMessage(); {
return 0; cout<<"Hello world";
#include <iostream> #include <iostream>
using namespace std; Example using namespace std;
//function declaration
void ourSite() void ourSite()
{ {
cout<<"www"; cout<<"www";
cout<<".AiT"; cout<<".AiT";
cout<<".com"; cout<<".com";
} }
int a, b;//Global variable to Add int Add()
//another function declaration {
int Add() return a + b;
{ }
return a + b; int a, b;//Won’t work why?
}
int main() int main()
{ {
a = 2; a = 2;
b = 3; b = 3;
int answer = Add();//calling Add 5 int answer = Add();
cout<<answer<<endl; www.Ait.com cout<<answer<<endl;
ourSite();//calling ourSite ourSite();
This is the best because it contains parameter list Using prototype
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void ourSite(); //prototype
void ourSite() // these are the same prototypes
{ int Add(int, int); //int Add(int a, int b);
cout<<"www"; int main()
cout<<".Ait";
{ int x = 2;
cout<<".com";
int y = 3;
}
int answer = Add(x,y);//calling Add()
int Add(int a, int b)//parameter list
cout<<answer<<endl;
{
return a + b;
ourSite(); } //calling ourSite
}
void ourSite()
int main() { cout<<"www";
{ cout<<".Ait";
int x = 2; cout<<".com";
int y = 3; }
int answer = Add(x,y);//calling Add() int Add(int a, int b)//parameter list
cout<<answer<<endl; 5 { return a + b; }
ourSite(); //calling ourSite www.Ait.com
#include <iostream>
using namespace std;
// these are prototypes
void ourSite(string a, string b, string c);
Passing
int Add(int, int); //int Add(int a, int b);
int main()
parameters
{ int a = 2, b = 3;
int answer = Add(a,b); //calling Add()
cout<<answer<<endl;
string u = "www", v=".AiT", c = ".com"; 5
ourSite(u,v,c); //calling ourSite }
www.Ait.com
void ourSite(string a, string b, string c)
{ cout<<a<<b<<c; }
int Add(int a, int b)//parameter list
{ return a + b; }
#include <iostream> Example
using namespace std;
void starline(); // prototype of function
int main()
{ starline( ); // function call
cout<< "\t Welcome to the C++ function class \n";
starline( ); // function call
return 0;
} ********************************************
// function definition Welcome to the c++ function class
********************************************
void starline()
{
int count; // declaring a LOCAL variable
for(count = 1; count <=50; count++)
cout<< "*";
cout<<endl;
}
Argument to a function Return type function
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int timesTwo(int num); //function prototype
void area(float);//Prototype
int main()
int main()
{
{
int number, response;
float radius; cout<<"Please enter a number:";
cout<<"Enter the value of radius: "; cin>>number;
cin>>radius;//inputting radius response = timesTwo(number);//function call
area(radius); //calling area cout<< "The answer is "<<response;
return 0; return 0;
} }
//function declaration //timesTwo function declaration
int timesTwo (int num)
void area(float r)
{
{
int answer; //local variable
cout << "the area of the circle is" answer = 2 * num;
<< 3.14*r*r << "\n"; return (answer);//return type
} }
Calling a Function
• A function can be called using any of the
following
1. Call by value
2. Call by reference
3. Call by pointer // we will not deal with this
#include <iostream> Call by value
using namespace std;
void swap(int , int );
nt main()
{
int a=10,b=20;
swap(a,b);
cout<<a<<" "<<b; Answer
return 0; }
10 20
void swap(int c, int d)
{
int t;
t=c;
c=d;
d=t;
#include <iostream> Call by value
using namespace std;

void callByReference(int x)
{ x = 5; } The value of x is 3

int main()
{
int x = 3; //change does affect function call
callByReference( x );
cout << "The value of x is " << x;
return 0; }
#include <iostream> Call by reference
using namespace std;
void swap(int &, int &);
int main()
{
int a=10,b=20;
swap(a,b);
cout<<a<<" "<<b;
Answer
return 0;
}
20 10
void swap(int &c, int &d)
{
int t;
t=c;
c=d;
Call by Reference
#include <iostream>
using namespace std;

void callByReference(int& x)
{ x = 5; } The value of x is 5,
int main()
{
int x = 3; //change does not affect function call
callByReference( x );
cout << "The value of x is " << x;
return 0;
Variable Scope and Lifetime
• Thus far, variables have been defined on top
of the main function (Global).
• In programs where only main is the function,
the variables can be accessed throughout the
entire program.
• Once we begin dividing up codes into separate
functions, there arise the issue of variable
scope and lifetime.
Variable Scope and Lifetime Cont.
• A global variable have scope through out a
program and lifetime did not end until the
entire program ends.
• A static variable has scope of local variable but
lifetime of a global variable.
• A static local variable is declared with the
keyword static attached and usually with a
starting value
Local Variable
#include <iostream> else
using namespace std; printMessage();
void printMessage();//prototype
cout<<endl;
int main()
{ }while (choice != 'Q');
char choice; Keeps say 1 time
do return 0;
{ }
cout<<"enter Q to quit, any other void printMessage()
character to continue: ";
{
cin>> choice;
int times = 0;//local variable
if (choice == 'Q' ) times++;
{ cout<< "This function called
cout<<"input stopped"<<endl; "<<times<< " times"<<endl;
Local Variable
• The variable times is local to printMessage
function since it is declared in that function.
• Being a local variable each time the
printMessage function is called, the variable
times is created
• Also each time the printMessage function
ends, the variable times is destroyed.
• To make a variable persistent between
function calls
1. Keep the variable local but make it static.
Global Variable
#include <iostream> {
using namespace std; cout<<"input stopped"<<endl;
void printMessage();//prototype
}
int times;//Global Variable else
printMessage();
int main() cout<<endl;
{
char choice; }while (choice != 'Q');
do
Same old results
{ return 0;
times = 0; }
cout<<"enter Q to quit, any other void printMessage()
character to continue: "; {
cin>> choice; times++;
cout<< "This function called
if (choice == 'Q' ) "<<times<< " times"<<endl;
Static local Variable
#include <iostream> else
using namespace std; printMessage();
void printMessage();
cout<<endl;
int main() }while (choice != 'Q');
{ return 0;
char choice;
}
do
{ void printMessage()
cout<<"enter Q to quit, any other {
character to continue: ";
static int times =0;
cin>> choice;
times++;
if (choice == 'Q' ) cout<< "This function called
{ "<<times<< " times"<<endl;
cout<<"input stopped"<<endl;
} Result will now change
Stopping the program after 3 inputs
#include <iostream> if (choice == 'Q' )
using namespace std; {
void printMessage();
cout<<"input stopped"<<endl;
int main()
}
{ else
char choice; printMessage();
int counter=1; cout<<endl;
do }while (choice != 'Q');
{
return 0;
cout<<"enter Q to quit, any other character
to continue: "; }
cin>> choice; void printMessage()
if (counter == 3)//counting {
{ static int times;
cout<<"you have entered the value 3 times++;
times"<<endl;
break;
cout<< "This function called
}
"<<times<< " times"<<endl;
}
Sending message to a function

#include <iostream> cout<<"Enter a string:


";
#include <string>
getline(cin,str);
using namespace std;
printMessage();
void printMessage ();
cout<<endl<<endl;
return 0;
string str;//Global }
Variable void printMessage()
int main() {
{ cout<<"You inputted
"<<str;
#include <iostream>
using namespace std; Example
//function
void goArray(int trinidad[],int d)
{
for(int i=0; i<d; ++i)

cout<<trinidad[i]<< ' '; 5 6 8 9


cout<<endl; 0 5 6 9 7 2
}
int main()
{
int tomatos[] = {5,6,8,9};
int barakota[] = {0,5,6,9,7,2};
goArray(tomatos,4);
goArray(barakota,6);

}
#include<iostream>
using namespace std;
Example 2

void goDady(int polabare[],int length)


{
for(int i = 0; i<length; ++i)
cout<<polabare[i]<<' ';
cout<<endl;
}
6,5
int main() 1,3,2,4,81
{
int boobala[] = {6,5,8,9,7};
int Rambo[] = {1,3,2,4,81,79};
goDady(boobala,2);
goDady(Rambo,5);
Assignment
• Write a program to calculates the factorial of a
number when entered.
• The program should contain a function which
purposely does the calculation

You might also like