Dti2143 chapter 5

1,437 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,437
On SlideShare
0
From Embeds
0
Number of Embeds
230
Actions
Shares
0
Downloads
121
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Dti2143 chapter 5

  1. 1. CHAPTER 6<br />FUNCTION<br />1<br />
  2. 2. What is function?<br />A function is a section of a program that performs a specific task .<br />Solving a problem using different functions makes programming much simpler with fewer defects .<br />It’s a solution for a big project that split into small sub project. <br />
  3. 3. Overview<br />Same book published in several volumes.<br />Easily manageable<br />Huge Book of 3000 pages<br />
  4. 4. Advantages of Functions<br />Problem can be viewed in a smaller scope<br />Program development are much faster compared to the common structure<br />Program becomes easier to maintain<br />
  5. 5. Classification of Functions<br />Library functions<br /><ul><li>defined in the language
  6. 6. provided along with the compiler</li></ul>Example:printf(), scanf() etc.<br />User Defined functions<br /><ul><li> written by the user</li></ul>Example:main() or any other user-defined function<br />
  7. 7. More about Function..<br />Functions are used to perform a specific task on a set of values<br />Values can be passed to functions so that the function performs the task on these values<br />Values passed to the function are called arguments<br />After the function performs the task, it can send back the results to the calling function.<br />The value sent back by the function is called return value<br />A function can return back only one valueto the calling function<br />
  8. 8. Writing User-Defined Functions<br />intfnAdd(int iNumber1, int iNumber2)<br />{<br /> /* Variable declaration*/<br />intiSum;<br /> /* Find the sum */<br />iSum = iNumber1 + iNumber2;<br /> /* Return the result */<br /> return (iSum);<br />}<br />Return data type<br />Arguments (Parameters)<br />Function header<br />Function Body<br />Can also be written as return isum;<br />
  9. 9. Example1: Writing User-Defined Functions<br />void fnDisplayPattern(unsigned intiCount)<br />{<br /> unsigned intiLoopIndex;<br /> for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {<br />printf(“*”);<br /> }<br /> /* return is optional */<br /> return;<br />} <br />
  10. 10. Example: Writing User-Defined Functions<br />Example2 <br />intfnAdd(int iNumber1, int iNumber2)<br />{<br /> /* Return the result */Can also be written as <br /> return (iNumber1 + iNumber2);<br />} <br />=======================================================<br />Example3<br />/* Function to display “UTHM.” */<br />void fnCompanyNameDisplay()<br />{<br />printf(“UTHM.”);<br />} <br />
  11. 11. Returning values<br /><ul><li>The result of the function can be given back to the calling functions
  12. 12. Return statement is used to return a value to the calling function
  13. 13. Syntax:</li></ul>return (expression) ;<br /><ul><li>Example:</li></ul>return(iNumber * iNumber); <br /> return 0;<br /> return (3);<br /> return;<br /> return (10 * i);<br />
  14. 14. Function Terminologies<br />Function Prototype<br />void fnDisplay() ;<br />int main(int argc, char **argv) {<br /> fnDisplay();<br /> return 0;<br />}<br />void fnDisplay() {<br /> printf(“Hello World”);<br />}<br />Calling Function<br />Function Call Statement<br />Function Definition<br />Called Function<br />
  15. 15. Formal and Actual Parameters<br /><ul><li>The variables declared in the function header are called as formal parameters
  16. 16. The variables or constants that are passed in the function call are called as actualparameters
  17. 17. The formal parameter names and actual parameters names can be the same or different </li></li></ul><li>Functions – Example<br />intfnAdd(int iNumber1, int iNumber2) ;<br />int main(intargc, char **argv) {<br />int iResult,iValue1, iValue2;<br /> /* Function is called here */<br />iResult = fnAdd(iValue1, iValue2);<br />printf(“Sum of %d and %d is %dn”,iValue1, iValue2, iResult);<br /> return 0;<br />}<br />/* Function to add two integers */<br />intfnAdd(int iNumber1, int iNumber2)<br />{<br /> /* Variable declaration*/<br />intiSum;<br />iSum = iNumber1 + iNumber2; /* Find the sum */<br /> return (iSum); /* Return the result */<br />}<br />Actual Argument<br />Formal Argument<br />Return value<br />
  18. 18. Types of Function in C Language<br />Function Definition<br />Function Calls<br />Function Prototypes<br />
  19. 19. Element Of Functions<br />Function definitions<br />The first line<br /> A function type<br />A function name<br />An optional list of formal parameters enclosed in parenthesis<br />Eg: <br />function_type function_name(formal parameters)<br />The body of the function<br />The function body is the expression of the algorithm for the <br />module in C.<br />The function body consist of variable declarations and statements<br />
  20. 20. Example of Function Definition<br />void print_menu(void)<br />/* example of function definition. The first line specifies the type of the function as void. This type of function will not return a value under its name. If a function is designed such that it does not return any value under its name, its type must be Void.*/<br />{<br />printf(“THIS PROGRAM DRAWS A RECTANGLE OR A TRIANGLE ON THE”);<br />printf(“SCREEN.n”);<br />printf(“Enter 1 to draw a rectangle.n”);<br />printf(“Enter 2 to draw a triangle.”);<br />} /*end function print_menu*/<br />
  21. 21. Function Calls<br />A function call requires the name of the function followed by a list of actual parameters (or arguments), if any enclosed in parentheses.<br />If a function has no formal parameters in its definition, it cannot have any actual parameters in calls to it.<br />In this case, in a function call, the name of the function must be followed by the function call operator, (). To indicate that it has no parameters<br /> Eg1 : Function that has no parameters<br /> polynomial ()<br />
  22. 22. The actual parameters may be expressed as constants, single variables or more complex expressions.<br />Eg2: Function that return value to y<br />y=polynomial(x);<br />Eg3: Function that does not returns anything<br />polynomial (a,b,c)<br />
  23. 23. Example Function that Return Value<br />/* determine the largest of three integer quantities*/<br />#include <stdio.h><br />#include <conio.h><br />int maximum (intx,int y)<br />{<br />int z;<br /> z=(x>=y)? x :y ;<br /> return(z);<br />}<br />main()<br />{<br />inta,b,c,d;<br /> /* read the integer quantities*/<br />printf("na=");<br />scanf("%d",&a);<br />printf("nb=");<br />scanf("%d",&b);<br />printf("nc = ");<br />scanf("%d",&c);<br /> /*calculate and display the maximum value*/<br /> d=maximum(a,b);<br />printf("nnmaximum =%d",maximum(c,d));<br />getch();<br /> }<br />
  24. 24. Function Prototypes<br />In general, all function in C must be declared<br />But function main, must not be declared.<br />Function prototype consist of<br />A function type<br />A function name<br />A list of function parameters, the list of function parameter types is written as (void) or (). If the function has more than one formal parameter, the parameter types in the list must be saparated by commas.<br />Eg format:<br />function_typefunction_name(parameters); <br />
  25. 25. Example of Function Prototype <br />Format: <br />function_typefunction_name(parameters);<br />Example:<br />void print_menu(void);<br />double squared (double number);<br />intget_menu_choice(void);<br />
  26. 26. Function prototype can be placed in the source file outside function definition and in a function definition.<br />
  27. 27. Outside Function Definition<br />Example of outside function definition:Global prototype<br />If a function prototype is global, any function in the program may use it because of this flexibility. <br />Global prototype will be place after the processor directives and before the definition or function main.<br />
  28. 28. Inside Function Definition<br />Example of inside function definition: Local prototype<br />The variables that are declared inside a function are called as local variables<br />Their scope is only within the function in which they are declared <br />These variables cannot be accessed outside the function <br />Local variables exist only till the function terminates its execution<br />The initial values of local variables are garbage values<br />
  29. 29. Do and Don’t in Function<br />
  30. 30. Passing Arguments to a Function<br />List them in parentheses following the function name.<br />The number of arguments and the type of each arguments must match the parameter in the function header and prototype.<br />Example<br />if a function is defined to take two type intarguments, you must pass it exactly two intarguments.<br />
  31. 31. Each argument cab be any valid C expression such as:<br />A constant<br />A variable<br />A mathematical or logical expression or event another function( one with a return value)<br />
  32. 32. <ul><li>Example:</li></ul>X=half (third(square(half(y))));<br />How to solve it?<br />The program first calls half(), passing it y as an argument.<br />When execution returns from half(), the program calls square(), passing half()’s return values as the argument.<br />Then, half() is called again, this time with third()’s return values as an argument<br />Finally, half()’s return value is assigned to the variable x.<br />
  33. 33. The following is an equivalent piece of code:<br />a= half(y);<br />b=square(a);<br />c= third(b);<br />x= half(c);<br />
  34. 34. Recursion <br />The term recursion refers to a situation in which a function calls itself either directly or indirectly.<br />Indirectly recursion:<br />Occurs when one functions and they can be useful in some situations.<br />This type of recursion can be used to calculated the factorial of a number and others situation.<br />
  35. 35. /*Demonstrates function recursion. Calculate the factorial of a number*/<br />#include <stdio.h><br />unsigned intf,x;<br />unsigned int factorial(unsigned int a);<br />main()<br />{<br /> puts ("Enter an integer value between 1 and 8:");<br />scanf("%d",&x); <br />if(x>8||x<1) {<br />printf("Only values from 1 to 8 are acceptable!");}<br />else{<br />f=factorial(x);<br />printf("%u factorial equals %un",x,f);} <br /> return 0;<br />}<br />unsigned int factorial (unsigned int a){<br /> if (a==1) <br /> return 1; <br /> else{<br /> a *=factorial(a-1);<br /> return a;<br />} }<br />
  36. 36. Others examples..<br />
  37. 37. Example – Finding the sum of two numbers using functions ( No parameter passing and no return)<br />#include <stdio.h><br />#include <conio.h><br />void fnSum();<br />int main( intargc, char **argv ) {<br />fnSum();<br />getch();<br /> return 0;<br />}<br />void fnSum() {<br />int iNum1,iNum2,iSum;<br />printf("nEnter the two numbers:");<br />scanf("%d%d",&iNum1,&iNum2);<br />iSum = iNum1 + iNum2;<br />printf("nThe sum is %dn",iSum); <br />} <br />
  38. 38. Example – Finding the sum of two numbers using functions ( parameter passing )<br />#include <stdio.h><br />#include <conio.h><br />void fnSum( int iNumber1, int iNumber2);<br />int main( intargc, char **argv ) {<br />int iNumber1,iNumber2;<br />printf("nEnter the two numbers:");<br />scanf("%d%d",&iNumber1,&iNumber2);<br />fnSum(iNumber1,iNumber2);<br />getch();<br /> return 0;<br />}<br />void fnSum(int iNum1,int iNum2){ <br />intiSum;<br />iSum=iNum1 + iNum2;<br />printf("nThe sum is %dn",iSum);<br />}<br />
  39. 39. Example – Finding the sum of two numbers using functions ( parameter passing and returning value)<br />#include <stdio.h><br />#include <conio.h><br />intfnSum( int iNumber1, int iNumber2);<br />int main( intargc, char **argv ){<br />int iNumber1,iNumber2,iSum;<br />printf("nEnter the two numbers:");<br />scanf("%d%d",&iNumber1,&iNumber2);<br />iSum = fnSum(iNumber1,iNumber2);<br />printf("nThe sum is %dn",iSum);<br />getch();<br /> return 0;<br />}<br />intfnSum(int iNum1,int iNum2){<br />intiTempSum;<br />iTempSum=iNum1 + iNum2;<br /> return iTempSum;<br />}<br />
  40. 40. Simple Example 1<br />#include<stdio.h><br />#include<conio.h><br />int addition (int a, int b)<br />{<br /> int r;<br /> r=a+b;<br /> return (r);<br />}<br />int main ()<br />{<br /> int z;<br /> z = addition (5,3);<br /> printf("The result is %d",z);<br /> getch();<br /> return 0;<br />}<br />
  41. 41. #include<stdio.h><br />#include<conio.h><br />int subtraction (int a, int b)<br />{<br /> int r;<br /> r=a-b;<br /> return (r);<br />}<br />int main ()<br />{<br /> int x=5, y=3, z;<br /> z = subtraction (7,2);<br /> printf("The first result is %dn",z);<br /> printf("The second result is %dn",subtraction (7,2));<br /> printf("The third result is %dn",subtraction (x,y));<br /> z= 4 + subtraction (x,y);<br /> printf("The fourth result is %dn",z);<br /> getch();<br /> return 0;<br />}<br />
  42. 42. Thank you !<br />38<br />38<br />

×