This document discusses functions in C++. It covers:
- The definition of a function as a subprogram that can act on data and return a value.
- Functions come in two varieties: user-defined and built-in.
- Functions must be declared before use with a prototype specifying the return type and parameters.
- A function is defined by providing the body of code that performs the task.
- Functions can interact through calls where parameters are passed by value or by reference.
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
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
Call by value or call by reference in C++Sachin Yadav
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.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
Call by value or call by reference in C++Sachin Yadav
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.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
2. • Function - a subprogram that can act on data and return
a value
• Every C++ program has at least one function, main(),
where program execution begins
• A C++ program might contain more than one function.
• Functions may interact using function call
• Functions in C++ come in two varieties:
– user-defined
– built-in
2
3. 3
Predefined Functions (continued)
• Some of the predefined mathematical functions are:
sqrt(x)
pow(x,y)
floor(x)
• Predefined functions are organized into separate
libraries
• I/O functions are in iostream header
• Math functions are in cmath header
4. 4
The Power Function (pow)
• pow(x,y) calculates xy, pow(2,3) = 8.0
• pow returns a value of type double
• x and y are called the parameters (or
arguments) of the function pow
• Function pow has two parameters
5. 5
The sqrt and floor Functions
• The square root function sqrt(x)
– Calculates the non-negative square root of x, for
x >= 0.0
– sqrt(2.25) is 1.5
– Type double
– Has only one parameter
6. 6
The sqrt and floor Functions
(continued)
• The floor function floor(x)
– Calculates largest whole number not greater than
x
– floor(48.79) is 48.0
– Type double
– Has only one parameter
7.
8.
9. Declaration of Functions
• Functions must be declared before use
• The declaration tells the compiler
– The name,
– Return type,
– Parameters of the function
• Three ways
– Write your prototype into a file, and then use the #include
directive to include it in your program.
– Write the prototype into the file in which your function is
used.
– Define the function before it is called by any other function.
9
10. Function Prototypes
• The declaration of a function is called its prototype
• Is a statement - it ends with a semicolon
• It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type
[parameterName1], type [ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
10
11. Function Prototypes
• All functions have a return type
• If the function doesn’t have a return type void will be used
– void is a reserved word
• The function prototype usually placed at the beginning of the
program
• The definition of the prototype must be given
• Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using
#include
11
12. Defining a Function
• The definition tells the compiler how the function works.
• Consists of :
– the function header :
• like the function prototype except that the parameters must be
named
• there is no terminating semicolon
– its body
• the task of the function
• Syntax
return_type function_name(parameter declarations)
{
declarations;
statements;
}
12
13. Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is typically used
to exit the function early
• C++ does not allow nested functions
– The definition of one function cannot be included in
the body of another function
• A function definition must agree in return type and
parameter list with its prototype
13
14. // Creating and using a programmer-defined function.
#include <iostream.h>
int square( int ); // function prototype
int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
cout << endl;
return 0; // indicates successful termination
} // end main
// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square
Definition of square. y is a
copy of the argument passed.
Returns y * y, or y squared.
Function prototype: specifies data types
of arguments and return values.
square expects an int, and returns
an int.
Parentheses () cause function to be called.
When done, it returns the result.
1 4 9 16 25 36 49 64 81 100
14
15. Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<
endl;
return 0;
}
double Celsius_to_Fahr(double Celsius)
{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
15
16. Scope of identifier
• Refers to where in the program an identifier is accessible
• Determines how long it is available to your program and
where it can be accessed
• Two kind
– Local identifier - identifiers declared within a function
(or block)
– Global identifier – identifiers declared outside of every
function definition
16
17. Local scope
• You can declare variables within the body of the function
– local variables
– When the function returns, the local variables are no
longer available
• Variables declared within a block are scoped to that
block – Local to that block
– they can be accessed only within that block and "go
out of existence" when that block ends
– E.g.
for (int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
17
18. Global Scope
• Variables defined outside of any function have global
scope
• Available for any function in the program, including main()
• A local variable with the same name as a global
variable hides the global variable - when used within
the function
18
19. #include <iostream.h>
void myFunction(); //
prototype
int x = 5, y = 7; //
global variables
int main()
{
cout << "x from main: "
<< x << "n";
cout << "y from main: "
<< y << "nn";
myFunction();
cout << "Back from
myFunction!nn";
cout << "x from main: "
<< x << "n";
cout << "y from main: "
<< y << "n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction:
" << x << "n";
cout << "y from myFunction:
" << y << "nn";
}
Output:
x from main: 5
y from main: 7
x from myFunction: 5
y from myFunction: 10
Back from myFunction!
x from main: 5
y from main: 7
19
20. Unary Scope Resolution Operator ::
• Using ::, one can access an global variable even
if it is over-shadowed by a local variable of the
same name.
• E.g.
#include <iostream.h>
float num=10.8;
int main()
{
float num= 9.66;
cout<<“the value of num is:”<<::num<<endl;
return 0;
}
20
21. inline Functions
• Function calls
– Cause execution-time overhead
• Qualifier inline before function return type
"advises" a function to be inlined
• Puts copy of function's code in place of function call
– Speeds up performance but increases file size
– Compiler can ignore the inline qualifier
• Ignores all but the smallest functions
– E.g.
inline double cube( const double s )
{
return s * s * s;
} 21
22. inline functions
• Advantage: function call overhead is eliminated,
thus faster and less memory consuming
• Disadvantage: the code is expanded during
compilation so that executable file is large
22
23. Functions with Default Parameters
• When a function is called
– The number of actual and formal parameters must be
the same
• C++ relaxes this condition for functions with default
parameters
• You specify the value of a default parameter when the
function name appears for the first time, such as in the
prototype
23
24. # include<iostream>
Using namespace std;
int product (int x, int y=3)
{
int multiply;
multiply = x* y;
return multiply;
}
void main()
{
// First call to function ‘product’
cout<<product(10)<<endl;
// Second call to function ‘product’
cout<<product(20,12);
}
24
25. Empty Parameter Lists
• functions can take no arguments
• To declare that a function takes no parameters:
– Write void or nothing in parentheses
• E.g
– void print1( void );
– void print2();
25
26. Parameter Passing
• Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
• Call by Reference
– Address of the function argument passed to the
formal parameter of the function
26
27. Call by Reference
• If a formal parameter is a reference parameter
– It receives the address of the corresponding actual parameter
– A reference parameter stores the address of the corresponding
actual parameter
• During program execution to manipulate the data
– The address stored in the reference parameter directs it to the
memory space of the corresponding actual parameter
– A reference parameter receives the address of the actual
parameter
• Reference parameters can:
– Pass one or more values from a function
– Change the value of the actual parameter
27
28. Call by Reference
• Reference parameters are useful in three
situations:
– Returning more than one value
– Changing the actual parameter
– When passing the address would save
memory space and time
28
29. 29
Reference Variable Example
int count;
int &x = count;
// Create x as an alias for count
count = 1;
cout << “x is “ << x << endl;
x++;
cout << “count is “ << count << endl;
30. // Initializing and using a reference.
#include <iostream>
using namespace std;
int main()
{
int x = 3;
int &y = x; // y refers to (is an alias for) x
cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;
return 0;
} // end main
30
31. Call by Value Example
/* Incorrect function to switch two values */
void swap(int a, int b)
{
int hold;
hold = a;
a = b;
b = hold;
return;
}
31
int a = 3, b = 5;
Swap( a,b);
Cout<<a<<b;
32. Call by Reference Example
/* Correct function to switch two values */
void swap2(int& a, int& b)
{
int hold;
hold = a;
a = b;
b = hold;
return;
}
32
33. 33
Recursion
• Functions can call themselves! This is
called recursion.
• Recursion is very useful – it’s often very
simple to express a complicated
computation recursively.
35. Finding Factorial iteratively
#include<iostream.h>
unsigned long factorial(unsigned long);//prototype
int main()
{
int num;
cout<<"enter a positive integer:";
cin>>num;
cout<<"The factorial of "<<num<<" is:
"<<factorial(num)<<endl;
return 0;
}
unsigned long factorial(unsigned long n)
{
unsigned long fact = 1;
for( int i=1; i<=n; i++)
fact*=i;
return fact;
}
35
36. //Recursive factorial Function
#include<iostream.h>
unsigned long factorial(unsigned long);//prototype
int main()
{
int num;
cout<<“enter a positive integer:”;
cin>>num;
cout<<“factorial=“<<factorial(num);
return 0;
}
unsigned long factorial(unsigned long n)
{
if ( n <= 1) //the base case
return 1;
else
return n * factorial (n - 1);
}
Finding Factorial Recursively
36
37. 37
Designing Recursive Functions
• Define “Base Case”:
– The situation in which the function does not
call itself.
• Define “recursive step”:
– Compute the return value the help of the
function itself.
38. 38
Recursion Base Case
• The base case corresponds to a case in which you know
the answer (the function returns the value immediately),
or can easily compute the answer.
• If you don’t have a base case you can’t use recursion!
(and you probably don’t understand the problem).
39. 39
Recursive Step
• Use the recursive call to solve a sub-
problem.
– The parameters must be different (or the
recursive call will get us no closer to the
solution).
– You generally need to do something besides
just making the recursive call.
40. 40
Recursion is a favorite test topic
• Write a recursive C++ function that
computes the area of an nxn square.
n
n
Base case:
n=1 area=1
Recursive Step:
area = n+n-1+area(n-1)
42. 42
Recursion Exercise
• Write a function that prints a triangle:
triangle(4); triangle(5);
* *
*** ***
***** *****
******* *******
*********
43. • Function overloading
– Functions with same name and different
parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
Function Overloading
43
44. // overloaded function
#include <iostream>
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "n";
cout << operate (n,m);
cout << "n";
return 0;
}
44