SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
1
Functions in C++
CHAPTER V
2
C++ Functions
In this tutorial, we will learn about the C++ function and function expressions with the help
of examples.
A function is a block of code that performs a specific task.
Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:
 a function to draw the circle
 a function to color the circle
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users
In this C++ User-defined Function
C++ allows the programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of code is given
a name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined
in the body of the function.
tutorial, we will focus mostly on user-defined functions.
3
C++ Function Declaration
The syntax to declare a function is:
returnType functionName (parameter1, parameter2,...) {
// function body
}
Here's an example of a function declaration.
// function declarationvoid greet() {
cout << "Hello World";
}
Here,
• the name of the function is greet()
• the return type of the function is void
• the empty parentheses mean it doesn't have any parameters
• the function body is written inside {}
Note: We will learn about returnType and parameters later in this tutorial.
4
Example 1: C++ if Statement
// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number; // checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
5
Calling a Function
In the above program, we have declared a function named greet(). To
use the greet() function, we need to call it.
Here's how we can call the above greet() function.
int main() {
// calling a function
greet();
}
6
Example 1: Display a Text
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function
greet();
return 0;
}
Output
Hello there!
7
Function Parameters
As mentioned above, a function can be declared with parameters
(arguments). A parameter is a value that is passed when declaring a
function.
For example, let us consider the function below:
void printNum(int num) {
cout << num;
}
Here, the int variable num is the function parameter.
We pass a value to the function parameter while calling the function.
int main() {
int n = 7;
// calling the function
// n is passed to the function as argument
printNum(n);
return 0;
} 8
Example 2: Function with Parameters
// program to print a text
#include <iostream>
using namespace std;
// display a numbe
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Output
The int number is 5
The double number is 5.5
9
• In the above program, we have used a function that has one int parameter and one double
parameter.
• We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.
Note: The type of the arguments passed while calling the function must
match with the corresponding parameters defined in the function
declaration.
10
Return Statement
• In the above programs, we have used void in the function declaration.
For example,
void displayNumber() { // code}
• This means the function is not returning any value.
• It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
• Then, the return statement can be used to return a value from a function.
For example,
int add (int a, int b) {
return (a + b);
}
• Here, we have the data type int instead of void. This means that the
function returns an int value.
• The code return (a + b); returns the sum of the two parameters as the
function value.
• The return statement denotes that the function has ended. Any code after
return inside the function is not executed.
11
Example 3: Add Two Numbers
// program to add two numbers using a function
#include <iostream>
using namespace std;
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Output
100 + 78 = 178
12
• In the above program, the add() function is used to find the sum of two numbers.
• We pass two int literals 100 and 78 while calling the function.
• We store the returned value of the function in the variable sum, and then we print it.
Notice that sum is a variable of int type. This is because the return value of add() is of int type.
Function Prototype
• In C++, the code of function declaration should be before the function call.
• However, if we want to define a function after the function call, we need to use the
function prototype. For example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);}
• In the above code, the function prototype is:
void add(int, int);
• This provides the compiler with information about the function name and its
parameters.
• That's why we can use the code to call a function before the function has been
defined.
• The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
14
Example 4: C++ Function Prototype
// using function definition after main() function;// function prototype is declared before
main()
#include <iostream>using namespace std;
// function prototype
int add(int, int);
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
// function definition
int add(int a, int b) {
return (a + b);
}
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only difference is that here,
the function is defined after the function call.That's why we have used a function
prototype in this example.
15
Benefits of Using User-Defined Functions
• Functions make the code reusable. We can declare them once and use them multiple
times.
• Functions make the program easier as each small task is divided into a function.
• Functions increase readability.
C++ Library Functions
• Library functions are the built-in functions in C++ programming.
• Programmers can use library functions by invoking the functions directly; they don't
need to write the functions themselves.
• Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
• In order to use library functions, we usually need to include the header file in which
these library functions are defined.
• For instance, in order to use mathematical functions such as sqrt() and abs(), we need to
include the header file cmath.
16
Example 5: C++ Program to Find the Square Root of a Number
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double number,
squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square
root of a number.
The function declaration of sqrt() is defined in the cmath header file.
That's why we need to use the code #include <cmath> to use the sqrt() function.
17
C++ Function Overloading
• In this tutorial, we will learn about the function overloading in C++ with examples.
• In C++, two functions can have the same name if the number and/or type of
arguments passed is different.
• These functions having the same name but different arguments are known as
overloaded functions. For example:
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
• Here, all 4 functions are overloaded functions.
• Notice that the return types of all these 4 functions are not the same. Overloaded
functions may or may not have different return types but they must have different
arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
• Here, both functions have the same name, the same type, and the same number of
arguments. Hence, the compiler will throw an error.
18
Example 1: Overloading Using Different Types of Parameter
// Program to compute absolute value// Works for both int and float
#include <iostream>
using namespace std;
// function with float type parameter
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
// function with int type parameter
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
int main() {
// call function with int type parameter
cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}
Output
Absolute value of -5 = 5; Absolute value of 5.5 = 5.5
19
• In this program, we overload the absolute() function. Based on the
type of parameter passed during the function call, the corresponding
function is called.
20
Example 2: Overloading Using Different Number of Parameters
#include <iostream>
using namespace std;
// function with 2 parameters
void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}
// function with double type single parameter
void display(double var) {
cout << "Double number: " << var << endl;
}
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}
int main() {
int a = 5; double b = 5.5;
// call function with int type parameter
display(a);
// call function with double type parameter
display(b);
// call function with 2 parameters
display(a, b);
return 0;
}
Output
Integer number: 5; Float number: 5.5; Integer number: 5 ; and double number: 5.5
21
• Here, the display() function is called three times with different arguments. Depending on the
number and type of arguments passed, the corresponding display() function is called.
• The return type of all these functions is the same but that need not be the case for function
overloading.
22
C++ Storage Class
In this article, you'll learn about different storage classes in C++.
Namely: local, global, static local, register and thread local.
Every variable in C++ has two features: type and storage class.
Type specifies the type of data that can be stored in a variable. For
example: int, float, char etc.
And, storage class controls two different properties of a variable:
lifetime (determines how long a variable can exist) and scope
(determines which part of the program can access it).
Depending upon the storage class of a variable, it can be divided into
4 major types:
•Local variable
•Global variable
•Static local variable
•Register Variable
•Thread Local Storage
1. Local Variable
A variable defined inside a function (defined inside function body between braces) is called a local
variable or automatic variable.
Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can
be accessed only inside a function.
The life of a local variable ends (It is destroyed) when the function exits.
Example 1: Local variable
#include <iostream>
using namespace std;
void test();
int main() {
// local variable to main()
int var = 5;
test();
// illegal: var1 not declared inside main()
var1 = 9;
}
void test(){
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var;
}
The variable var cannot be used inside test() and var1 cannot be used inside main() function.
24
2. Global Variable
• If a variable is defined outside all functions, then it is called a global variable.
• The scope of a global variable is the whole program. This means, It can be used and changed at any part
of the program after its declaration.
• Likewise, its life ends only when the program ends.
Example 2: Global variable
#include <iostream>
using namespace std;
// Global variable declaration
int c = 12;
void test();
int main(){
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test(){
++c;
// Outputs 14
cout << c;
}
Output
13 14
In the above program, c is a global variable.
This variable is visible to both functions main() and test() in the above program.

Mais conteúdo relacionado

Mais procurados

Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusDhivyaSubramaniyam
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in PythonRaajendra M
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programmingClaus Wu
 
Operators and Control Statements in Python
Operators and Control Statements in PythonOperators and Control Statements in Python
Operators and Control Statements in PythonRajeswariA8
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statementsIntro C# Book
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & ImportMohd Sajjad
 

Mais procurados (20)

C++ Ch3
C++ Ch3C++ Ch3
C++ Ch3
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
Operators and Control Statements in Python
Operators and Control Statements in PythonOperators and Control Statements in Python
Operators and Control Statements in Python
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 

Semelhante a Chap 5 c++

unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfJAVVAJI VENKATA RAO
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxvanshhans21102005
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdfziyadaslanbey
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptxDikshaDani5
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptxrebin5725
 

Semelhante a Chap 5 c++ (20)

unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
unit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdfunit3 part2 pcds function notes.pdf
unit3 part2 pcds function notes.pdf
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
Chapter 1.ppt
Chapter 1.pptChapter 1.ppt
Chapter 1.ppt
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
C++ Functions.pptx
C++ Functions.pptxC++ Functions.pptx
C++ Functions.pptx
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
 
Function
FunctionFunction
Function
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 

Último

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Último (20)

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

Chap 5 c++

  • 1. 1 Functions in C++ CHAPTER V 2 C++ Functions In this tutorial, we will learn about the C++ function and function expressions with the help of examples. A function is a block of code that performs a specific task. Suppose we need to create a program to create a circle and color it. We can create two functions to solve this problem:  a function to draw the circle  a function to color the circle Dividing a complex problem into smaller chunks makes our program easy to understand and reusable. There are two types of function: 1. Standard Library Functions: Predefined in C++ 2. User-defined Function: Created by users In this C++ User-defined Function C++ allows the programmer to define their own function. A user-defined function groups code to perform a specific task and that group of code is given a name (identifier). When the function is invoked from any part of the program, it all executes the codes defined in the body of the function. tutorial, we will focus mostly on user-defined functions. 3 C++ Function Declaration The syntax to declare a function is: returnType functionName (parameter1, parameter2,...) { // function body } Here's an example of a function declaration. // function declarationvoid greet() { cout << "Hello World"; } Here, • the name of the function is greet() • the return type of the function is void • the empty parentheses mean it doesn't have any parameters • the function body is written inside {} Note: We will learn about returnType and parameters later in this tutorial. 4 Example 1: C++ if Statement // Program to print positive number entered by the user // If the user enters a negative number, it is skipped #include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; // checks if the number is positive if (number > 0) { cout << "You entered a positive integer: " << number << endl; } cout << "This statement is always executed."; return 0; }
  • 2. 5 Calling a Function In the above program, we have declared a function named greet(). To use the greet() function, we need to call it. Here's how we can call the above greet() function. int main() { // calling a function greet(); } 6 Example 1: Display a Text #include <iostream> using namespace std; // declaring a function void greet() { cout << "Hello there!"; } int main() { // calling the function greet(); return 0; } Output Hello there! 7 Function Parameters As mentioned above, a function can be declared with parameters (arguments). A parameter is a value that is passed when declaring a function. For example, let us consider the function below: void printNum(int num) { cout << num; } Here, the int variable num is the function parameter. We pass a value to the function parameter while calling the function. int main() { int n = 7; // calling the function // n is passed to the function as argument printNum(n); return 0; } 8 Example 2: Function with Parameters // program to print a text #include <iostream> using namespace std; // display a numbe void displayNum(int n1, float n2) { cout << "The int number is " << n1; cout << "The double number is " << n2; } int main() { int num1 = 5; double num2 = 5.5; // calling the function displayNum(num1, num2); return 0; } Output The int number is 5 The double number is 5.5
  • 3. 9 • In the above program, we have used a function that has one int parameter and one double parameter. • We then pass num1 and num2 as arguments. These values are stored by the function parameters n1 and n2 respectively. Note: The type of the arguments passed while calling the function must match with the corresponding parameters defined in the function declaration. 10 Return Statement • In the above programs, we have used void in the function declaration. For example, void displayNumber() { // code} • This means the function is not returning any value. • It's also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration. • Then, the return statement can be used to return a value from a function. For example, int add (int a, int b) { return (a + b); } • Here, we have the data type int instead of void. This means that the function returns an int value. • The code return (a + b); returns the sum of the two parameters as the function value. • The return statement denotes that the function has ended. Any code after return inside the function is not executed. 11 Example 3: Add Two Numbers // program to add two numbers using a function #include <iostream> using namespace std; // declaring a function int add(int a, int b) { return (a + b); } int main() { int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0; } Output 100 + 78 = 178 12 • In the above program, the add() function is used to find the sum of two numbers. • We pass two int literals 100 and 78 while calling the function. • We store the returned value of the function in the variable sum, and then we print it. Notice that sum is a variable of int type. This is because the return value of add() is of int type.
  • 4. Function Prototype • In C++, the code of function declaration should be before the function call. • However, if we want to define a function after the function call, we need to use the function prototype. For example, // function prototype void add(int, int); int main() { // calling the function before declaration. add(5, 3); return 0; } // function definition void add(int a, int b) { cout << (a + b);} • In the above code, the function prototype is: void add(int, int); • This provides the compiler with information about the function name and its parameters. • That's why we can use the code to call a function before the function has been defined. • The syntax of a function prototype is: returnType functionName(dataType1, dataType2, ...); 14 Example 4: C++ Function Prototype // using function definition after main() function;// function prototype is declared before main() #include <iostream>using namespace std; // function prototype int add(int, int); int main() { int sum; // calling the function and storing // the returned value in sum sum = add(100, 78); cout << "100 + 78 = " << sum << endl; return 0; } // function definition int add(int a, int b) { return (a + b); } Output 100 + 78 = 178 The above program is nearly identical to Example 3. The only difference is that here, the function is defined after the function call.That's why we have used a function prototype in this example. 15 Benefits of Using User-Defined Functions • Functions make the code reusable. We can declare them once and use them multiple times. • Functions make the program easier as each small task is divided into a function. • Functions increase readability. C++ Library Functions • Library functions are the built-in functions in C++ programming. • Programmers can use library functions by invoking the functions directly; they don't need to write the functions themselves. • Some common library functions in C++ are sqrt(), abs(), isdigit(), etc. • In order to use library functions, we usually need to include the header file in which these library functions are defined. • For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include the header file cmath. 16 Example 5: C++ Program to Find the Square Root of a Number #include <iostream> #include <cmath> using namespace std; int main() { double number, squareRoot; number = 25.0; // sqrt() is a library function to calculate the square root squareRoot = sqrt(number); cout << "Square root of " << number << " = " << squareRoot; return 0; } Output Square root of 25 = 5 In this program, the sqrt() library function is used to calculate the square root of a number. The function declaration of sqrt() is defined in the cmath header file. That's why we need to use the code #include <cmath> to use the sqrt() function.
  • 5. 17 C++ Function Overloading • In this tutorial, we will learn about the function overloading in C++ with examples. • In C++, two functions can have the same name if the number and/or type of arguments passed is different. • These functions having the same name but different arguments are known as overloaded functions. For example: // same name different arguments int test() { } int test(int a) { } float test(double a) { } int test(int a, double b) { } • Here, all 4 functions are overloaded functions. • Notice that the return types of all these 4 functions are not the same. Overloaded functions may or may not have different return types but they must have different arguments. For example, // Error code int test(int a) { } double test(int b){ } • Here, both functions have the same name, the same type, and the same number of arguments. Hence, the compiler will throw an error. 18 Example 1: Overloading Using Different Types of Parameter // Program to compute absolute value// Works for both int and float #include <iostream> using namespace std; // function with float type parameter float absolute(float var){ if (var < 0.0) var = -var; return var; } // function with int type parameter int absolute(int var) { if (var < 0) var = -var; return var; } int main() { // call function with int type parameter cout << "Absolute value of -5 = " << absolute(-5) << endl; // call function with float type parameter cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl; return 0; } Output Absolute value of -5 = 5; Absolute value of 5.5 = 5.5 19 • In this program, we overload the absolute() function. Based on the type of parameter passed during the function call, the corresponding function is called. 20 Example 2: Overloading Using Different Number of Parameters #include <iostream> using namespace std; // function with 2 parameters void display(int var1, double var2) { cout << "Integer number: " << var1; cout << " and double number: " << var2 << endl; } // function with double type single parameter void display(double var) { cout << "Double number: " << var << endl; } // function with int type single parameter void display(int var) { cout << "Integer number: " << var << endl; } int main() { int a = 5; double b = 5.5; // call function with int type parameter display(a); // call function with double type parameter display(b); // call function with 2 parameters display(a, b); return 0; } Output Integer number: 5; Float number: 5.5; Integer number: 5 ; and double number: 5.5
  • 6. 21 • Here, the display() function is called three times with different arguments. Depending on the number and type of arguments passed, the corresponding display() function is called. • The return type of all these functions is the same but that need not be the case for function overloading. 22 C++ Storage Class In this article, you'll learn about different storage classes in C++. Namely: local, global, static local, register and thread local. Every variable in C++ has two features: type and storage class. Type specifies the type of data that can be stored in a variable. For example: int, float, char etc. And, storage class controls two different properties of a variable: lifetime (determines how long a variable can exist) and scope (determines which part of the program can access it). Depending upon the storage class of a variable, it can be divided into 4 major types: •Local variable •Global variable •Static local variable •Register Variable •Thread Local Storage 1. Local Variable A variable defined inside a function (defined inside function body between braces) is called a local variable or automatic variable. Its scope is only limited to the function where it is defined. In simple terms, local variable exists and can be accessed only inside a function. The life of a local variable ends (It is destroyed) when the function exits. Example 1: Local variable #include <iostream> using namespace std; void test(); int main() { // local variable to main() int var = 5; test(); // illegal: var1 not declared inside main() var1 = 9; } void test(){ // local variable to test() int var1; var1 = 6; // illegal: var not declared inside test() cout << var; } The variable var cannot be used inside test() and var1 cannot be used inside main() function. 24 2. Global Variable • If a variable is defined outside all functions, then it is called a global variable. • The scope of a global variable is the whole program. This means, It can be used and changed at any part of the program after its declaration. • Likewise, its life ends only when the program ends. Example 2: Global variable #include <iostream> using namespace std; // Global variable declaration int c = 12; void test(); int main(){ ++c; // Outputs 13 cout << c <<endl; test(); return 0; } void test(){ ++c; // Outputs 14 cout << c; } Output 13 14 In the above program, c is a global variable. This variable is visible to both functions main() and test() in the above program.