Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
C++ FunctionsC++ Functions
22
AgendaAgenda
 What is a function?What is a function?
 Types of C++Types of C++
functions:functions:
 Standard functionsStandard functions
 User-defined functionsUser-defined functions
 C++ function structureC++ function structure
 Function signatureFunction signature
 Function bodyFunction body
 Declaring andDeclaring and
Implementing C++Implementing C++
functionsfunctions
 Sharing data amongSharing data among
functions throughfunctions through
function parametersfunction parameters
 Value parametersValue parameters
 Reference parametersReference parameters
 Const referenceConst reference
parametersparameters
 Scope of variablesScope of variables
 Local VariablesLocal Variables
 Global variableGlobal variable
33
Functions and subprogramsFunctions and subprograms
 The Top-down design appeoach is based on dividing theThe Top-down design appeoach is based on dividing the
main problem into smaller tasks which may be dividedmain problem into smaller tasks which may be divided
into simpler tasks, then implementing each simple taskinto simpler tasks, then implementing each simple task
by a subprogram or a functionby a subprogram or a function
 A C++ function or a subprogram is simply a chunk of C+A C++ function or a subprogram is simply a chunk of C+
+ code that has+ code that has
 A descriptive function name, e.g.A descriptive function name, e.g.
 computeTaxescomputeTaxes to compute the taxes for an employeeto compute the taxes for an employee
 isPrimeisPrime to check whether or not a number is a prime numberto check whether or not a number is a prime number
 A returning valueA returning value
 The cThe computeTaxesomputeTaxes function may return with a double numberfunction may return with a double number
representing the amount of taxesrepresenting the amount of taxes
 TheThe isPrimeisPrime function may return with a Boolean value (true or false)function may return with a Boolean value (true or false)
44
C++ Standard FunctionsC++ Standard Functions
 C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions
which are known as standard functionswhich are known as standard functions
 These standard functions are groups in differentThese standard functions are groups in different
libraries which can be included in the C++libraries which can be included in the C++
program, e.g.program, e.g.
 Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library
 Character-manipulation functions are declared inCharacter-manipulation functions are declared in
<ctype.h> library<ctype.h> library
 C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries,
some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h>
and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain
hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>

Recommended for you

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++

It tells about functions in C++,Types,Use,prototype,declaration,Arguments etc function with A function with no parameter and no return value A function with parameter and no return value A function with parameter and return value A function without parameter and return value Call by value and address

 
by LPU
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++

Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it DO NOT affect the source variable. In call by value method, the called function creates its own copies of original values sent to it. Any changes, that are made, occur on the function’s copy of values and are not reflected back to the calling function.

c++tutorialprogramming
Functions in C++
Functions in C++Functions in C++
Functions in C++

This document provides an outline and overview of functions in C++. It discusses: - The definition of a function as a block of code that performs a specific task and can be called from other parts of the program. - The standard library that is included in C++ and provides useful tools like containers, iterators, algorithms and more. - The parts of a function definition including the return type, name, parameters, and body. - How to declare functions, call functions by passing arguments, and how arguments are handled. - Scope rules for local and global variables as they relate to functions.

55
Example of UsingExample of Using
Standard C++ Math FunctionsStandard C++ Math Functions
#include <iostream.h>#include <iostream.h>
#include <math.h>#include <math.h>
void main()void main()
{{
// Getting a double value// Getting a double value
double x;double x;
cout << "Please enter a real number: ";cout << "Please enter a real number: ";
cin >> x;cin >> x;
// Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl;
}}
66
Example of UsingExample of Using
Standard C++ Character FunctionsStandard C++ Character Functions
#include <iostream.h> // input/output handling#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions#include <ctype.h> // character type functions
void main()void main()
{{
char ch;char ch;
cout << "Enter a character: ";cout << "Enter a character: ";
cin >> ch;cin >> ch;
cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
if (isdigit(ch))if (isdigit(ch))
cout << "'" << ch <<"' is a digit!n";cout << "'" << ch <<"' is a digit!n";
elseelse
cout << "'" << ch <<"' is NOT a digit!n";cout << "'" << ch <<"' is NOT a digit!n";
}}
Explicit casting
77
User-Defined C++ FunctionsUser-Defined C++ Functions
 Although C++ is shipped with a lot of standardAlthough C++ is shipped with a lot of standard
functions, these functions are not enough for allfunctions, these functions are not enough for all
users, therefore, C++ provides its users with ausers, therefore, C++ provides its users with a
way to define their own functions (or user-way to define their own functions (or user-
defined function)defined function)
 For example, the <math.h> library does notFor example, the <math.h> library does not
include a standard function that allows users toinclude a standard function that allows users to
round a real number to the iround a real number to the ithth
digits, therefore, wedigits, therefore, we
must declare and implement this functionmust declare and implement this function
ourselvesourselves
88
How to define a C++ Function?How to define a C++ Function?
 Generally speaking, we define a C++Generally speaking, we define a C++
function in two steps (preferably but notfunction in two steps (preferably but not
mandatory)mandatory)
Step #1 – declare theStep #1 – declare the function signaturefunction signature inin
either a header file (.h file) or before the maineither a header file (.h file) or before the main
function of the programfunction of the program
Step #2 – Implement the function in either anStep #2 – Implement the function in either an
implementation file (.cpp) or after the mainimplementation file (.cpp) or after the main
functionfunction

Recommended for you

Functions in C++
Functions in C++Functions in C++
Functions in C++

C++ functions require prototypes that specify the return type and parameters. Function overloading allows multiple functions to have the same name but different signatures. Default arguments allow functions to be called without providing trailing arguments. Inline functions expand the function body at the call site for small functions to reduce overhead compared to regular function calls.

default argumentfunction overloadinginline function
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT

This document discusses functions in C++. It defines what a function is and explains that functions are the building blocks of C++ programs. Functions allow code to be reused, making programs easier to code, modify and maintain. The document covers function definitions, declarations, calls, parameters, return types, scope, and overloading. It also discusses local and global variables as well as pass by value and pass by reference.

Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)

Look at brief notes of Function Overloading.You can view tutorialfocus.net to get complete explanation of topic with its programs.

tutorialfocus.netfunction overloadingc++
99
What is The Syntactic Structure ofWhat is The Syntactic Structure of
a C++ Function?a C++ Function?
 A C++ function consists of two partsA C++ function consists of two parts
The function header, andThe function header, and
The function bodyThe function body
 The function header has the followingThe function header has the following
syntaxsyntax
<return value> <name> (<parameter list>)<return value> <name> (<parameter list>)
 The function body is simply a C++ codeThe function body is simply a C++ code
enclosed between { }enclosed between { }
1010
Example of User-definedExample of User-defined
C++ FunctionC++ Function
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
1111
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
Example of User-definedExample of User-defined
C++ FunctionC++ Function
Function
header
1212
Example of User-definedExample of User-defined
C++ FunctionC++ Function
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
Function
header
Function
body

Recommended for you

03 function overloading
03 function overloading03 function overloading
03 function overloading

If any class have multiple functions with same names but different parameters then they are said to be overloaded. Function overloading allows you to use the same name for different functions, to perform, either same or different functions in the same class. If you have to perform one single operation but with different number or types of arguments, then you can simply overload the function.

c++programmingconcepts of object oriented programming
Chapter 5
Chapter 5Chapter 5
Chapter 5

Functions allow programmers to organize code into reusable blocks. There are three main types of functions: library functions, user-defined functions, and main(). Functions can return values and take parameters. Parameters can be passed by value, reference using an alias, or reference using pointers. Passing by value copies the values, while passing by reference or pointer passes the actual arguments so any changes made in the function also change the original variables. Well-defined functions promote code reuse and modular programming.

Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++

This document discusses references and reference parameters in C++. It explains that call by reference allows a function to directly access and modify the original argument, unlike call by value where only a copy is passed. A reference parameter creates an alias for the argument, allowing changes to affect the original. The document provides examples demonstrating pass by value versus pass by reference using reference parameters, and also covers default arguments, reference initialization requirements, and function overloading.

1313
Function SignatureFunction Signature
 The function signature is actually similar toThe function signature is actually similar to
the function header except in two aspects:the function header except in two aspects:
The parameters’ names may not be specifiedThe parameters’ names may not be specified
in the function signaturein the function signature
The function signature must be ended by aThe function signature must be ended by a
semicolonsemicolon
 ExampleExample
double computeTaxes(double) ;double computeTaxes(double) ;
Unnamed
Parameter
Semicolon
;
1414
Why Do We Need FunctionWhy Do We Need Function
Signature?Signature?
 For Information HidingFor Information Hiding
 If you want to create your own library and share it withIf you want to create your own library and share it with
your customers without letting them know theyour customers without letting them know the
implementation details, you should declare all theimplementation details, you should declare all the
function signatures in a header (.h) file and distributefunction signatures in a header (.h) file and distribute
the binary code of the implementation filethe binary code of the implementation file
 For Function AbstractionFor Function Abstraction
 By only sharing the function signatures, we have theBy only sharing the function signatures, we have the
liberty to change the implementation details from timeliberty to change the implementation details from time
to time toto time to
 Improve function performanceImprove function performance
 make the customers focus on the purpose of the function, notmake the customers focus on the purpose of the function, not
its implementationits implementation
1515
ExampleExample
#include <iostream>#include <iostream>
#include <string>#include <string>
using namespace std;using namespace std;
// Function Signature// Function Signature
double getIncome(string);double getIncome(string);
double computeTaxes(double);double computeTaxes(double);
void printTaxes(double);void printTaxes(double);
void main()void main()
{{
// Get the income;// Get the income;
double income = getIncome("Please enterdouble income = getIncome("Please enter
the employee income: ");the employee income: ");
// Compute Taxes// Compute Taxes
double taxes = computeTaxes(income);double taxes = computeTaxes(income);
// Print employee taxes// Print employee taxes
printTaxes(taxes);printTaxes(taxes);
}}
double computeTaxes(double income)double computeTaxes(double income)
{{
if (income<5000) return 0.0;if (income<5000) return 0.0;
return 0.07*(income-5000.0);return 0.07*(income-5000.0);
}}
double getIncome(string prompt)double getIncome(string prompt)
{{
cout << prompt;cout << prompt;
double income;double income;
cin >> income;cin >> income;
return income;return income;
}}
void printTaxes(double taxes)void printTaxes(double taxes)
{{
cout << "The taxes is $" << taxes << endl;cout << "The taxes is $" << taxes << endl;
}}
1616
Building Your LibrariesBuilding Your Libraries
 It is a good practice to build libraries to beIt is a good practice to build libraries to be
used by you and your customersused by you and your customers
 In order to build C++ libraries, you shouldIn order to build C++ libraries, you should
be familiar withbe familiar with
How to create header files to store functionHow to create header files to store function
signaturessignatures
How to create implementation files to storeHow to create implementation files to store
function implementationsfunction implementations
How to include the header file to yourHow to include the header file to your
program to use your user-defined functionsprogram to use your user-defined functions

Recommended for you

Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C

The document discusses functions and recursion in C programming. It provides examples of different types of functions like void, float, int functions. It demonstrates simple functions with no parameters, functions that return values, and functions with parameters. It also explains recursion with examples of calculating factorials and Fibonacci series recursively. Finally, it discusses other function related concepts like function prototypes, scope of variables, and pre-defined math functions in C.

functionsrecursionc
Functions in C++
Functions in C++Functions in C++
Functions in C++

this presentation has a brief discussion about the Functions in C++, with respect to the Object oriented point of view.

c++object oriented programming in c++functions
Functions in c++
Functions in c++Functions in c++
Functions in c++

Functions allow programmers to structure C++ programs into modular segments of code to perform individual tasks. There are two types of functions: library functions and user-defined functions. User-defined functions are defined using a return type, function name, and parameters. Functions can be called by value or by reference and can also be inline, recursive, or friend functions.

1717
C++ Header FilesC++ Header Files
 The C++ header files must have .hThe C++ header files must have .h
extension and should have the followingextension and should have the following
structurestructure
#ifndef compiler directive#ifndef compiler directive
#define compiler directive#define compiler directive
May include some other header filesMay include some other header files
All functions signatures with some commentsAll functions signatures with some comments
about their purposes, their inputs, and outputsabout their purposes, their inputs, and outputs
#endif compiler directive#endif compiler directive
1818
TaxesRules Header fileTaxesRules Header file
#ifndef _TAXES_RULES_#ifndef _TAXES_RULES_
#define _TAXES_RULES_#define _TAXES_RULES_
#include <iostream>#include <iostream>
#include <string>#include <string>
using namespace std;using namespace std;
double getIncome(string);double getIncome(string);
// purpose -- to get the employee// purpose -- to get the employee
incomeincome
// input -- a string prompt to be// input -- a string prompt to be
displayed to the userdisplayed to the user
// output -- a double value// output -- a double value
representing the incomerepresenting the income
double computeTaxes(double);double computeTaxes(double);
// purpose -- to compute the taxes for// purpose -- to compute the taxes for
a given incomea given income
// input -- a double value// input -- a double value
representing the incomerepresenting the income
// output -- a double value// output -- a double value
representing the taxesrepresenting the taxes
void printTaxes(double);void printTaxes(double);
// purpose -- to display taxes to the// purpose -- to display taxes to the
useruser
// input -- a double value// input -- a double value
representing the taxesrepresenting the taxes
// output -- None// output -- None
#endif#endif
1919
TaxesRules Implementation FileTaxesRules Implementation File
#include "TaxesRules.h"#include "TaxesRules.h"
double computeTaxes(doubledouble computeTaxes(double
income)income)
{{
if (income<5000) return 0.0;if (income<5000) return 0.0;
return 0.07*(income-5000.0);return 0.07*(income-5000.0);
}}
double getIncome(string prompt)double getIncome(string prompt)
{{
cout << prompt;cout << prompt;
double income;double income;
cin >> income;cin >> income;
return income;return income;
}}
void printTaxes(double taxes)void printTaxes(double taxes)
{{
cout << "The taxes is $" << taxescout << "The taxes is $" << taxes
<< endl;<< endl;
}}
2020
Main Program FileMain Program File
#include "TaxesRules.h"#include "TaxesRules.h"
void main()void main()
{{
// Get the income;// Get the income;
double income =double income =
getIncome("Please enter the employee income: ");getIncome("Please enter the employee income: ");
// Compute Taxes// Compute Taxes
double taxes = computeTaxes(income);double taxes = computeTaxes(income);
// Print employee taxes// Print employee taxes
printTaxes(taxes);printTaxes(taxes);
}}

Recommended for you

C++ Function
C++ FunctionC++ Function
C++ Function

This document discusses various aspects of functions in C++ including function prototypes, definitions, calls, overloading, pointers, callbacks, and templates. It provides examples and explanations of each concept. The key topics covered are: - Function prototypes declare a function's name, return type, and parameters. - Definitions implement what a function does through code within curly braces. - Functions are called by name with appropriate arguments. - Overloading allows different functions to have the same name based on different parameters. - Function pointers allow functions to be passed as arguments to other functions. - Callback functions are functions that are passed as arguments to be called later. - Templates define functions that operate on different data

functionc++
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c

This document discusses parameters in C++. There are two types of parameters: formal parameters defined in a function and actual parameters passed during a function call. C++ supports two ways of passing parameters: call by value where the formal parameter is a copy of the actual value, and call by reference where the formal parameter is an alias to the actual parameter. Call by reference allows a function to modify the original value. While it is more efficient for large data types, it can be ambiguous whether a parameter is intended for input or output.

programmingc language
Call by value
Call by valueCall by value
Call by value

The document discusses call by value and call by reference in functions. Call by value passes the actual value of an argument to the formal parameter, so any changes made to the formal parameter do not affect the actual argument. Call by reference passes the address of the actual argument, so changes to the formal parameter do directly modify the actual argument. An example program demonstrates call by value, where changing the formal parameter does not change the original variable.

2121
Inline FunctionsInline Functions
 Sometimes, we use the keywordSometimes, we use the keyword inlineinline to defineto define
user-defined functionsuser-defined functions
 Inline functions are very small functions, generally,Inline functions are very small functions, generally,
one or two lines of codeone or two lines of code
 Inline functions are very fast functions compared toInline functions are very fast functions compared to
the functions declared without the inline keywordthe functions declared without the inline keyword
 ExampleExample
inlineinline double degrees( double radian)double degrees( double radian)
{{
return radian * 180.0 / 3.1415;return radian * 180.0 / 3.1415;
}}
2222
Example #1Example #1
 Write a function to test if a number is anWrite a function to test if a number is an
odd numberodd number
inline bool odd (int x)inline bool odd (int x)
{{
return (x % 2 == 1);return (x % 2 == 1);
}}
2323
Example #2Example #2
 Write a function to compute the distanceWrite a function to compute the distance
between two points (x1, y1) and (x2, y2)between two points (x1, y1) and (x2, y2)
Inline double distance (double x1, double y1,Inline double distance (double x1, double y1,
double x2, double y2)double x2, double y2)
{{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}}
2424
Example #3Example #3
 Write a function to compute n!Write a function to compute n!
int factorial( int n)int factorial( int n)
{{
int product=1;int product=1;
for (int i=1; i<=n; i++) product *= i;for (int i=1; i<=n; i++) product *= i;
return product;return product;
}}

Recommended for you

Functions
FunctionsFunctions
Functions

The document discusses functions in C++. It covers standard and user-defined functions, value-returning and void functions, formal and actual parameters, and how to define, declare, and call functions. It also discusses scope of identifiers, value vs reference parameters, function overloading, and functions with default parameters.

C++ functions
C++ functionsC++ functions
C++ functions

This document discusses C++ functions. It begins by defining what a function is and describing standard and user-defined functions. It then covers the structure of C++ functions including the function signature, parameters, return values, and body. Examples are provided of defining, declaring, calling and overloading functions. The document also discusses scope of variables, passing data between functions, and inline functions.

c++functionsc++clanguage
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)

C++ arrays allow storing a fixed number of elements of the same type sequentially in memory. Arrays are declared by specifying the element type and number, such as int numbers[100]. Individual elements can then be accessed via their index like numbers[0]. Arrays can be initialized with a list of values or left uninitialized. Elements are accessed using their index and the array name, like n[5] to get the 6th element.

programmingc++ programming (array)arrays
2525
Example #4Example #4
Function OverloadingFunction Overloading
 Write functions to return with the maximum number ofWrite functions to return with the maximum number of
two numberstwo numbers
inline int max( int x, int y)inline int max( int x, int y)
{{
if (x>y) return x; else return y;if (x>y) return x; else return y;
}}
inline double max( double x, double y)inline double max( double x, double y)
{{
if (x>y) return x; else return y;if (x>y) return x; else return y;
}}
An overloaded
function is a
function that is
defined more than
once with different
data types or
different number
of parameters
2626
Sharing Data AmongSharing Data Among
User-Defined FunctionsUser-Defined Functions
There are two ways to share dataThere are two ways to share data
among different functionsamong different functions
Using global variables (very bad practice!)Using global variables (very bad practice!)
Passing data through function parametersPassing data through function parameters
Value parametersValue parameters
Reference parametersReference parameters
Constant reference parametersConstant reference parameters
2727
C++ VariablesC++ Variables
 A variable is a place in memory that hasA variable is a place in memory that has
 A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.)
 A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.)
 A size (number of bytes)A size (number of bytes)
 A scope (the part of the program code that can use it)A scope (the part of the program code that can use it)
 Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it
 Local variables – only the function that declare localLocal variables – only the function that declare local
variables see and use these variablesvariables see and use these variables
 A life time (the duration of its existence)A life time (the duration of its existence)
 Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed
 Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define
these variables are executedthese variables are executed
2828
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}

Recommended for you

Functions in C++
Functions in C++Functions in C++
Functions in C++

The document discusses functions in C++. It begins by outlining key topics about functions that will be covered, such as function definitions, standard library functions, and function calls. It then provides details on defining and calling functions, including specifying return types, parameters, function prototypes, scope rules, and passing arguments by value or reference. The document also discusses local and global variables, function errors, and the differences between calling functions by value or reference.

computer sciencec++functions
Function C++
Function C++ Function C++
Function C++

This document discusses functions in C++. It defines a function as a block of code that performs a specific task and can be reused. The key points made are: - Functions allow for modular and reusable code. They group statements and give them a name to be called from other parts of a program. - The document demonstrates simple functions in C++ through examples, including defining, declaring, calling, passing arguments to, and returning values from functions. - Other function concepts covered include function overloading, recursion, inline functions, default arguments, scope and storage class, and global vs local variables.

Array in c++
Array in c++Array in c++
Array in c++

- An array is a collection of consecutive memory locations that all have the same name and type. An array allows storing multiple values of the same type using a single name. - Arrays in C++ must be declared before use, specifying the type, name, and number of elements. Elements are accessed using an index. - The main advantages of arrays are that they allow storing and processing large numbers of values efficiently using a single name. Arrays also make sorting and searching values easier.

2929
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x 0
3030
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
3131
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
2
4
3232
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
3
void f1()void f1()
{{
x++;x++;
}}
4

Recommended for you

C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES

The document contains C++ code examples for performing common matrix operations using 2D arrays, including summing and subtracting matrices, finding the transpose of a matrix, multiplying 2x2 matrices, and calculating the inverse of a 2x2 matrix. It prompts the user for matrix inputs, performs the selected operation on the matrices, and outputs the results.

array
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)

View C++ notes of Friend function here. To get Detailed knowledge of Friend Function visit tutorialfocus.net where you can also download it.

tutorialfocus.netc++ tutorialfriend function
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer

The document discusses arrays and pointers in C++. It covers: - How to declare and initialize arrays - Accessing array elements using subscripts - Using parallel arrays when subscripts are not sequential numbers - Special considerations for strings as arrays of characters - Declaring pointer variables and using pointers to access array elements - Potential issues with pointers like dangling references

3333
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
3
void f1()void f1()
{{
x++;x++;
}}5
3434
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}6
3535
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
7
3636
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}8

Recommended for you

functions of C++
functions of C++functions of C++
functions of C++

The document contains information about Tarandeep Kaur, including her name, section, and roll number. It then lists and describes various topics related to functions in C++, including definition of functions, function calling, function prototypes, void functions, local vs global variables, function overloading, and recursion. Examples are provided to illustrate function calling, passing arguments, return values, and differences between call by value and call by reference.

power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts

The document discusses C++ functions. It covers the following key points in 3 sentences: Standard functions that are included with C++ like math functions are discussed as well as how to define user-defined functions. User-defined functions are defined with a function header, parameters, and body. Functions can share data through parameters, either by value or by reference, and variables can have local or global scope.

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt

thsi describe how to use functions in C++ and types of functions aviable in c++.In this we discuss different types of function calls

functionscall by value
3737
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
3838
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
3939
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
0x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
1
The inline keyword
instructs the compiler
to replace the function
call with the function
body!
4040
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
4x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
2

Recommended for you

C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT

C++ is an object-oriented programming language that was created as an extension of C programming language. It was created by Bjarne Stroustrup in 1979 at Bell Labs. Some key differences between C and C++ include C++ supporting object-oriented programming concepts like classes, inheritance and polymorphism, while C is a procedural language. Pointers and references are commonly used in C++ to pass arguments to functions by reference rather than by value. Arrays and functions are also important elements of C++ programs.

C++
C++C++
C++

C++ is an object-oriented programming language that was created as an extension of C by Bjarne Stroustrup in 1979 at Bell Labs. It supports concepts like inheritance, polymorphism, and encapsulation. C++ is a systems programming language that is commonly used to develop applications that require high performance or require low-level access to hardware. Some key features of C++ include object-oriented programming, functions, arrays, pointers, strings, file handling, and inheritance. C++ allows programmers to write code that is very close to the underlying hardware and has performance advantages over other languages.

unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx

The document discusses functions in C programming. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined standard library functions and user-defined functions. The key aspects of a function are its declaration, definition, and call. Functions can be used to break a large program into smaller, reusable components. Parameters can be passed to functions by value or by reference. Recursion is when a function calls itself, and is used in algorithms like calculating factorials. Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free().

function
4141
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
3
4242
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}4
4343
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
4444
What is Bad About UsingWhat is Bad About Using
Global Vairables?Global Vairables?
 Not safe!Not safe!
 If two or more programmers are working together in aIf two or more programmers are working together in a
program, one of them may change the value stored inprogram, one of them may change the value stored in
the global variable without telling the others who maythe global variable without telling the others who may
depend in their calculation on the old stored value!depend in their calculation on the old stored value!
 Against The Principle of Information Hiding!Against The Principle of Information Hiding!
 Exposing the global variables to all functions isExposing the global variables to all functions is
against the principle of information hiding since thisagainst the principle of information hiding since this
gives all functions the freedom to change the valuesgives all functions the freedom to change the values
stored in the global variables at any time (unsafe!)stored in the global variables at any time (unsafe!)

Recommended for you

Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++

The document provides an overview of the C++ programming language. It discusses the history and development of C++, with key points being that C++ was created by Bjarne Stroustrup in 1983 as an extension of C to support object-oriented programming. It then covers some of the main differences between C and C++, uses of C++, advantages and disadvantages, standard libraries, basic C++ structures like data types, variables, operators, functions, arrays, and pointers.

unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx

The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().

cn
Intro to c++
Intro to c++Intro to c++
Intro to c++

This document provides an introduction to C++ programming. It discusses key differences between C and C++, shows simple C++ examples, and covers important C++ concepts like input/output streams, header files, inline functions, references, and reference parameters. The document is intended to teach basic C++ syntax and features to someone new to the language.

4545
Local VariablesLocal Variables
 Local variables are declared inside the functionLocal variables are declared inside the function
body and exist as long as the function is runningbody and exist as long as the function is running
and destroyed when the function exitand destroyed when the function exit
 You have to initialize the local variable beforeYou have to initialize the local variable before
using itusing it
 If a function defines a local variable and thereIf a function defines a local variable and there
was a global variable with the same name, thewas a global variable with the same name, the
function uses its local variable instead of usingfunction uses its local variable instead of using
the global variablethe global variable
4646
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
4747
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 0
Global variables are
automatically initialized to 0
4848
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
1

Recommended for you

cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx

C++ is an object-oriented programming language that was created as an extension of C programming language. It was created by Bjarne Stroustrup in 1979 at Bell Labs. Some key features of C++ include support for object-oriented programming concepts like inheritance, polymorphism, and encapsulation. C++ also supports functions, arrays, pointers, and file handling. It is commonly used for system software, drivers, servers, and applications like video games.

Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment

Here is the class Book with the requested attributes and member functions: #include <iostream> using namespace std; class Book { private: string title; string author; string publisher; float price; public: Book() { title = "No title"; author = "No author"; publisher = "No publisher"; price = 0.0; } void display_data() { cout << "Title: " << title << endl; cout << "Author: " << author << endl; cout << "Publisher: " << publisher << endl; cout << "Price: " << price << endl; }

bcsl 031 solve assignment
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes

C++ is an object-oriented programming language that was created as an extension of C programming language. Some key points: - C++ was created by Bjarne Stroustrup starting in 1979 at Bell Labs to support object-oriented programming. It was initially called C with Classes but later renamed to C++. - C++ supports concepts like classes, inheritance and dynamic binding that allow object-oriented programming. It also maintains compatibility with C by supporting procedural programming. - C++ is widely used to create system software, drivers, servers, applications and games due to being relatively low-level yet supporting high-level concepts. It has a large community and clear standards.

4949
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x ????
3
5050
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
3
5151
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
4
5252
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
5

Recommended for you

Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming

Fundamental of programming

Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx

This document discusses functions in C++ programming. It begins by explaining the objectives of learning about standard predefined functions, user-defined functions, value-returning functions, and constructing user-defined functions. It then provides examples of user-defined functions for finding the maximum of two numbers, checking if a number is prime, calculating the nth Fibonacci number, and calculating binomial coefficients. It also discusses concepts like function prototypes, parameters, return types, and using functions to break programs into manageable pieces.

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types

Programming Fundamentals Functions in C Lecture Outline • Functions • Function declaration • Function call • Function definition – Passing arguments to function 1) Passing constants 2) Passing variables – Pass by value – Returning values from functions • Preprocessor directives • Local and external variables

programming fundamentals functions in cfunctions in cpreprocessor directives
5353
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
6
5454
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}7
5555
II. Using ParametersII. Using Parameters
 Function Parameters come in threeFunction Parameters come in three
flavors:flavors:
Value parametersValue parameters – which copy the values of– which copy the values of
the function argumentsthe function arguments
Reference parametersReference parameters – which refer to the– which refer to the
function arguments by other local names andfunction arguments by other local names and
have the ability to change the values of thehave the ability to change the values of the
referenced argumentsreferenced arguments
Constant reference parametersConstant reference parameters – similar to– similar to
the reference parameters but cannot changethe reference parameters but cannot change
the values of the referenced argumentsthe values of the referenced arguments
5656
Value ParametersValue Parameters
 This is what we use to declare in the function signature orThis is what we use to declare in the function signature or
function header, e.g.function header, e.g.
int max (int x, int y);int max (int x, int y);
 Here, parameters x and y are value parametersHere, parameters x and y are value parameters
 When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7
are copied to x and y respectivelyare copied to x and y respectively
 When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and
b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively
 When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50
and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively
 Once the value parameters accepted copies of theOnce the value parameters accepted copies of the
corresponding arguments data, they act as localcorresponding arguments data, they act as local
variables!variables!

Recommended for you

c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf

The document provides an overview of key C++ concepts including: - C++ is an extension of C that adds object-oriented features like inheritance, polymorphism, encapsulation and abstraction. - It discusses the differences between C and C++, data types, variables, arrays, strings, functions, and conditionals. - The document concludes with examples of C++ programs and practice questions.

Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1

This document discusses the basic structure of C++ programs. It covers preprocessor directives, header files, the main function, and return statements. It provides examples of a simple Hello World program structure and explains each part. It also lists common C++ header files and their purposes.

Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3

Header files contain function and variable definitions that are imported into C++ programs using the #include statement. Header files have a ".h" extension and declare functions and define macros. When a function is used in a C++ program, its definition must be imported from the library by including the appropriate header file. Common header files provide input/output operations (iostream.h), console input/output (conio.h), formatted I/O (iomanip.h), strings (string.h), mathematics functions (math.h), general purpose functions like memory management (stdlib.h), and random number generation (stdlib.h).

xi-xii unit 3 computer science ppt
5757
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
1
5858
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
3
3
5959
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
3
4
8
6060
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
38
5

Recommended for you

Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3

Header files contain function and variable definitions that are imported into C++ programs using the #include statement. Header files have a ".h" extension and declare functions and define macros. When a function is used in a C++ program, its definition must be imported from the library by including the appropriate header file. Common header files provide input/output operations (iostream.h), console input/output (conio.h), formatted I/O (iomanip.h), strings (string.h), mathematics functions (math.h), general purpose functions like memory management (stdlib.h), and random number generation (stdlib.h).

xi-xii unit 3 computer science ppt
Functions in c++
Functions in c++Functions in c++
Functions in c++

Functions in C++ provide more capabilities than functions in C, including function prototypes, function overloading, default arguments, and operator overloading. Function prototypes allow strong type checking and prevent illegal values from being passed to functions. Function overloading allows multiple functions to have the same name if they have different parameters. Default arguments allow functions to be called without passing all parameters by using default values defined in the function prototype. Operator overloading extends operators like + and - to non-standard data types like strings. Inline functions help reduce function call overhead by inserting the function code directly in the calling code.

c++
C tutorials
C tutorialsC tutorials
C tutorials

C is a general-purpose programming language widely used to develop operating systems and compilers. It was developed in the early 1970s at Bell Labs by Dennis Ritchie. Some key reasons for C's popularity include its efficiency, ability to access low-level hardware, and ability to be compiled on a variety of computers. C source code files use a .c extension and must be compiled into an executable binary file before running. Common uses of C include operating systems, language compilers, databases, and network drivers.

6161
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
6
6262
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}7
6363
Reference ParametersReference Parameters
 As we saw in the last example, any changes inAs we saw in the last example, any changes in
the value parameters don’t affect the originalthe value parameters don’t affect the original
function argumentsfunction arguments
 Sometimes, we want to change the values of theSometimes, we want to change the values of the
original function arguments or return with moreoriginal function arguments or return with more
than one value from the function, in this case wethan one value from the function, in this case we
use reference parametersuse reference parameters
 A reference parameter is just another name to theA reference parameter is just another name to the
original argument variableoriginal argument variable
 We define a reference parameter by adding the & inWe define a reference parameter by adding the & in
front of the parameter name, e.g.front of the parameter name, e.g.
double update (doubledouble update (double && x);x);
6464
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4;int x = 4; // Local variable// Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
1 x? x4

Recommended for you

Information Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIAInformation Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIA

Information Security- Threats and Attacks, Types of Threats,Trespassing, Espionage, Software Attacks, Trojan Horse, Worms,Worm Propagation Model, Virus

information securityvirussoftware attack
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIAMicroprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA

The document discusses protected mode memory addressing in microprocessors. It describes how protected mode allows access to 4GB of memory using 32-bit offsets and segment descriptors. Segment descriptors stored in global and local descriptor tables define memory segment locations, lengths, and access rights. Operating systems like Windows use protected mode and 32-bit environments while DOS uses 16-bit. The microprocessor caches descriptor information from the tables in program-invisible registers associated with segment registers to efficiently access memory segments.

microprocessorglobal descriptorlocal descrriptor
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIAE facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA

This document provides an overview of the various departments, services, and information available on the Municipal Corporation of Delhi website. It lists sections for knowing the corporation, zones/wards/colonies, departments, logins, RTI acts, press/information, advertisements, awards/photos, jobs, downloads, parking management, complaints, tenders, sanitation workers, building plans, contacts, citizen services, general services, hospitals/courts/banks, GIS maps, nursing admissions, reports, attendance, help, and details about the website development and maintenance.

of delhiwebsitee-facilities
6565
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x4
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}
3
6666
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x4
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}
4 9
6767
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x9
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}5
6868
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
6
x? x9

Recommended for you

Matrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIAMatrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIA

1) A matrix is a rectangular array of numbers arranged in rows and columns. The dimensions of a matrix are specified by the number of rows and columns. 2) The inverse of a square matrix A exists if and only if the determinant of A is not equal to 0. The inverse of A, denoted A^-1, is the matrix that satisfies AA^-1 = A^-1A = I, where I is the identity matrix. 3) For two matrices A and B to be inverses, their product must result in the identity matrix regardless of order, i.e. AB = BA = I. This shows that one matrix undoes the effect of the other.

echleon formgauss-jordangauss-elimination
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA

The document discusses recursion and provides examples of recursion including nested recursion. It explains recursion using functions like the Ackermann function and Fibonacci numbers. It discusses excessive recursion and how it can lead to many repeated computations. The document also covers backtracking as a method for systematically trying sequences of decisions to find a solution. It provides the example of solving the eight queens problem using backtracking and recursion.

Heritage and tourism in india by DHEERAJ KATARIA
Heritage and  tourism in india by DHEERAJ KATARIAHeritage and  tourism in india by DHEERAJ KATARIA
Heritage and tourism in india by DHEERAJ KATARIA

Explore the sites to Visit in India And also explore the vast Built Heritage of India Built heritage of India....

heritageindiaplaces to visit in india
6969
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
x? x9
7
7070
Constant Reference ParametersConstant Reference Parameters
 Constant reference parameters are used underConstant reference parameters are used under
the following two conditions:the following two conditions:
 The passed data are so big and you want to saveThe passed data are so big and you want to save
time and computer memorytime and computer memory
 The passed data will not be changed or updated inThe passed data will not be changed or updated in
the function bodythe function body
 For exampleFor example
void report (void report (constconst stringstring && prompt);prompt);
 The only valid arguments accepted by referenceThe only valid arguments accepted by reference
parameters and constant reference parametersparameters and constant reference parameters
are variable namesare variable names
 It is a syntax error to pass constant values orIt is a syntax error to pass constant values or
expressions to the (const) reference parametersexpressions to the (const) reference parameters

More Related Content

What's hot

Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Abdullah Turkistani
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
Amrit Kaur
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
NUST Stuff
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
Aditya Nihal Kumar Singh
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 

What's hot (18)

Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Call by value
Call by valueCall by value
Call by value
 

Viewers also liked

Functions
FunctionsFunctions
Functions
Online
 
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
طارق بالحارث
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
Array in c++
Array in c++Array in c++
Array in c++
Mahesha Mano
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
Farhan Ab Rahman
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
Tareq Hasan
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 

Viewers also liked (10)

Functions
FunctionsFunctions
Functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function C++
Function C++ Function C++
Function C++
 
Array in c++
Array in c++Array in c++
Array in c++
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
 
functions of C++
functions of C++functions of C++
functions of C++
 

Similar to C++ functions presentation by DHEERAJ KATARIA

power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
bhargavi804095
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
kanaka vardhini
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
Thooyavan Venkatachalam
 
C++
C++C++
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
Venkatesh Goud
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
somu rajesh
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
JVenkateshGoud
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
WatchDog13
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
SukhpreetSingh519414
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
LidetAdmassu
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
NoorAntakia
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
imtiazalijoono
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
AnkurSingh656748
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
rohassanie
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
MOHIT TOMAR
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
MOHIT TOMAR
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Srikanth Mylapalli
 
C tutorials
C tutorialsC tutorials
C tutorials
Amit Kapoor
 

Similar to C++ functions presentation by DHEERAJ KATARIA (20)

power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 
Fundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programmingFundamental of programming Fundamental of programming
Fundamental of programming Fundamental of programming
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C tutorials
C tutorialsC tutorials
C tutorials
 

More from Dheeraj Kataria

Information Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIAInformation Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIAMicroprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Dheeraj Kataria
 
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIAE facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
Dheeraj Kataria
 
Matrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIAMatrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIA
Dheeraj Kataria
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
 
Heritage and tourism in india by DHEERAJ KATARIA
Heritage and  tourism in india by DHEERAJ KATARIAHeritage and  tourism in india by DHEERAJ KATARIA
Heritage and tourism in india by DHEERAJ KATARIA
Dheeraj Kataria
 

More from Dheeraj Kataria (6)

Information Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIAInformation Security- Threats and Attacks presentation by DHEERAJ KATARIA
Information Security- Threats and Attacks presentation by DHEERAJ KATARIA
 
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIAMicroprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
Microprocessor Protected Mode Memory addressing By DHEERAJ KATARIA
 
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIAE facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
E facilities of Municipal Corporation of Delhi By DHEERAJ KATARIA
 
Matrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIAMatrix presentation By DHEERAJ KATARIA
Matrix presentation By DHEERAJ KATARIA
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
 
Heritage and tourism in india by DHEERAJ KATARIA
Heritage and  tourism in india by DHEERAJ KATARIAHeritage and  tourism in india by DHEERAJ KATARIA
Heritage and tourism in india by DHEERAJ KATARIA
 

Recently uploaded

Introduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptxIntroduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptx
archanac21
 
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai AvailableMumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
1258strict
 
Application Infrastructure and cloud computing.pdf
Application Infrastructure and cloud computing.pdfApplication Infrastructure and cloud computing.pdf
Application Infrastructure and cloud computing.pdf
Mithun Chakroborty
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
Blesson Easo Varghese
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
maisnampibarel
 
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model SafeBangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
bookhotbebes1
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
IIIT Hyderabad
 
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
aarusi sexy model
 
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
sanabts249
 
Analysis and Design of Algorithm Lab Manual (BCSL404)
Analysis and Design of Algorithm Lab Manual (BCSL404)Analysis and Design of Algorithm Lab Manual (BCSL404)
Analysis and Design of Algorithm Lab Manual (BCSL404)
VishalMore197390
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
pavanaroshni1977
 
How to Manage Internal Notes in Odoo 17 POS
How to Manage Internal Notes in Odoo 17 POSHow to Manage Internal Notes in Odoo 17 POS
How to Manage Internal Notes in Odoo 17 POS
Celine George
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
itssurajthakur06
 
Biology for computer science BBOC407 vtu
Biology for computer science BBOC407 vtuBiology for computer science BBOC407 vtu
Biology for computer science BBOC407 vtu
santoshpatilrao33
 
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen FramesUnblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Sinan KOZAK
 
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
hahehot
 
( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile
butwhat24
 
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and PreventionUnderstanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Bert Blevins
 
Literature Reivew of Student Center Design
Literature Reivew of Student Center DesignLiterature Reivew of Student Center Design
Literature Reivew of Student Center Design
PriyankaKarn3
 
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
IJAEMSJORNAL
 

Recently uploaded (20)

Introduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptxIntroduction to neural network (Module 1).pptx
Introduction to neural network (Module 1).pptx
 
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai AvailableMumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
Mumbai @Call @Girls 🛴 9930687706 🛴 Aaradhaya Best High Class Mumbai Available
 
Application Infrastructure and cloud computing.pdf
Application Infrastructure and cloud computing.pdfApplication Infrastructure and cloud computing.pdf
Application Infrastructure and cloud computing.pdf
 
Quadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and ControlQuadcopter Dynamics, Stability and Control
Quadcopter Dynamics, Stability and Control
 
Development of Chatbot Using AI/ML Technologies
Development of  Chatbot Using AI/ML TechnologiesDevelopment of  Chatbot Using AI/ML Technologies
Development of Chatbot Using AI/ML Technologies
 
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model SafeBangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
Bangalore @ℂall @Girls ꧁❤ 0000000000 ❤꧂@ℂall @Girls Service Vip Top Model Safe
 
Response & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITHResponse & Safe AI at Summer School of AI at IIITH
Response & Safe AI at Summer School of AI at IIITH
 
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model SafePaharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
Paharganj @ℂall @Girls ꧁❤ 9873777170 ❤꧂VIP Arti Singh Top Model Safe
 
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
21CV61- Module 3 (CONSTRUCTION MANAGEMENT AND ENTREPRENEURSHIP.pptx
 
Analysis and Design of Algorithm Lab Manual (BCSL404)
Analysis and Design of Algorithm Lab Manual (BCSL404)Analysis and Design of Algorithm Lab Manual (BCSL404)
Analysis and Design of Algorithm Lab Manual (BCSL404)
 
LeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdfLeetCode Database problems solved using PySpark.pdf
LeetCode Database problems solved using PySpark.pdf
 
How to Manage Internal Notes in Odoo 17 POS
How to Manage Internal Notes in Odoo 17 POSHow to Manage Internal Notes in Odoo 17 POS
How to Manage Internal Notes in Odoo 17 POS
 
PMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOCPMSM-Motor-Control : A research about FOC
PMSM-Motor-Control : A research about FOC
 
Biology for computer science BBOC407 vtu
Biology for computer science BBOC407 vtuBiology for computer science BBOC407 vtu
Biology for computer science BBOC407 vtu
 
Unblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen FramesUnblocking The Main Thread - Solving ANRs and Frozen Frames
Unblocking The Main Thread - Solving ANRs and Frozen Frames
 
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
一比一原版(skku毕业证)韩国成均馆大学毕业证如何办理
 
( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile( Call  ) Girls Noida 9873940964 High Profile
( Call  ) Girls Noida 9873940964 High Profile
 
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and PreventionUnderstanding Cybersecurity Breaches: Causes, Consequences, and Prevention
Understanding Cybersecurity Breaches: Causes, Consequences, and Prevention
 
Literature Reivew of Student Center Design
Literature Reivew of Student Center DesignLiterature Reivew of Student Center Design
Literature Reivew of Student Center Design
 
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
Profiling of Cafe Business in Talavera, Nueva Ecija: A Basis for Development ...
 

C++ functions presentation by DHEERAJ KATARIA

  • 2. 22 AgendaAgenda  What is a function?What is a function?  Types of C++Types of C++ functions:functions:  Standard functionsStandard functions  User-defined functionsUser-defined functions  C++ function structureC++ function structure  Function signatureFunction signature  Function bodyFunction body  Declaring andDeclaring and Implementing C++Implementing C++ functionsfunctions  Sharing data amongSharing data among functions throughfunctions through function parametersfunction parameters  Value parametersValue parameters  Reference parametersReference parameters  Const referenceConst reference parametersparameters  Scope of variablesScope of variables  Local VariablesLocal Variables  Global variableGlobal variable
  • 3. 33 Functions and subprogramsFunctions and subprograms  The Top-down design appeoach is based on dividing theThe Top-down design appeoach is based on dividing the main problem into smaller tasks which may be dividedmain problem into smaller tasks which may be divided into simpler tasks, then implementing each simple taskinto simpler tasks, then implementing each simple task by a subprogram or a functionby a subprogram or a function  A C++ function or a subprogram is simply a chunk of C+A C++ function or a subprogram is simply a chunk of C+ + code that has+ code that has  A descriptive function name, e.g.A descriptive function name, e.g.  computeTaxescomputeTaxes to compute the taxes for an employeeto compute the taxes for an employee  isPrimeisPrime to check whether or not a number is a prime numberto check whether or not a number is a prime number  A returning valueA returning value  The cThe computeTaxesomputeTaxes function may return with a double numberfunction may return with a double number representing the amount of taxesrepresenting the amount of taxes  TheThe isPrimeisPrime function may return with a Boolean value (true or false)function may return with a Boolean value (true or false)
  • 4. 44 C++ Standard FunctionsC++ Standard Functions  C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions which are known as standard functionswhich are known as standard functions  These standard functions are groups in differentThese standard functions are groups in different libraries which can be included in the C++libraries which can be included in the C++ program, e.g.program, e.g.  Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library  Character-manipulation functions are declared inCharacter-manipulation functions are declared in <ctype.h> library<ctype.h> library  C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>
  • 5. 55 Example of UsingExample of Using Standard C++ Math FunctionsStandard C++ Math Functions #include <iostream.h>#include <iostream.h> #include <math.h>#include <math.h> void main()void main() {{ // Getting a double value// Getting a double value double x;double x; cout << "Please enter a real number: ";cout << "Please enter a real number: "; cin >> x;cin >> x; // Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl; }}
  • 6. 66 Example of UsingExample of Using Standard C++ Character FunctionsStandard C++ Character Functions #include <iostream.h> // input/output handling#include <iostream.h> // input/output handling #include <ctype.h> // character type functions#include <ctype.h> // character type functions void main()void main() {{ char ch;char ch; cout << "Enter a character: ";cout << "Enter a character: "; cin >> ch;cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl; cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl; if (isdigit(ch))if (isdigit(ch)) cout << "'" << ch <<"' is a digit!n";cout << "'" << ch <<"' is a digit!n"; elseelse cout << "'" << ch <<"' is NOT a digit!n";cout << "'" << ch <<"' is NOT a digit!n"; }} Explicit casting
  • 7. 77 User-Defined C++ FunctionsUser-Defined C++ Functions  Although C++ is shipped with a lot of standardAlthough C++ is shipped with a lot of standard functions, these functions are not enough for allfunctions, these functions are not enough for all users, therefore, C++ provides its users with ausers, therefore, C++ provides its users with a way to define their own functions (or user-way to define their own functions (or user- defined function)defined function)  For example, the <math.h> library does notFor example, the <math.h> library does not include a standard function that allows users toinclude a standard function that allows users to round a real number to the iround a real number to the ithth digits, therefore, wedigits, therefore, we must declare and implement this functionmust declare and implement this function ourselvesourselves
  • 8. 88 How to define a C++ Function?How to define a C++ Function?  Generally speaking, we define a C++Generally speaking, we define a C++ function in two steps (preferably but notfunction in two steps (preferably but not mandatory)mandatory) Step #1 – declare theStep #1 – declare the function signaturefunction signature inin either a header file (.h file) or before the maineither a header file (.h file) or before the main function of the programfunction of the program Step #2 – Implement the function in either anStep #2 – Implement the function in either an implementation file (.cpp) or after the mainimplementation file (.cpp) or after the main functionfunction
  • 9. 99 What is The Syntactic Structure ofWhat is The Syntactic Structure of a C++ Function?a C++ Function?  A C++ function consists of two partsA C++ function consists of two parts The function header, andThe function header, and The function bodyThe function body  The function header has the followingThe function header has the following syntaxsyntax <return value> <name> (<parameter list>)<return value> <name> (<parameter list>)  The function body is simply a C++ codeThe function body is simply a C++ code enclosed between { }enclosed between { }
  • 10. 1010 Example of User-definedExample of User-defined C++ FunctionC++ Function double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }}
  • 11. 1111 double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }} Example of User-definedExample of User-defined C++ FunctionC++ Function Function header
  • 12. 1212 Example of User-definedExample of User-defined C++ FunctionC++ Function double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }} Function header Function body
  • 13. 1313 Function SignatureFunction Signature  The function signature is actually similar toThe function signature is actually similar to the function header except in two aspects:the function header except in two aspects: The parameters’ names may not be specifiedThe parameters’ names may not be specified in the function signaturein the function signature The function signature must be ended by aThe function signature must be ended by a semicolonsemicolon  ExampleExample double computeTaxes(double) ;double computeTaxes(double) ; Unnamed Parameter Semicolon ;
  • 14. 1414 Why Do We Need FunctionWhy Do We Need Function Signature?Signature?  For Information HidingFor Information Hiding  If you want to create your own library and share it withIf you want to create your own library and share it with your customers without letting them know theyour customers without letting them know the implementation details, you should declare all theimplementation details, you should declare all the function signatures in a header (.h) file and distributefunction signatures in a header (.h) file and distribute the binary code of the implementation filethe binary code of the implementation file  For Function AbstractionFor Function Abstraction  By only sharing the function signatures, we have theBy only sharing the function signatures, we have the liberty to change the implementation details from timeliberty to change the implementation details from time to time toto time to  Improve function performanceImprove function performance  make the customers focus on the purpose of the function, notmake the customers focus on the purpose of the function, not its implementationits implementation
  • 15. 1515 ExampleExample #include <iostream>#include <iostream> #include <string>#include <string> using namespace std;using namespace std; // Function Signature// Function Signature double getIncome(string);double getIncome(string); double computeTaxes(double);double computeTaxes(double); void printTaxes(double);void printTaxes(double); void main()void main() {{ // Get the income;// Get the income; double income = getIncome("Please enterdouble income = getIncome("Please enter the employee income: ");the employee income: "); // Compute Taxes// Compute Taxes double taxes = computeTaxes(income);double taxes = computeTaxes(income); // Print employee taxes// Print employee taxes printTaxes(taxes);printTaxes(taxes); }} double computeTaxes(double income)double computeTaxes(double income) {{ if (income<5000) return 0.0;if (income<5000) return 0.0; return 0.07*(income-5000.0);return 0.07*(income-5000.0); }} double getIncome(string prompt)double getIncome(string prompt) {{ cout << prompt;cout << prompt; double income;double income; cin >> income;cin >> income; return income;return income; }} void printTaxes(double taxes)void printTaxes(double taxes) {{ cout << "The taxes is $" << taxes << endl;cout << "The taxes is $" << taxes << endl; }}
  • 16. 1616 Building Your LibrariesBuilding Your Libraries  It is a good practice to build libraries to beIt is a good practice to build libraries to be used by you and your customersused by you and your customers  In order to build C++ libraries, you shouldIn order to build C++ libraries, you should be familiar withbe familiar with How to create header files to store functionHow to create header files to store function signaturessignatures How to create implementation files to storeHow to create implementation files to store function implementationsfunction implementations How to include the header file to yourHow to include the header file to your program to use your user-defined functionsprogram to use your user-defined functions
  • 17. 1717 C++ Header FilesC++ Header Files  The C++ header files must have .hThe C++ header files must have .h extension and should have the followingextension and should have the following structurestructure #ifndef compiler directive#ifndef compiler directive #define compiler directive#define compiler directive May include some other header filesMay include some other header files All functions signatures with some commentsAll functions signatures with some comments about their purposes, their inputs, and outputsabout their purposes, their inputs, and outputs #endif compiler directive#endif compiler directive
  • 18. 1818 TaxesRules Header fileTaxesRules Header file #ifndef _TAXES_RULES_#ifndef _TAXES_RULES_ #define _TAXES_RULES_#define _TAXES_RULES_ #include <iostream>#include <iostream> #include <string>#include <string> using namespace std;using namespace std; double getIncome(string);double getIncome(string); // purpose -- to get the employee// purpose -- to get the employee incomeincome // input -- a string prompt to be// input -- a string prompt to be displayed to the userdisplayed to the user // output -- a double value// output -- a double value representing the incomerepresenting the income double computeTaxes(double);double computeTaxes(double); // purpose -- to compute the taxes for// purpose -- to compute the taxes for a given incomea given income // input -- a double value// input -- a double value representing the incomerepresenting the income // output -- a double value// output -- a double value representing the taxesrepresenting the taxes void printTaxes(double);void printTaxes(double); // purpose -- to display taxes to the// purpose -- to display taxes to the useruser // input -- a double value// input -- a double value representing the taxesrepresenting the taxes // output -- None// output -- None #endif#endif
  • 19. 1919 TaxesRules Implementation FileTaxesRules Implementation File #include "TaxesRules.h"#include "TaxesRules.h" double computeTaxes(doubledouble computeTaxes(double income)income) {{ if (income<5000) return 0.0;if (income<5000) return 0.0; return 0.07*(income-5000.0);return 0.07*(income-5000.0); }} double getIncome(string prompt)double getIncome(string prompt) {{ cout << prompt;cout << prompt; double income;double income; cin >> income;cin >> income; return income;return income; }} void printTaxes(double taxes)void printTaxes(double taxes) {{ cout << "The taxes is $" << taxescout << "The taxes is $" << taxes << endl;<< endl; }}
  • 20. 2020 Main Program FileMain Program File #include "TaxesRules.h"#include "TaxesRules.h" void main()void main() {{ // Get the income;// Get the income; double income =double income = getIncome("Please enter the employee income: ");getIncome("Please enter the employee income: "); // Compute Taxes// Compute Taxes double taxes = computeTaxes(income);double taxes = computeTaxes(income); // Print employee taxes// Print employee taxes printTaxes(taxes);printTaxes(taxes); }}
  • 21. 2121 Inline FunctionsInline Functions  Sometimes, we use the keywordSometimes, we use the keyword inlineinline to defineto define user-defined functionsuser-defined functions  Inline functions are very small functions, generally,Inline functions are very small functions, generally, one or two lines of codeone or two lines of code  Inline functions are very fast functions compared toInline functions are very fast functions compared to the functions declared without the inline keywordthe functions declared without the inline keyword  ExampleExample inlineinline double degrees( double radian)double degrees( double radian) {{ return radian * 180.0 / 3.1415;return radian * 180.0 / 3.1415; }}
  • 22. 2222 Example #1Example #1  Write a function to test if a number is anWrite a function to test if a number is an odd numberodd number inline bool odd (int x)inline bool odd (int x) {{ return (x % 2 == 1);return (x % 2 == 1); }}
  • 23. 2323 Example #2Example #2  Write a function to compute the distanceWrite a function to compute the distance between two points (x1, y1) and (x2, y2)between two points (x1, y1) and (x2, y2) Inline double distance (double x1, double y1,Inline double distance (double x1, double y1, double x2, double y2)double x2, double y2) {{ return sqrt(pow(x1-x2,2)+pow(y1-y2,2));return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); }}
  • 24. 2424 Example #3Example #3  Write a function to compute n!Write a function to compute n! int factorial( int n)int factorial( int n) {{ int product=1;int product=1; for (int i=1; i<=n; i++) product *= i;for (int i=1; i<=n; i++) product *= i; return product;return product; }}
  • 25. 2525 Example #4Example #4 Function OverloadingFunction Overloading  Write functions to return with the maximum number ofWrite functions to return with the maximum number of two numberstwo numbers inline int max( int x, int y)inline int max( int x, int y) {{ if (x>y) return x; else return y;if (x>y) return x; else return y; }} inline double max( double x, double y)inline double max( double x, double y) {{ if (x>y) return x; else return y;if (x>y) return x; else return y; }} An overloaded function is a function that is defined more than once with different data types or different number of parameters
  • 26. 2626 Sharing Data AmongSharing Data Among User-Defined FunctionsUser-Defined Functions There are two ways to share dataThere are two ways to share data among different functionsamong different functions Using global variables (very bad practice!)Using global variables (very bad practice!) Passing data through function parametersPassing data through function parameters Value parametersValue parameters Reference parametersReference parameters Constant reference parametersConstant reference parameters
  • 27. 2727 C++ VariablesC++ Variables  A variable is a place in memory that hasA variable is a place in memory that has  A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.)  A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.)  A size (number of bytes)A size (number of bytes)  A scope (the part of the program code that can use it)A scope (the part of the program code that can use it)  Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it  Local variables – only the function that declare localLocal variables – only the function that declare local variables see and use these variablesvariables see and use these variables  A life time (the duration of its existence)A life time (the duration of its existence)  Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed  Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define these variables are executedthese variables are executed
  • 28. 2828 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 29. 2929 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 0
  • 30. 3030 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1
  • 31. 3131 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 2 4
  • 32. 3232 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 3 void f1()void f1() {{ x++;x++; }} 4
  • 33. 3333 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 3 void f1()void f1() {{ x++;x++; }}5
  • 34. 3434 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }}6
  • 35. 3535 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 7
  • 36. 3636 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}8
  • 37. 3737 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 38. 3838 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 39. 3939 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 0x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 1 The inline keyword instructs the compiler to replace the function call with the function body!
  • 40. 4040 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 4x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 2
  • 41. 4141 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 3
  • 42. 4242 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }}4
  • 43. 4343 What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 44. 4444 What is Bad About UsingWhat is Bad About Using Global Vairables?Global Vairables?  Not safe!Not safe!  If two or more programmers are working together in aIf two or more programmers are working together in a program, one of them may change the value stored inprogram, one of them may change the value stored in the global variable without telling the others who maythe global variable without telling the others who may depend in their calculation on the old stored value!depend in their calculation on the old stored value!  Against The Principle of Information Hiding!Against The Principle of Information Hiding!  Exposing the global variables to all functions isExposing the global variables to all functions is against the principle of information hiding since thisagainst the principle of information hiding since this gives all functions the freedom to change the valuesgives all functions the freedom to change the values stored in the global variables at any time (unsafe!)stored in the global variables at any time (unsafe!)
  • 45. 4545 Local VariablesLocal Variables  Local variables are declared inside the functionLocal variables are declared inside the function body and exist as long as the function is runningbody and exist as long as the function is running and destroyed when the function exitand destroyed when the function exit  You have to initialize the local variable beforeYou have to initialize the local variable before using itusing it  If a function defines a local variable and thereIf a function defines a local variable and there was a global variable with the same name, thewas a global variable with the same name, the function uses its local variable instead of usingfunction uses its local variable instead of using the global variablethe global variable
  • 46. 4646 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }}
  • 47. 4747 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 0 Global variables are automatically initialized to 0
  • 48. 4848 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 1
  • 49. 4949 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x ???? 3
  • 50. 5050 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 3
  • 51. 5151 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 4
  • 52. 5252 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 5
  • 53. 5353 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 6
  • 54. 5454 Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }}7
  • 55. 5555 II. Using ParametersII. Using Parameters  Function Parameters come in threeFunction Parameters come in three flavors:flavors: Value parametersValue parameters – which copy the values of– which copy the values of the function argumentsthe function arguments Reference parametersReference parameters – which refer to the– which refer to the function arguments by other local names andfunction arguments by other local names and have the ability to change the values of thehave the ability to change the values of the referenced argumentsreferenced arguments Constant reference parametersConstant reference parameters – similar to– similar to the reference parameters but cannot changethe reference parameters but cannot change the values of the referenced argumentsthe values of the referenced arguments
  • 56. 5656 Value ParametersValue Parameters  This is what we use to declare in the function signature orThis is what we use to declare in the function signature or function header, e.g.function header, e.g. int max (int x, int y);int max (int x, int y);  Here, parameters x and y are value parametersHere, parameters x and y are value parameters  When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7 are copied to x and y respectivelyare copied to x and y respectively  When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively  When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50 and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively  Once the value parameters accepted copies of theOnce the value parameters accepted copies of the corresponding arguments data, they act as localcorresponding arguments data, they act as local variables!variables!
  • 57. 5757 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 1
  • 58. 5858 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 3 3
  • 59. 5959 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 3 4 8
  • 60. 6060 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 38 5
  • 61. 6161 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 6
  • 62. 6262 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }}7
  • 63. 6363 Reference ParametersReference Parameters  As we saw in the last example, any changes inAs we saw in the last example, any changes in the value parameters don’t affect the originalthe value parameters don’t affect the original function argumentsfunction arguments  Sometimes, we want to change the values of theSometimes, we want to change the values of the original function arguments or return with moreoriginal function arguments or return with more than one value from the function, in this case wethan one value from the function, in this case we use reference parametersuse reference parameters  A reference parameter is just another name to theA reference parameter is just another name to the original argument variableoriginal argument variable  We define a reference parameter by adding the & inWe define a reference parameter by adding the & in front of the parameter name, e.g.front of the parameter name, e.g. double update (doubledouble update (double && x);x);
  • 64. 6464 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4;int x = 4; // Local variable// Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 1 x? x4
  • 65. 6565 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x4 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }} 3
  • 66. 6666 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x4 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }} 4 9
  • 67. 6767 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x9 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }}5
  • 68. 6868 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 6 x? x9
  • 69. 6969 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} x? x9 7
  • 70. 7070 Constant Reference ParametersConstant Reference Parameters  Constant reference parameters are used underConstant reference parameters are used under the following two conditions:the following two conditions:  The passed data are so big and you want to saveThe passed data are so big and you want to save time and computer memorytime and computer memory  The passed data will not be changed or updated inThe passed data will not be changed or updated in the function bodythe function body  For exampleFor example void report (void report (constconst stringstring && prompt);prompt);  The only valid arguments accepted by referenceThe only valid arguments accepted by reference parameters and constant reference parametersparameters and constant reference parameters are variable namesare variable names  It is a syntax error to pass constant values orIt is a syntax error to pass constant values or expressions to the (const) reference parametersexpressions to the (const) reference parameters