CHAPTER 6FUNCTION1
What is function?A function is a section of a program that performs a specific task .Solving a problem using different functions makes programming much simpler with fewer defects .It’s a solution for a big project that split into small sub project.
OverviewSame book published in several volumes.Easily manageableHuge Book of 3000 pages
Advantages of FunctionsProblem can be viewed in a smaller scopeProgram development are much faster compared to the common structureProgram becomes easier to maintain
Classification of FunctionsLibrary  functionsdefined in the language
provided along with the compilerExample:printf(), scanf() etc.User Defined functions written by the userExample:main() or any other user-defined function
More about Function..Functions are used to perform a specific task on a set of valuesValues can be passed to functions so that the function performs the task on these valuesValues passed to the function are called argumentsAfter the function performs the task, it can send back the results to the calling function.The value sent back by the function is called return valueA function can return back only one valueto the calling function
Writing User-Defined FunctionsintfnAdd(int iNumber1, int iNumber2){	/* Variable declaration*/intiSum;	/* Find the sum */iSum = iNumber1 + iNumber2;	/* Return the result */	return (iSum);}Return data typeArguments (Parameters)Function headerFunction BodyCan also be written as return isum;
Example1: Writing User-Defined Functionsvoid fnDisplayPattern(unsigned intiCount){	unsigned intiLoopIndex;	for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {printf(“*”);	}	/* return is optional */	return;}
Example: Writing User-Defined FunctionsExample2 intfnAdd(int iNumber1, int iNumber2){	/* Return the result */Can also be written as 	return (iNumber1 + iNumber2);} =======================================================Example3/* Function to display “UTHM.” */void fnCompanyNameDisplay(){printf(“UTHM.”);}
Returning valuesThe result of the function can be given back to the calling functions
Return statement is used to return a value to the calling function
Syntax:return (expression) ;Example:return(iNumber * iNumber);	      return 0;      return (3);      return;      return (10 * i);
Function TerminologiesFunction Prototypevoid fnDisplay() ;int main(int argc, char **argv) {	fnDisplay();	return 0;}void fnDisplay() {	printf(“Hello World”);}Calling FunctionFunction Call StatementFunction DefinitionCalled Function
Formal and Actual ParametersThe variables declared in the function header are called as formal parameters
The variables or constants that are passed in the function call are called as actualparameters
The formal parameter names and actual parameters names can be the same or different Functions – ExampleintfnAdd(int iNumber1, int iNumber2) ;int main(intargc, char **argv) {int iResult,iValue1, iValue2;	/* Function is called here */iResult = fnAdd(iValue1, iValue2);printf(“Sum of %d and %d is %d\n”,iValue1, iValue2, iResult);	return 0;}/* Function to add two integers */intfnAdd(int iNumber1, int iNumber2){	 /* Variable declaration*/intiSum;iSum = iNumber1 + iNumber2; /* Find the sum */	 return (iSum); 	/* Return the result */}Actual ArgumentFormal ArgumentReturn value
Types of Function in C LanguageFunction DefinitionFunction CallsFunction Prototypes
Element Of FunctionsFunction definitionsThe first line	A function typeA function nameAn optional list of formal parameters enclosed in parenthesisEg: function_type   function_name(formal parameters)The body of the functionThe function body is the expression of the algorithm for the module in C.The function body consist of variable declarations and statements
Example of Function Definitionvoid print_menu(void)/* 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.*/{printf(“THIS PROGRAM DRAWS A RECTANGLE OR A TRIANGLE ON THE”);printf(“SCREEN.\n”);printf(“Enter 1 to draw a rectangle.\n”);printf(“Enter 2 to draw a triangle.”);} /*end function print_menu*/
Function CallsA function call requires the name of the function followed by a list of actual parameters (or arguments), if any enclosed in parentheses.If a function has no formal parameters in its definition, it cannot have any actual parameters in calls to it.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          Eg1 : Function that has no parameters      polynomial ()
The actual parameters may be expressed as constants, single variables or more complex expressions.Eg2: Function that return value to yy=polynomial(x);Eg3: Function that does not returns anythingpolynomial (a,b,c)
Example Function that Return Value/* determine the largest of three integer quantities*/#include <stdio.h>#include <conio.h>int maximum (intx,int y){int z;    z=(x>=y)? x :y ;    return(z);}main(){inta,b,c,d;      /* read the integer quantities*/printf("\na=");scanf("%d",&a);printf("\nb=");scanf("%d",&b);printf("\nc = ");scanf("%d",&c);      /*calculate and display the maximum value*/      d=maximum(a,b);printf("\n\nmaximum =%d",maximum(c,d));getch();      }
Function PrototypesIn general, all function in C must be declaredBut function main, must not be declared.Function prototype consist ofA function typeA function nameA 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.Eg format:function_typefunction_name(parameters);
Example of Function Prototype	Format: function_typefunction_name(parameters);Example:void print_menu(void);double squared (double number);intget_menu_choice(void);
Function prototype can be placed in the source file outside function definition and in a function definition.
Outside Function DefinitionExample of outside function definition:Global prototypeIf a function prototype is global, any function in the program may use it because of this flexibility. Global prototype will be place after the processor directives and before the definition or function main.
Inside Function DefinitionExample of inside function definition: Local prototypeThe variables that are declared inside a function are called as local variablesTheir scope is only within the function in which they are declared These variables cannot be accessed outside the function Local variables exist only till the function terminates its executionThe initial values of local variables are garbage values
Do and Don’t in Function
Passing Arguments to a FunctionList them in parentheses following the function name.The number of arguments and the type of each arguments must match the parameter in the function header and prototype.Exampleif a function is defined to take two type intarguments, you must pass it exactly two intarguments.
Each argument cab be any valid C expression such as:A constantA variableA mathematical or logical expression or event another function( one with a return value)
Example:X=half (third(square(half(y))));How to solve it?The program first calls half(), passing it y as an argument.When execution returns from half(), the program calls square(), passing half()’s return values as the argument.Then, half() is called again, this time with third()’s return values as an argumentFinally, half()’s return value is assigned to the variable x.
The following is an equivalent piece of code:a= half(y);b=square(a);c= third(b);x= half(c);
Recursion	The term recursion refers to a situation in which a function calls itself either directly or indirectly.Indirectly recursion:Occurs when one functions and they can be useful in some situations.This type of recursion can be used to calculated the factorial of a number and others situation.
/*Demonstrates function recursion. Calculate the factorial of a number*/#include <stdio.h>unsigned intf,x;unsigned int factorial(unsigned int a);main(){ puts ("Enter an integer value between 1 and 8:");scanf("%d",&x); if(x>8||x<1) {printf("Only values from 1 to 8 are acceptable!");}else{f=factorial(x);printf("%u factorial equals %u\n",x,f);}        return 0;}unsigned int factorial (unsigned int a){         if (a==1)                  return 1;                  else{              a *=factorial(a-1);              return a;}	}
Others examples..
Example – Finding the sum of two numbers using functions ( No parameter passing and no return)#include <stdio.h>#include <conio.h>void fnSum();int main( intargc, char **argv ) {fnSum();getch();    return 0;}void fnSum() {int iNum1,iNum2,iSum;printf("\nEnter the two numbers:");scanf("%d%d",&iNum1,&iNum2);iSum = iNum1 + iNum2;printf("\nThe sum is %d\n",iSum);	}
Example – Finding the sum of two numbers using functions ( parameter passing )#include <stdio.h>#include <conio.h>void fnSum( int iNumber1, int  iNumber2);int main( intargc, char **argv ) {int iNumber1,iNumber2;printf("\nEnter the two numbers:");scanf("%d%d",&iNumber1,&iNumber2);fnSum(iNumber1,iNumber2);getch();	return 0;}void fnSum(int iNum1,int iNum2){    intiSum;iSum=iNum1 + iNum2;printf("\nThe sum is %d\n",iSum);}

Dti2143 chapter 5

  • 1.
  • 2.
    What is function?Afunction is a section of a program that performs a specific task .Solving a problem using different functions makes programming much simpler with fewer defects .It’s a solution for a big project that split into small sub project.
  • 3.
    OverviewSame book publishedin several volumes.Easily manageableHuge Book of 3000 pages
  • 4.
    Advantages of FunctionsProblemcan be viewed in a smaller scopeProgram development are much faster compared to the common structureProgram becomes easier to maintain
  • 5.
    Classification of FunctionsLibrary functionsdefined in the language
  • 6.
    provided along withthe compilerExample:printf(), scanf() etc.User Defined functions written by the userExample:main() or any other user-defined function
  • 7.
    More about Function..Functionsare used to perform a specific task on a set of valuesValues can be passed to functions so that the function performs the task on these valuesValues passed to the function are called argumentsAfter the function performs the task, it can send back the results to the calling function.The value sent back by the function is called return valueA function can return back only one valueto the calling function
  • 8.
    Writing User-Defined FunctionsintfnAdd(intiNumber1, int iNumber2){ /* Variable declaration*/intiSum; /* Find the sum */iSum = iNumber1 + iNumber2; /* Return the result */ return (iSum);}Return data typeArguments (Parameters)Function headerFunction BodyCan also be written as return isum;
  • 9.
    Example1: Writing User-DefinedFunctionsvoid fnDisplayPattern(unsigned intiCount){ unsigned intiLoopIndex; for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) {printf(“*”); } /* return is optional */ return;}
  • 10.
    Example: Writing User-DefinedFunctionsExample2 intfnAdd(int iNumber1, int iNumber2){ /* Return the result */Can also be written as return (iNumber1 + iNumber2);} =======================================================Example3/* Function to display “UTHM.” */void fnCompanyNameDisplay(){printf(“UTHM.”);}
  • 11.
    Returning valuesThe resultof the function can be given back to the calling functions
  • 12.
    Return statement isused to return a value to the calling function
  • 13.
    Syntax:return (expression) ;Example:return(iNumber* iNumber); return 0; return (3); return; return (10 * i);
  • 14.
    Function TerminologiesFunction PrototypevoidfnDisplay() ;int main(int argc, char **argv) { fnDisplay(); return 0;}void fnDisplay() { printf(“Hello World”);}Calling FunctionFunction Call StatementFunction DefinitionCalled Function
  • 15.
    Formal and ActualParametersThe variables declared in the function header are called as formal parameters
  • 16.
    The variables orconstants that are passed in the function call are called as actualparameters
  • 17.
    The formal parameternames and actual parameters names can be the same or different Functions – ExampleintfnAdd(int iNumber1, int iNumber2) ;int main(intargc, char **argv) {int iResult,iValue1, iValue2; /* Function is called here */iResult = fnAdd(iValue1, iValue2);printf(“Sum of %d and %d is %d\n”,iValue1, iValue2, iResult); return 0;}/* Function to add two integers */intfnAdd(int iNumber1, int iNumber2){ /* Variable declaration*/intiSum;iSum = iNumber1 + iNumber2; /* Find the sum */ return (iSum); /* Return the result */}Actual ArgumentFormal ArgumentReturn value
  • 18.
    Types of Functionin C LanguageFunction DefinitionFunction CallsFunction Prototypes
  • 19.
    Element Of FunctionsFunctiondefinitionsThe first line A function typeA function nameAn optional list of formal parameters enclosed in parenthesisEg: function_type function_name(formal parameters)The body of the functionThe function body is the expression of the algorithm for the module in C.The function body consist of variable declarations and statements
  • 20.
    Example of FunctionDefinitionvoid print_menu(void)/* 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.*/{printf(“THIS PROGRAM DRAWS A RECTANGLE OR A TRIANGLE ON THE”);printf(“SCREEN.\n”);printf(“Enter 1 to draw a rectangle.\n”);printf(“Enter 2 to draw a triangle.”);} /*end function print_menu*/
  • 21.
    Function CallsA functioncall requires the name of the function followed by a list of actual parameters (or arguments), if any enclosed in parentheses.If a function has no formal parameters in its definition, it cannot have any actual parameters in calls to it.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 Eg1 : Function that has no parameters polynomial ()
  • 22.
    The actual parametersmay be expressed as constants, single variables or more complex expressions.Eg2: Function that return value to yy=polynomial(x);Eg3: Function that does not returns anythingpolynomial (a,b,c)
  • 23.
    Example Function thatReturn Value/* determine the largest of three integer quantities*/#include <stdio.h>#include <conio.h>int maximum (intx,int y){int z; z=(x>=y)? x :y ; return(z);}main(){inta,b,c,d; /* read the integer quantities*/printf("\na=");scanf("%d",&a);printf("\nb=");scanf("%d",&b);printf("\nc = ");scanf("%d",&c); /*calculate and display the maximum value*/ d=maximum(a,b);printf("\n\nmaximum =%d",maximum(c,d));getch(); }
  • 24.
    Function PrototypesIn general,all function in C must be declaredBut function main, must not be declared.Function prototype consist ofA function typeA function nameA 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.Eg format:function_typefunction_name(parameters);
  • 25.
    Example of FunctionPrototype Format: function_typefunction_name(parameters);Example:void print_menu(void);double squared (double number);intget_menu_choice(void);
  • 26.
    Function prototype canbe placed in the source file outside function definition and in a function definition.
  • 27.
    Outside Function DefinitionExampleof outside function definition:Global prototypeIf a function prototype is global, any function in the program may use it because of this flexibility. Global prototype will be place after the processor directives and before the definition or function main.
  • 28.
    Inside Function DefinitionExampleof inside function definition: Local prototypeThe variables that are declared inside a function are called as local variablesTheir scope is only within the function in which they are declared These variables cannot be accessed outside the function Local variables exist only till the function terminates its executionThe initial values of local variables are garbage values
  • 29.
    Do and Don’tin Function
  • 30.
    Passing Arguments toa FunctionList them in parentheses following the function name.The number of arguments and the type of each arguments must match the parameter in the function header and prototype.Exampleif a function is defined to take two type intarguments, you must pass it exactly two intarguments.
  • 31.
    Each argument cabbe any valid C expression such as:A constantA variableA mathematical or logical expression or event another function( one with a return value)
  • 32.
    Example:X=half (third(square(half(y))));How tosolve it?The program first calls half(), passing it y as an argument.When execution returns from half(), the program calls square(), passing half()’s return values as the argument.Then, half() is called again, this time with third()’s return values as an argumentFinally, half()’s return value is assigned to the variable x.
  • 33.
    The following isan equivalent piece of code:a= half(y);b=square(a);c= third(b);x= half(c);
  • 34.
    Recursion The term recursionrefers to a situation in which a function calls itself either directly or indirectly.Indirectly recursion:Occurs when one functions and they can be useful in some situations.This type of recursion can be used to calculated the factorial of a number and others situation.
  • 35.
    /*Demonstrates function recursion.Calculate the factorial of a number*/#include <stdio.h>unsigned intf,x;unsigned int factorial(unsigned int a);main(){ puts ("Enter an integer value between 1 and 8:");scanf("%d",&x); if(x>8||x<1) {printf("Only values from 1 to 8 are acceptable!");}else{f=factorial(x);printf("%u factorial equals %u\n",x,f);} return 0;}unsigned int factorial (unsigned int a){ if (a==1) return 1; else{ a *=factorial(a-1); return a;} }
  • 36.
  • 37.
    Example – Findingthe sum of two numbers using functions ( No parameter passing and no return)#include <stdio.h>#include <conio.h>void fnSum();int main( intargc, char **argv ) {fnSum();getch(); return 0;}void fnSum() {int iNum1,iNum2,iSum;printf("\nEnter the two numbers:");scanf("%d%d",&iNum1,&iNum2);iSum = iNum1 + iNum2;printf("\nThe sum is %d\n",iSum); }
  • 38.
    Example – Findingthe sum of two numbers using functions ( parameter passing )#include <stdio.h>#include <conio.h>void fnSum( int iNumber1, int iNumber2);int main( intargc, char **argv ) {int iNumber1,iNumber2;printf("\nEnter the two numbers:");scanf("%d%d",&iNumber1,&iNumber2);fnSum(iNumber1,iNumber2);getch(); return 0;}void fnSum(int iNum1,int iNum2){ intiSum;iSum=iNum1 + iNum2;printf("\nThe sum is %d\n",iSum);}