Professional Documents
Culture Documents
Day 1 - Functions and Array
Day 1 - Functions and Array
Day 1 - Functions and Array
Session 2
C++ Functions
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into
a function.
• Functions are used to perform certain actions,
and they are important for reusing code:
Define the code once, and use it many times.
Create a Function
• C++ provides some pre-defined functions, such as main(), which is used to
execute code. But you can also create your own functions to perform certain
actions.
• To create (often referred to as declare) a function, specify the name of the
function, followed by parentheses ():
• void myFunction()
• {
// code to be executed
}
• myFunction() is the name of the function
• void means that the function does not have a return value. You will learn more
about return values later in the next chapter
• inside the function (the body), add code that defines what the function should do
Call a Function
• Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
• To call a function, write the function's name followed by two parentheses () and a semicolon ;
• In the following example, myFunction() is used to print a text (the action), when it is called:
Example
• Inside main, call myFunction():
• // Create a function
void myFunction()
• {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// Error
• However, it is possible to separate the declaration and the definition of the function - for
code optimization.
• You will often see C++ programs that have function declaration above main(), and function
definition below main()
• // Function declaration
void myFunction();
// Function definition
void myFunction()
{
cout << "I just got executed!";
}
C++ Function Parameters
• Parameters and Arguments
• Information can be passed to functions as a parameter.
Parameters act as variables inside the function.
• Parameters are specified after the function name, inside the
parentheses. You can add as many parameters as you want,
just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
Example
void myFunction(string fname)
{
cout << fname << " Refsnes\n";
}
int main()
{
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Output
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the function, it is called an argument. So, from the example above: fname is
a parameter, while Liam, Jenny and Anja are arguments.
Default Parameter Value
• You can also use a default parameter value, by using the equals sign (=).
Example
void myFunction(string country = "Norway")
{
cout << country << "\n";
}
int main()
{
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
C++ Multiple Parameters
• Inside the function, you can add as many parameters as you want:
• Example
void myFunction(string fname, int age)
{
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are
parameters, and the arguments must be passed in the same order.
C++ The Return Keyword
Return Values
The void keyword, used in the previous examples, indicates that the function should
not return a value. If you want the function to return a value, you can use a data type
(such as int, string, etc.) instead of void, and use the return keyword inside the
function:
Example
int myFunction(int x)
{
return 5 + x;
}
int main()
{
cout << myFunction(3);
return 0;
}
// Outputs 8
Example
This example returns the sum of a function with two parameters:
int main()
{
cout << myFunction(5, 3);
return 0;
}
// Output 8
Example - You can also store the result in a variable:
int main()
{
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Call Type & Description
• Call by Value This method copies the actual value of an argument into
the formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.
• Call by (address) Pointer This method copies the address of an
argument into the formal parameter. Inside the function, the address
is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
• Call by Reference This method copies the reference of an argument
into the formal parameter. Inside the function, the reference is used
to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
C++ function Call by value
• The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function. In this case,
changes made to the parameter inside the function
have no effect on the argument.
int b = 200;
/* calling a function to swap the values using When the above code is put
variable reference.*/ together in a file, compiled and
swap(a, b); executed, it produces the
following result −
Before swap, value of a :100
cout << "After swap, value of a :" << a << endl; Before swap, value of b :200
cout << "After swap, value of b :" << b << endl; After swap, value of a :200
return 0; After swap, value of b :100
}
Recursion
• A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
Advantages and Disadvantages of
Recursion
Advantages of C++ Recursion
• It makes our code shorter and cleaner.
• Recursion is required in problems concerning data structures
and advanced algorithms, such as Graph and Tree Traversal.
Disadvantages of C++ Recursion
• It takes a lot of stack space compared to an iterative
program.
• It uses more processor time.
• It can be more difficult to debug compared to an equivalent
iterative program.
Arrays
• Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
• To declare an array, define the variable type, specify the name of the array followed
by square brackets and specify the number of elements it should store:
• string cars[4];
• We have now declared a variable that holds an array of four strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly braces:
// function declaration:
double getAverage(int arr[], int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
return avg;
} output : Average value is: 214.4