This document provides an overview of functions in C++, including their definition, advantages, types, declaration, and usage. It explains the concepts of parameters and arguments, default parameters, passing arguments by value and by reference, and recursive functions. Additionally, it covers variable scope, distinguishing between local and global variables.
This document provides an overview of functions in C++, including their definition, advantages, types, declaration, and usage. It explains the concepts of parameters and arguments, default parameters, passing arguments by value and by reference, and recursive functions. Additionally, it covers variable scope, distinguishing between local and global variables.
Lecture 5: Functions Christopher Kalolo Introduction
● A function is a group of code for performing a specific task.
● In other programming languages, functions are also known as procedures or subroutines. ● Functions are important for code reusability. ● Functions allows you to define the code once, and reuse it many times. Introduction
● In order for a function to run, it must be invoked/called;
● Calling a function in C++ is accomplished by writing the name of the function followed by a pair of parenthesis ● While calling a function, you can pass data to the called function. ● The data (values) passed to a function are called arguments. ● The called function must include parameters in order to receive data passed to it. Advantages of functions ● Code Reusability ○ By creating functions in C++, you can call it many times. So we don't need to write the same code again and again. ● Code optimization ○ It makes the code optimized, we don't need to write much code. ○ Suppose you have to calculate the square root of 10 numbers (625, 144, 400, 321, 81, 25, 169, 64, 256 and 196). ○ Without using function, you need to write the square root logic 10 times which causes repetition of code. ○ But if you use functions, you need to write the logic only once and you can reuse it several times. Types of functions ● C++ offers two types of functions: ○ Inbuilt functions (also known as pre-defined functions or library functions) ○ User-defined functions ● Inbuilt functions are the functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x), etc. ○ You call an inbuilt function by writing the name of the function followed by a pair of parenthesis. ○ You can pass parameters into the function as well. ● User-defined functions are functions which are created by the programmer, so that he/she can use it many times. ○ It reduces complexity of a big program and optimizes the code Declaring functions
● The syntax of creating function in C++ language is given below:
1. return_type function_name(data_type parameter...) 2. { 3. //code to be executed 4. } ● A C++ function consist of two parts: ○ Declaration: the function's name, return type, and parameters (if any) ○ Definition: the body of the function (code to be executed) Declaring functions 1. #include <iostream> 2. using namespace std; 3. void func() { 4. static int i=0; //static variable 5. int j=0; //local variable 6. i++; 7. j++; 8. cout<<"i=" << i<<" and j=" <<j<<endl; 9. } 10. int main() { 11. func(); 12. func(); 13. } Declaring functions ● func() is the name of the function ● void means that the function does not have a return value. ● inside the function (the body) is a block of code that defines what the function does Declaring functions 1. #include <iostream> 2. #include <cmath> 3. using namespace std; 4. float squareroot(int num) { 5. float d; 6. d = sqrt(num) 7. return d; 8. } 9. int main() { 10. cout<<"The square root of 25 is: " << squareroot(25)<<endl; 11. cout<<"The square root of 196 is: " << squareroot(196)<<endl; 12. return 0; 13. } Calling a function ● Declared functions are not executed automatically, they’re only saved for later use. ● Declared functions are only executed when they’re called/invoked. ● To call a function, write the function's name followed by two parentheses () and a semicolon ; ● In the following example, myFunc() is used to print a text (the action), when it is called: 1. #include <iostream> 2. using namespace std; 3. 4. void myFunc() { 5. cout << "I just got executed!"; 6. } 7. 8. int main() { 9. myFunc(); 10. return 0; 11. } Parameters and Arguments ● Function parameters are the names (variables) listed in the function's definition. ● Parameters are specified after the function name, inside the parentheses as local variables that will be used inside the function body. ● The purpose of declaring function parameters is to enable the function to receive information passed from the function call. ● Function arguments are the real values passed to the function. ● Function arguments are passed during the function call. ● Unless there are default parameters, arguments must match the parameters defined during the function creation. Parameters and Arguments ● void functionName(parameter1, parameter2, parameter3, …, parameterN) { ● // code to be executed ● }
○ Leah Stewart ○ Jenny Stewart ○ Barbara Stewart ● From the above code ○ fname in the function definition is called a parameter ○ Leah, Jenny and Barbara are called arguments Default parameters
● Default parameters are parameters with a default value
● Default parameters are also known as optional parameters ● You define a default parameter by initializing a value to it. ● During the function call, if an argument is not passed to that function then the value in the default parameter is used. Default parameters 1. void myFunction(string name, string citizenship = "Tanzanian") { 2. cout << "My name is: "<<name<< ". I am a " <<citizenship << "\n"; 3. } 4. 5. int main() { 6. myFunction("Mwalimu Mwanakijiji"); 7. myFunction("Leonard Fredrick", "American"); 8. myFunction("Punjab Krishin", "Indian"); 9. myFunction("Jacob Matata");; 10. return 0; 11. } Multiple parameters ● You can add as many parameters as you wish. ● 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. 1. void myFunction(string fname, int age) { 2. cout << fname << " Refsnes. " << age << " years old. \n"; 3. } Passing arguments by value ● When you pass an argument to a function by value, you just send a copy of the value to that function. ● Arguments passed by value cannot be modified ● In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. ● If you change the value of function parameter, it is changed for the current function only. ● It will not change the value of variable inside the caller method such as main(). Passing arguments by value 1. #include <iostream> 2. using namespace std; 3. void change(int); 4. int main() { 5. int data = 3; 6. change(data); 7. cout << "Value of the data is: " << data<< endl; 8. return 0; 9. } 10. void change(int data){ 11. data = 5; 12. } Passing arguments by reference ● When you pass an argument to a function by reference, you send an address of the value to that function. ● Arguments passed by reference can be modified ● In a call by reference, address of the value is passed in the function, so actual and formal arguments share the same address space. ● If the value is changed inside the function, the effect is reflected inside as well as outside the function.. Passing arguments by reference 1. #include<iostream> 9. int main(){ 2. using namespace std; 10. int x=500, y=100; 3. void swap(int *x, int *y){ 11. swap(&x, &y); // passing value to 4. int swap; function 5. swap=*x; 12. cout<<"Value of x is: "<<x<<endl; 6. *x=*y; 13. cout<<"Value of y is: "<<y<<endl; 7. *y=swap; 14. return 0; 8. } 15. } Recursive Functions
● When function is called within the same function, it is known as
recursion in C++. ● The function which calls the same function, is known as recursive function. ● Recursive functions works far the same as iterative statements (loops) ● However, there are situations where loops cannot solve certain problems iteratively which recursion do. Recursive Functions ● The code below calculates the cumulative sum up to a number passed to a function int recsum(int x) { if (x === 0) { return 0; } else { return x + recsum(x - 1); } } Recursive Functions ● The code below calculates the factorial of a number passed to a function int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } Variable scope ● Variable scope is the extent to which the a variable can be accessed within the program code ● In C++, there are two types of variable scopes ○ Local Variables ○ Global Variables