1 / 92

Intro to Programming Week # 7 & 8 Functions Lecture # 11& 12

This lecture provides an introduction to functions in programming, including their definition, declaration, values passed to them, and values they return. The lecture also discusses the uses and types of functions in C++.

fgiron
Download Presentation

Intro to Programming Week # 7 & 8 Functions Lecture # 11& 12

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intro to ProgrammingWeek # 7 & 8FunctionsLecture # 11& 12 By: Saqib Rasheed

  2. What we will study today … • What are functions? • How are they defined ? • How are they declared ? • What values are passed to functions ? • What values do functions return ? Saqib Rasheed

  3. What is C++ function •   A large C++ program is divided into basic building blocks called C++ function. C++ function contains set of instructions enclosed by “{  }” which performs specific operation in a C++ program. Actually, Collection of these functions creates a C++ program. Saqib Rasheed

  4. Uses of C++ functions: • C++ functions are used to avoid rewriting same logic/code again and again in a program. • There is no limit in calling C++ functions to make use of same functionality wherever required. • We can call functions any number of times in a program and from any place in a program. • A large C++ program can easily be tracked when it is divided into functions. • The core concept of C++ functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C++ programs Saqib Rasheed

  5. Function Two types of functions: • Functions that return a value • Functions that do not return a value Saqib Rasheed

  6. Function • You've already encountered a few functions: main, cout and cin. • The main function is special, in the way that it's called automatically when the program starts. • In C++, and other programming languages, you can create your own functions. Saqib Rasheed

  7. A Typical Function Functions have 5 main features: 1.  The DATA TYPE is the data type of the RETURN VALUE of the function. 2. The NAME is required as an identifier to the function, so that the computer knows which function is called. Naming of functions follows the same set of rules as the naming of variables. 3. Functions can take ARGUMENTS - a function might need extra information for it to work. Arguments are optional. 4. The function BODY is surrounded by curly brackets and contains the statements of the function. 5. The RETURN VALUE is the value that is passed back to the main program. Functions exit whenever you return a value. Saqib Rasheed

  8. Function Syntax Function has three parts • Function Declaration / Prototype • Function Call • Function Body Saqib Rasheed

  9. Function Prototype • The function prototype is a single line “summary” of the function • Tells the number of inputs and output • Tells the type of inputs and output (int, float, double, char). • It is normally located at the top of your program listing • Usually above the main function and below the #include files definition • A function prototype has the form output Parameter functionName(input parameter, input parameter, …);

  10. Function Return Type • A function can only return either a single variable OR nothing at all • Multiple values are return using pointers and that can be specify in the input parameters. • The return type indicates the type of variable (if any) that the function outputs (returns) • Return type can be of any type (e.g. int, float, char) OR void (indicating the function does not return anything)

  11. Function Name • A function name can be anything but it is a good idea that the name used tells you what the function does • For example if the function used for deleting any student data (use name deleteStudentData) • We can declare more than one functions with the same name • But there input parameters should be different. • For example • void deleteStudentData (void); // delete all the students data • void deleteStudentData (int studentID); // delete the student data with specific ID.

  12. Function Inputs • Most functions will use input values • It is possible to write a function that has no inputs (e.g. rand function) • Examplevoid deleteStudentData (void); • Input values must be separated by commas if there are more than one input value within the brackets () after the function name • Examplevoid deleteStudentData (int studentID,float CGPA) • Each entry in this list of arguments must identify the input variable type and define a name by which that input can be referred to • In the case where there are no inputs to a function the keyword void appears instead of the list of arguments

  13. Example • Consider our function to calculate the factorial of an integer • Inputs: A single integer (that we will referred by its name) • Function Name: factorial • Return value: integer • Thus the prototype of this function is: intfactorial(int value);

  14. Function Implementation • ALL functions are typically located either before the main function OR after the main function • A function implementation is very like the main function itself • It starts with the function description (effectively the same as the prototype) • Without the ; • It is bounded by a pair of chain brackets {} • (Local) variables can be defined within (at the start of) the function • If the function has an output, return command must be present in the function

  15. Function Implementation • You cannot refer to a variable that is defined in any other function directly why? • The return command is used as follows: return (variableName); • This return command can : • Appear only in a function if it is returning output value in its prototype • Causes the function to immediately end and output the value in the single variable being “returned” • You can only return a single variable using the return statement

  16. Declaration of Function //Prototype / Declaration return-value-type function-name( argument--type-list) ; void main ( ) { Statement1; function-name( argument) ; //Call Of Function } Saqib Rasheed

  17. Function Body Syntax //Function Body return-value-type function-name( argument-list ){ statements;} Saqib Rasheed

  18. Simple Example 1 #include<iostream.h> void print(void); --------------Function Declaration int main() { cout<<"\nDisplaying Statement 1"; print(); --------------Function Call cout<<"\nDisplaying Statement 2 "; return 0; } void print(void) --------------Function Body { cout<<"\n\n*****Displaying Statement 3 ****** \n"; } Saqib Rasheed

  19. Simple Example 2 #include < iostream.h > int i ; ----------- Global Variable void myfun ( void ) ; --------------Function Declaration main ( ) { i = 10 ; cout<< "\n within main i = " << i ; myfun ( ) ; --------------Function Call cout<<endl; } Saqib Rasheed

  20. Simple Example 2 void myfun ( void ) -----------Function Body { i = 20 ; cout<< "\n Inside function f , i = " << i ; } Saqib Rasheed

  21. Calling the Function • If the function returns a value, you may store the result in a suitable variable type using the assignment (=) operator • Examples of function calls would be: variableName=functionOne(); variableName=functionTwo(variableA,variableB); functionThree(variableA,variableB); • A function can be called from the main function or from any other function • When a function is completed the program returns to the next line after where the function was called from

  22. Example • Get three integers numbers from user • Pass them to function • Add them and find the average in function body • Display the Average in function body Saqib Rasheed

  23. voidprintAverage(int x, int y, int z);//Function Prototype void main() { int a, b, c; cout<<"Enter 3 integers = "; cin>>a>>b>>c; printAverage(a, b, c); //Function Call cout<<“Ending Program”<<endl”; } voidprintAverage(int x, int y, int z) //Function Body { int res = (x + y + z) / 3; cout<<“Average = ”<<res<<endl; }

  24. Function Returning value Saqib Rasheed

  25. intprintAverage(int , int , int ); //Function Prototype void main() { int a, b, c; cout<<"Enter 3 integers = "; cin>>a>>b>>c; int res= printAverage(a, b, c); //Function Call cout<<“Average = <<res<<endl”; } intprintAverage(int x, int y, int z) //Function Body { return (x + y + z) / 3; } Saqib Rasheed

  26. intprintAverage(int , int , int );//Function Prototype void main() { int a, b, c; cout<<"Enter 3 integers = "; cin>>a>>b>>c; cout<<“Average = ”<<printAverage(a, b, c); } intprintAverage(int x, int y, int z) //Function Body { return (x + y + z) / 3; } Saqib Rasheed

  27. #include <iostream> using namespace std; int addition(int a, int b); int main () { int z; z = addition (5,3); cout << "The result is " << z; } int addition (int a, int b) { int r; r=a+b; return r; } Saqib Rasheed

  28. #include <iostream.h> int factorial (int value); // function prototype void main (void) { int scanValue = 0; cout<<“\n Enter the input value:”; cin>>scanValue; int res; res= factorial (scanValue); // function calling cout<<“\nThe Result is = ”<< res; res = factorial (10); // function calling cout<<“\nThe Result is = ”<< res ; } intfactorial (int value) // function implementation { int counter=0; int result=1; for (counter=1; counter<=value; counter++) { result= result * counter; } return (result); }

  29. void main (void) { int result = factorial (4); cout<<“The result is”<<result; } Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter<=value; counter++) { result= result * counter; } return(result); }

  30. value = 4 counter = 0 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter<=value; counter++) { result= result * counter; } return(result); }

  31. value = 4 counter = 0 result = 1 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter<=value; counter++) { result= result * counter; } return(result); }

  32. value = 4 counter = 1 result = 1 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter <= value; counter++) { result= result * counter; } return(result); }

  33. value = 4 counter = 1 result = 1 * 1 = 1 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1.0; for (counter=1; counter <= value; counter++) { result= result * counter; } return(result); }

  34. value = 4 counter = 2 result = 1 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter <= value; counter++) { result= result * counter; } return(result); }

  35. value = 4 counter = 2 result = 1* 2 = 2 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1.0; for (counter=1; counter <= value; counter++) { result= result * counter; } return (result); }

  36. value = 4 counter = 3 result = 3 * 2 = 6 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter <= value; counter++) { result= result * counter; } return (result); }

  37. value = 4 counter = 4 result = 6 * 4 = 24 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1; for (counter=1; counter <= value; counter++) { result= result * counter; } return (result); }

  38. value = 4 counter = 5 result = 24 Example • Consider our example: intfactorial (int value) { int counter=0; int result=1.0; for (counter=1; counter <= value; counter++) { result= result * counter; } return (result); }

  39. Calling the Function void main (void) { int result = factorial (4); cout<<“The result is ”<<result; } • If the function returns a value, you may store the result in a suitable variable type using the assignment (=) operator • Examples of function calls would be: variableName = functionOne(); variableName = functionTwo(variableA, variableB); functionThree(variableA,variableB); • A function can be called from the mainfunction or from any other function • When a function has completed its execution then the program returns to the next line after where the function was called from. • All the local variables of the function are destroyed after function execution.

  40. Advantages of using functions • Code becomes more readable easy to modifiable by second person. • Code becomes more compact and small. • If code is small then the exe file will be also small, which will enable your executable file to fit in a very small RAM.

  41. What will be the output? • voidduplicate (int a, int b) { a*=2; b*=2; } intmain () { int x=1, y=3; duplicate (x, y); cout << "x=" << x << ", y=" << y; return 0; }

  42. Example 2 #include <iostream.h> int Square( int ); // function prototype void main() { for ( int counter = 1; counter <= 10; counter++ ) { cout<<“The square of “<< counter<< “ is”; cout<<Square( counter )”<<endl;// function call } } // end _tmain // function definition int Square( int y ) { return y * y; // return square of y } // end function Square

  43. Sharing Data Among User-Defined Functions • There are two ways to share data among different functions • Using global variables (very bad practice!) • Passing data through function parameters • Value parameters • Reference parameters • Constant reference parameters

  44. C++ Variables • A variable is a place in memory that has • A name or identifier (e.g. income, taxes, etc.) • A data type (e.g. int, double, char, etc.) • A size (number of bytes) • A scope (the part of the program code that can use it) • Global variables – all functions can see it and using it • Local variables – only the function that declare local variables see and use these variables • A life time (the duration of its existence) • Global variables can live as long as the program is executed • Local variables are lived only when the functions that define these variables are executed

  45. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables

  46. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables 0 x

  47. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables 0 x void main() { f2(); cout << x << endl ; } 1

  48. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables 0 4 x void f2() { x += 4; f1(); } 2 void main() { f2(); cout << x << endl ; } 1

  49. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables 4 5 x void f1() { x++; } 4 void f2() { x += 4; f1(); } 3 void main() { f2(); cout << x << endl ; } 1

  50. #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } I. Using Global Variables 4 5 x void f1() { x++; } 5 void f2() { x += 4; f1(); } 3 void main() { f2(); cout << x << endl; } 1

More Related