[go: up one dir, main page]

0% found this document useful (0 votes)
26 views33 pages

C++ Session 8

In Java, functions are called methods. A function performs a specific task and can be reused by calling it from other parts of the code. Dividing code into well-defined functions makes programs easier to understand, maintain and debug. Functions are defined by specifying their return type, name, parameters, and body. Functions must be defined before they are called. Calling a function involves specifying the function name and passing any required parameters.

Uploaded by

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

C++ Session 8

In Java, functions are called methods. A function performs a specific task and can be reused by calling it from other parts of the code. Dividing code into well-defined functions makes programs easier to understand, maintain and debug. Functions are defined by specifying their return type, name, parameters, and body. Functions must be defined before they are called. Calling a function involves specifying the function name and passing any required parameters.

Uploaded by

jehoshua35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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> Example #include <iostream>
using namespace std;
using namespace std;
//function declaration void ourSite()
void ourSite() {
cout<<"www";
{ cout<<"www";
cout<<".AiT";
cout<<".AiT"; cout<<".com";
cout<<".com"; } }
int Add()
{
int a, b;//Global variable to Add return a + b;
//another function declaration }
int Add() int a, b;//Won’t work why?
{ return a + b; }
int main()
int main()
{
{ a = 2; a = 2;
b = 3; b = 3;
int answer = Add();//calling Add int answer = Add();
5 cout<<answer<<endl;
cout<<answer<<endl; www.AiT.com 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 = 4;
cout<<".com";
int y = 5;
}
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 = 6; cout<<".com";
int y = 3; }
int answer = Add(x,y);//calling Add() int Add(int a, int b)//parameter list
cout<<answer<<endl; 9 { 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;
void area(float);//Prototype int timesTwo(int num); //prototype
int main()
int main()
{
{ int number, response;
float radius; cout<<"Please enter a number:";
cout<<"Enter the radius: "; cin>>number;
cin>>radius;//inputting radius response = timesTwo(number);//fn call
cout<< "The answer is "<<response;
area(radius); //calling area
return 0;
return 0; }
} //timesTwo function declaration
//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 );
int 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;
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
"<<times<< " times"<<endl;
cout<<"input stopped"<<endl; Keeps saying 1 time
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 Changes now
{ 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 = 0;
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)
{ 5 6 8 9
for(int i=0; i<d; ++i) 0 5 6 9 7 2
cout<<trinidad[i]<< ' ';
cout<<endl;
}
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
The Ghana water company limited is thinking of automating it billing system. As a software developer, you have been
contracted to develop an application for them. The application should be able to:

a. accept the following input:


Customer’s name
Quantity of water consumed
b. distinguish the following categories of consumers based on the number of galons of water used:
i. Domestic if water consumed is less than or equal to 500 galons a month
ii. Commercial if water consumed is more than 500 but less than or equel to1000 galons a month
iii. Industrial if water consumed is more than 1000 galons of water a month.

c. Computer the following:


i. Domestic, amount to pay is GHC 0.15 per galon
ii Commercial, amount to pay is GHC 0.25 per galon
iii. Industrial, amount to pay is GHC 0.30 per galon

d. Display
i. Custmers name:
ii galons of water consumed:
ii Amout of water consumed GHC:
iii 2% of amount consumed to be added for rural water project and fire service.
iv. Total amount payable = Amount of water consumed + amount for rural water and fire service
NB:
Customer name is of type string
Water consumed, amount of water consumed, total Amont payable and 2% rural water project are of type float.

You might also like