SlideShare a Scribd company logo
C++ Functions
Main () function
C++ functions are a group of statements in a single logical unit
to perform some specific task.
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello world!";
return 0;
}
Structure of main () function
Function Header
Return type
In this case,
integer
Function_name,
main
Argument/s ( )
In this case, void
Entry Point, Curly braces
Exit Point, Curly braces
Return statement
Function
Body
Statement 1…
Statement 2…
……………..
Note: main () structure defined above extends for all functions
Defining a function
The function header and body together are referred to as the function definition. A function cannot
execute until it is first defined. Once defined, a function executes when it is called.
#include <iostream>
using namespace std;
// begins definition of printMessage function
void printMessage (void)
{ // Statements
cout << "Hello world!";
// return;
}
// ends definition of printMessage function
int main ()
{
printMessage(); // calls printMessage function
return 0;
}
Function Definition
User-defined function
(Header)
No return
Value
Function_name No arguments/parameters
Or simply ( )
Function body
Main Function
#include <iostream>
using namespace std;
void printMessage (void)
{
cout << "Hello world!";
return; //It makes no difference
}
int main ()
{
printMessage();
// calls printMessage function
return 0;
}
Code
Output
Calling a function
A function must be defined first, before it can be called. Unless a function is called, it lies dormant with in
the program. A function can be called from with in main function (or any other function) followed by a
semicolon. { function_name(); }
#include <iostream>
using namespace std;
void sum ()
{
int a,b;
cout << "Addition of 2 numbers!n";
cout << "Enter the 2 numbers...n";
cin >> a >> b;
cout << a << " + " << b << " = "
<< a + b;
return;
}
int main ()
{
sum();
// calls sum() function
return 0;
}
Code Output/s
User Defined Function
Function Header
No return
value
Function_name Function
arguments (none)
Function Body
Main () Function
Function being called from main() body. A
function is called by its name followed by a
semicolon
Order of Execution for a Multi-function program
The order of execution is as follows:
1. Execution always starts with the
main function.
2. The first statement in main,
printMessage(), is executed.
3. Execution next shifts to the
printMessage function, and begins
with the first statement in that
function, which outputs “Hello
world!”
4. After the printMessage function
completes executing, execution
returns to the main function with
the next unexecuted statement,
return 0, which completes the main
function.
Function Prototyping
A function prototype is a function declaration that specifies the data types of its arguments in the parameter list. The compiler
uses the information in a function prototype to verify it later when it is defined.
#include <iostream>
using namespace std;
int main ()
{
printMessage();
// calls printMessage function
return 0;
}
void printMessage (void)
{
cout << "Hello world!";
return;
}
Code •Since Execution always begins from main(), why isn’t it placed in the beginning of program
syntax as shown in the code on the left?
•However If we run this code, the compiler gives an error “undeclared identifier”.
•The reason being that since compiler runs from top to bottom & always executes from the
main (), as it encounters the printmessage() function call, it generates error. Because it must
already know of the function’s name, return type, & arguments.
•The preferred solution is to prototype every function (except main ofcourse).
•After prototyping (typing function header followed by ;) above the main function!The
program runs just fine.!
•Output:
•But why should we prototype?
void printMessage (void);
//function prototype
Scope of a variable
Local
Variables
So far all variables have been defined
within main function. In programs
where the only function is main, those
variables can be accessed throughout
the entire program since main is the
entire program. However, once we start
dividing up the code into separate
functions, issues arise.
•The portion of the program where an
identifier can be used is known as its scope.
For example, when we declare a local variable
in a block, it can be referenced only in that
block and in blocks nested within that block.
•The life of a local variable ends (It is
destroyed) when the function exits.
LocalVariable
#include <iostream>
using namespace std;
void test(); Function Prototype( indicates there is 1 function besides main)
int main()
{
// local variable to main()
int var = 5; Variable defined in the locality of main
test(); Function Call
// illegal: var1 not declared inside main()
var1 = 9; // error – undefined identifier
}
void test()
{
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var; //error – undefined identifier
}
Main Function
Test Function
•The portion of the program where an
identifier can be used is known as its scope.
However if a variable is declared above all
functions & their prototypes, then that
variable scopes to the whole of the program.
•It is accessible anywhere through out the
program.
•The life of a local variable ends (It is
destroyed) when the program itself exits.
GlobalVariable
#include <iostream>
using namespace std;
// Global variable declaration
int c = 12;
void test();
int main()
{
++c; // global variable(accessible)
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c; // global variable (accessible)
// Outputs 14
cout << c;
}
GlobalVariable (Variable identified by all
function throughout the program.)
Function Call
So far, we have passed none arguments to the function. Hence we used void function_name (void) type.
Sending Information to a function
There are 2 methods for passing
arguments!
• Passing by reference. (It makes
use of addresses & pointers),
Thus we will study it later.
• Passing by value. In this method,
a value (in constant or variable
form) is passed as an argument to
the function, It then manipulates
it according to program.
• OUTPUT:
#include <iostream>
#include <cmath> // Math function Library
using namespace std; // standard namespace
void circle (double); // function prototype (only data-types)
double PI = 3.1415; // Global Variable
int main() // Main () Header
{ // Main () body entry brace
double rad; // Local variable (rad)
cout << "Solving for the circumference “
<< "& Area of the Circle." << endl;
cout << "...............................n";
cout << "Enter the radius! n";
cin >> rad; // Initializing the local variable (rad)
cout << "...............................n";
circle(rad); // Passing the value to circle() as argument
return 0; // Program exit code
} // Main () body exit brace
void circle (double r) // circle () Header with one double type argument
{ // circle () body entry brace
cout << "Circumference of circle = "
<< 2*PI*r << endl; // Circumference displayed
cout << "Area of the circle = "
<< PI * pow(r,2) << endl; // pow(r,2) is builtin function from math lib
return;
} // circle () body exit brace
Sending Multiple Arguments to a function
#include <iostream>
using namespace std; // standard namespace
void rectangle (double, double);
// function prototype (only data-types)
int main() // Main () Header
{ // Main () body entry brace
double len,wid; // Local variables(len,wid)
cout << "Solving for the Perimeter "
<< "& Area of the rectangle." << endl;
cout << "...............................n";
cout << "Enter the Length & width values! n";
cin >> len >> wid; // Initializing the local variables
cout << "...............................n";
rectangle(len,wid); // Passing the values to rectangle() as
arguments
return 0; // Program exit code
} // Main () body exit brace
void rectangle (double l,double w) // rectangle () Header
{ // rectangle () body entry brace
cout << "Perimeter of rectangle = "
<< 2*(l+w) << endl; // Perimeter displayed
cout << "Area of the circle = "
<< l*w << endl; // Area displayed
return;
} // rectangle () body exit brace
A function can receive multiple arguments
as well.
e.g.
1. rectangle(len,wid);
2. rectangle(14.5,78);
3. sum(3,4,6);
4. Avg(num1,num2,………..num_n)
ReturnValue from a function
#include <iostream>
using namespace std;
double Avg (double,double,double); //function prototype
int main() // main () header
{
double a,b,c; // Local variables to main()
cout << "Solving for Average of 3 numbers!"
<< endl << "Enter the 3 numbers!n";
cin >> a >> b >> c; // Local var initialization
double ans = Avg(a,b,c); // function call with a
return value
// stored in double variable ans
cout << "Answer = "<< ans; // display ans
}
double Avg (double n1,double n2,double n3) // Avg
function header
{
return (n1+n2+n3)/3; // return statement for Avg()
}
C++ Functions
Types of Function Calling
1
Accepting Parameter and Returning Value
2
Accepting Parameter and not Returning Value
Types of Function Calling (Continued)
4
Not Accepting Parameter & not Returning Value
3
Not Accepting Parameter but Returning Value
TO BE CONTINUED

More Related Content

What's hot (20)

PPTX
Inline Functions and Default arguments
Nikhil Pandit
 
PDF
Booting into functional programming
Dhaval Dalal
 
PPTX
Inline functions
DhwaniHingorani
 
PDF
How To Use IO Monads in Scala?
Knoldus Inc.
 
PDF
(3) cpp procedural programming
Nico Ludwig
 
PDF
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
PPTX
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
ODP
C++ Function
PingLun Liao
 
PPTX
Operator overloading
Kumar
 
PDF
Php, mysq lpart3
Subhasis Nayak
 
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
PPT
Operator overloading
ArunaDevi63
 
PDF
Kotlin으로 안드로이드 개발하기
Taehwan kwon
 
PDF
iOS Selectors Blocks and Delegation
Jussi Pohjolainen
 
PPTX
Operator overloading
Garima Singh Makhija
 
PDF
iOS: Frameworks and Delegation
Jussi Pohjolainen
 
PDF
AnyObject – 自分が見落としていた、基本の話
Tomohiro Kumagai
 
KEY
What's New In Python 2.4
Richard Jones
 
PPTX
Operator overloading
ramya marichamy
 
Inline Functions and Default arguments
Nikhil Pandit
 
Booting into functional programming
Dhaval Dalal
 
Inline functions
DhwaniHingorani
 
How To Use IO Monads in Scala?
Knoldus Inc.
 
(3) cpp procedural programming
Nico Ludwig
 
Intro to JavaScript - Week 2: Function
Jeongbae Oh
 
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
C++ Function
PingLun Liao
 
Operator overloading
Kumar
 
Php, mysq lpart3
Subhasis Nayak
 
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
Operator overloading
ArunaDevi63
 
Kotlin으로 안드로이드 개발하기
Taehwan kwon
 
iOS Selectors Blocks and Delegation
Jussi Pohjolainen
 
Operator overloading
Garima Singh Makhija
 
iOS: Frameworks and Delegation
Jussi Pohjolainen
 
AnyObject – 自分が見落としていた、基本の話
Tomohiro Kumagai
 
What's New In Python 2.4
Richard Jones
 
Operator overloading
ramya marichamy
 

Similar to C++ Functions (20)

PPT
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
PPT
Functions
PatriciaPabalan
 
PPTX
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
PPTX
Chapter 4
temkin abdlkader
 
PPT
User Defined Functions
Praveen M Jigajinni
 
PPTX
Amit user defined functions xi (2)
Arpit Meena
 
PPTX
Function C++
Shahzad Afridi
 
PPTX
Cs1123 8 functions
TAlha MAlik
 
PPTX
Intro To C++ - Class #19: Functions
Blue Elephant Consulting
 
PPT
POLITEKNIK MALAYSIA
Aiman Hud
 
DOCX
Functions assignment
Ahmad Kamal
 
DOCX
Introduction to c programming
AMAN ANAND
 
DOC
Functions
zeeshan841
 
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
PDF
concept of functions and its types in c++ language
soniasharmafdp
 
PPT
Functions in c++
Abdullah Turkistani
 
PPT
Lecture 4
Mohammed Saleh
 
PPT
C++ Functions.ppt
WaheedAnwar20
 
PDF
Functionssssssssssssssssssssssssssss.pdf
bodzzaa21
 
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
Functions
PatriciaPabalan
 
Part 3-functions1-120315220356-phpapp01
Abdul Samee
 
Chapter 4
temkin abdlkader
 
User Defined Functions
Praveen M Jigajinni
 
Amit user defined functions xi (2)
Arpit Meena
 
Function C++
Shahzad Afridi
 
Cs1123 8 functions
TAlha MAlik
 
Intro To C++ - Class #19: Functions
Blue Elephant Consulting
 
POLITEKNIK MALAYSIA
Aiman Hud
 
Functions assignment
Ahmad Kamal
 
Introduction to c programming
AMAN ANAND
 
Functions
zeeshan841
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
concept of functions and its types in c++ language
soniasharmafdp
 
Functions in c++
Abdullah Turkistani
 
Lecture 4
Mohammed Saleh
 
C++ Functions.ppt
WaheedAnwar20
 
Functionssssssssssssssssssssssssssss.pdf
bodzzaa21
 
Ad

Recently uploaded (20)

PPTX
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
PPTX
Mining Presentation Underground - Copy.pptx
patallenmoore
 
PPT
Total time management system and it's applications
karunanidhilithesh
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPT
04 Origin of Evinnnnnnnnnnnnnnnnnnnnnnnnnnl-notes.ppt
LuckySangalala1
 
PPTX
Data_Analytics_Presentation_By_Malik_Azanish_Asghar.pptx
azanishmalik1
 
PPTX
EC3551-Transmission lines Demo class .pptx
Mahalakshmiprasannag
 
PDF
monopile foundation seminar topic for civil engineering students
Ahina5
 
PPTX
drones for disaster prevention response.pptx
NawrasShatnawi1
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPTX
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
PPTX
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
PDF
PRIZ Academy - Change Flow Thinking Master Change with Confidence.pdf
PRIZ Guru
 
PDF
Detailed manufacturing Engineering and technology notes
VIKKYsing
 
PDF
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
PDF
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
PDF
Number Theory practice session 25.05.2025.pdf
DrStephenStrange4
 
PDF
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
Mining Presentation Underground - Copy.pptx
patallenmoore
 
Total time management system and it's applications
karunanidhilithesh
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
04 Origin of Evinnnnnnnnnnnnnnnnnnnnnnnnnnl-notes.ppt
LuckySangalala1
 
Data_Analytics_Presentation_By_Malik_Azanish_Asghar.pptx
azanishmalik1
 
EC3551-Transmission lines Demo class .pptx
Mahalakshmiprasannag
 
monopile foundation seminar topic for civil engineering students
Ahina5
 
drones for disaster prevention response.pptx
NawrasShatnawi1
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Statistical Data Analysis Using SPSS Software
shrikrishna kesharwani
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
Electron Beam Machining for Production Process
Rajshahi University of Engineering & Technology(RUET), Bangladesh
 
ISO/IEC JTC 1/WG 9 (MAR) Convenor Report
Kurata Takeshi
 
PRIZ Academy - Change Flow Thinking Master Change with Confidence.pdf
PRIZ Guru
 
Detailed manufacturing Engineering and technology notes
VIKKYsing
 
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
UNIT-4-FEEDBACK AMPLIFIERS AND OSCILLATORS (1).pdf
Sridhar191373
 
Number Theory practice session 25.05.2025.pdf
DrStephenStrange4
 
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
Ad

C++ Functions

  • 2. Main () function C++ functions are a group of statements in a single logical unit to perform some specific task. #include <iostream> using namespace std; int main () { cout << "Hello world!"; return 0; } Structure of main () function Function Header Return type In this case, integer Function_name, main Argument/s ( ) In this case, void Entry Point, Curly braces Exit Point, Curly braces Return statement Function Body Statement 1… Statement 2… …………….. Note: main () structure defined above extends for all functions
  • 3. Defining a function The function header and body together are referred to as the function definition. A function cannot execute until it is first defined. Once defined, a function executes when it is called. #include <iostream> using namespace std; // begins definition of printMessage function void printMessage (void) { // Statements cout << "Hello world!"; // return; } // ends definition of printMessage function int main () { printMessage(); // calls printMessage function return 0; } Function Definition User-defined function (Header) No return Value Function_name No arguments/parameters Or simply ( ) Function body Main Function #include <iostream> using namespace std; void printMessage (void) { cout << "Hello world!"; return; //It makes no difference } int main () { printMessage(); // calls printMessage function return 0; } Code Output
  • 4. Calling a function A function must be defined first, before it can be called. Unless a function is called, it lies dormant with in the program. A function can be called from with in main function (or any other function) followed by a semicolon. { function_name(); } #include <iostream> using namespace std; void sum () { int a,b; cout << "Addition of 2 numbers!n"; cout << "Enter the 2 numbers...n"; cin >> a >> b; cout << a << " + " << b << " = " << a + b; return; } int main () { sum(); // calls sum() function return 0; } Code Output/s User Defined Function Function Header No return value Function_name Function arguments (none) Function Body Main () Function Function being called from main() body. A function is called by its name followed by a semicolon
  • 5. Order of Execution for a Multi-function program The order of execution is as follows: 1. Execution always starts with the main function. 2. The first statement in main, printMessage(), is executed. 3. Execution next shifts to the printMessage function, and begins with the first statement in that function, which outputs “Hello world!” 4. After the printMessage function completes executing, execution returns to the main function with the next unexecuted statement, return 0, which completes the main function.
  • 6. Function Prototyping A function prototype is a function declaration that specifies the data types of its arguments in the parameter list. The compiler uses the information in a function prototype to verify it later when it is defined. #include <iostream> using namespace std; int main () { printMessage(); // calls printMessage function return 0; } void printMessage (void) { cout << "Hello world!"; return; } Code •Since Execution always begins from main(), why isn’t it placed in the beginning of program syntax as shown in the code on the left? •However If we run this code, the compiler gives an error “undeclared identifier”. •The reason being that since compiler runs from top to bottom & always executes from the main (), as it encounters the printmessage() function call, it generates error. Because it must already know of the function’s name, return type, & arguments. •The preferred solution is to prototype every function (except main ofcourse). •After prototyping (typing function header followed by ;) above the main function!The program runs just fine.! •Output: •But why should we prototype? void printMessage (void); //function prototype
  • 7. Scope of a variable Local Variables So far all variables have been defined within main function. In programs where the only function is main, those variables can be accessed throughout the entire program since main is the entire program. However, once we start dividing up the code into separate functions, issues arise.
  • 8. •The portion of the program where an identifier can be used is known as its scope. For example, when we declare a local variable in a block, it can be referenced only in that block and in blocks nested within that block. •The life of a local variable ends (It is destroyed) when the function exits. LocalVariable #include <iostream> using namespace std; void test(); Function Prototype( indicates there is 1 function besides main) int main() { // local variable to main() int var = 5; Variable defined in the locality of main test(); Function Call // illegal: var1 not declared inside main() var1 = 9; // error – undefined identifier } void test() { // local variable to test() int var1; var1 = 6; // illegal: var not declared inside test() cout << var; //error – undefined identifier } Main Function Test Function
  • 9. •The portion of the program where an identifier can be used is known as its scope. However if a variable is declared above all functions & their prototypes, then that variable scopes to the whole of the program. •It is accessible anywhere through out the program. •The life of a local variable ends (It is destroyed) when the program itself exits. GlobalVariable #include <iostream> using namespace std; // Global variable declaration int c = 12; void test(); int main() { ++c; // global variable(accessible) // Outputs 13 cout << c <<endl; test(); return 0; } void test() { ++c; // global variable (accessible) // Outputs 14 cout << c; } GlobalVariable (Variable identified by all function throughout the program.) Function Call
  • 10. So far, we have passed none arguments to the function. Hence we used void function_name (void) type. Sending Information to a function There are 2 methods for passing arguments! • Passing by reference. (It makes use of addresses & pointers), Thus we will study it later. • Passing by value. In this method, a value (in constant or variable form) is passed as an argument to the function, It then manipulates it according to program. • OUTPUT: #include <iostream> #include <cmath> // Math function Library using namespace std; // standard namespace void circle (double); // function prototype (only data-types) double PI = 3.1415; // Global Variable int main() // Main () Header { // Main () body entry brace double rad; // Local variable (rad) cout << "Solving for the circumference “ << "& Area of the Circle." << endl; cout << "...............................n"; cout << "Enter the radius! n"; cin >> rad; // Initializing the local variable (rad) cout << "...............................n"; circle(rad); // Passing the value to circle() as argument return 0; // Program exit code } // Main () body exit brace void circle (double r) // circle () Header with one double type argument { // circle () body entry brace cout << "Circumference of circle = " << 2*PI*r << endl; // Circumference displayed cout << "Area of the circle = " << PI * pow(r,2) << endl; // pow(r,2) is builtin function from math lib return; } // circle () body exit brace
  • 11. Sending Multiple Arguments to a function #include <iostream> using namespace std; // standard namespace void rectangle (double, double); // function prototype (only data-types) int main() // Main () Header { // Main () body entry brace double len,wid; // Local variables(len,wid) cout << "Solving for the Perimeter " << "& Area of the rectangle." << endl; cout << "...............................n"; cout << "Enter the Length & width values! n"; cin >> len >> wid; // Initializing the local variables cout << "...............................n"; rectangle(len,wid); // Passing the values to rectangle() as arguments return 0; // Program exit code } // Main () body exit brace void rectangle (double l,double w) // rectangle () Header { // rectangle () body entry brace cout << "Perimeter of rectangle = " << 2*(l+w) << endl; // Perimeter displayed cout << "Area of the circle = " << l*w << endl; // Area displayed return; } // rectangle () body exit brace A function can receive multiple arguments as well. e.g. 1. rectangle(len,wid); 2. rectangle(14.5,78); 3. sum(3,4,6); 4. Avg(num1,num2,………..num_n)
  • 12. ReturnValue from a function #include <iostream> using namespace std; double Avg (double,double,double); //function prototype int main() // main () header { double a,b,c; // Local variables to main() cout << "Solving for Average of 3 numbers!" << endl << "Enter the 3 numbers!n"; cin >> a >> b >> c; // Local var initialization double ans = Avg(a,b,c); // function call with a return value // stored in double variable ans cout << "Answer = "<< ans; // display ans } double Avg (double n1,double n2,double n3) // Avg function header { return (n1+n2+n3)/3; // return statement for Avg() }
  • 14. Types of Function Calling 1 Accepting Parameter and Returning Value 2 Accepting Parameter and not Returning Value
  • 15. Types of Function Calling (Continued) 4 Not Accepting Parameter & not Returning Value 3 Not Accepting Parameter but Returning Value

Editor's Notes

  • #4: Let’s take our “Hello World” example and divide the code into two functions, main and a printMessage function that outputs “Hello world!” The body of the printMessage function has one statement, which outputs “Hello world!” The function body does not need to contain an explicit return statement because, since the return type is void, the return statement is implied. However, you may include an explicit return statement.