Computer Programming and Logic Building Lecturer Hamza Azeem
Computer Programming and Logic Building Lecturer Hamza Azeem
Lecture 7 Functions
Introduction to Functions • A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself • Functions make programs easier to understand • Functions can be called several times in the same program, allowing the code to be reused
Introduction to Functions
Introduction to Functions
Creating Function • There are three steps involved in creating your own function – Declaration – Call – Definition
Example Function • Create a function which will multiply two numbers and outputs a result. • Declaration int multiply (int num 1, int num 2); • Call result = multiply (2, 3);
Example Function • Definition int multiply (int num 1, int num 2) { return (num 1 * num 2); }
Example Function #include <stdio. h> #include <conio. h> int multiply (int num 1, int num 2); int result; void main() { result = multiply ( 2 , 3 ); printf ( “The answer is %d”, result ); } int multiply(int num 1, int num 2) { int answer; answer = num 1 * num 2; return(num 1 * num 2); } // Function Declaration // Function Call // Function Definition
Functions • The function prototype has the following syntax: <type> <function name>(<argument list>); E. g. int multiply (int num 1, int num 2); • A function call has the following syntax: <function name>(<argument list>) E. g. multiply (2, 3);
Functions A function definition has the following syntax: <type> <function name>(<parameter list>) { <local declarations> <sequence of statements> } E. g. int multiply (int num 1, int num 2) { return (num 1 * num 2); }
Example int absolute (int x); // function prototype for absolute() int main(){ int num, answer; printf("Enter an integer (0 to stop): “); scanf(“%d”, &num); } while (num!=0) { answer = absolute(num); printf( "The absolute value is: %d”, answer); scanf(“%d”, &num); } // Define a function to take absolute value of an integer int absolute(int x){ if (x >= 0) return x; else return -x; }
Types of Arguments • Pass by value • Pass by reference
Pass by Value • In pass by value function we pass the values of the variables to the function. int multiply (int num 1, int num 2) { return (num 1 * num 2); }
Pass by reference • In Pass by reference method, not only the values are passed as arguments but also the variable itself. • It is used when changing the content of variable is required.
Pass by reference void changevalue (int& a, int& b, int& c) { a = a * 2; b = b * 2; c = c * 2; } int main () { int x=1, y=3, z=7; changevalue (x, y, z); printf("x = %d, y = %d, z = %d", x, y, z); } getch();
Pass by reference void changevalue (int a, int b, int c) { a = a * 2; b = b * 2; c = c * 2; } int main () { int x=1, y=3, z=7; changevalue (x, y, z); printf("x = %d, y = %d, z = %d", x, y, z); } getch();
- Slides: 17