SlideShare a Scribd company logo
CHAPTER 6 FUNCTION 1
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.
Overview Same book published in several volumes. Easily manageable Huge Book of 3000 pages
Advantages of Functions Problem can be viewed in a smaller scope Program development are much faster compared to the common structure Program becomes easier to maintain
Classification of Functions Library  functions ,[object Object]
provided along with the compilerExample:printf(), scanf() etc. User Defined functions ,[object Object],Example:main() or any other user-defined function
More about Function.. Functions are used to perform a specific task on a set of values Values can be passed to functions so that the function performs the task on these values Values passed to the function are called arguments After 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 value A function can return back only one valueto the calling function
Writing User-Defined Functions intfnAdd(int iNumber1, int iNumber2) { 	/* Variable declaration*/ intiSum; 	/* Find the sum */ iSum = iNumber1 + iNumber2; 	/* Return the result */ 	return (iSum); } Return data type Arguments (Parameters) Function header Function Body Can also be written as return isum;
Example1: Writing User-Defined Functions void fnDisplayPattern(unsigned intiCount) { 	unsigned intiLoopIndex; 	for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) { printf(“*”); 	} 	/* return is optional */ 	return; }
Example: Writing User-Defined Functions Example2  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 values ,[object Object]
Return statement is used to return a value to the calling function
Syntax:return (expression) ; ,[object Object],return(iNumber * iNumber);	       return 0;       return (3);       return;       return (10 * i);
Function Terminologies Function Prototype void fnDisplay() ; int main(int argc, char **argv) { 	fnDisplay(); 	return 0; } void fnDisplay() { 	printf(“Hello World”); } Calling Function Function Call Statement Function Definition Called Function
Formal and Actual Parameters ,[object Object]
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 ,[object Object]
Types of Function in C Language Function Definition Function Calls Function Prototypes
Element Of Functions Function definitions The first line 	A function type A function name An optional list of formal parameters enclosed in parenthesis Eg:  function_type   function_name(formal parameters) The body of the function The 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 Definition void 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.”); printf(“Enter 1 to draw a rectangle.”); printf(“Enter 2 to draw a triangle.”); } /*end function print_menu*/
Function Calls A 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 y y=polynomial(x); Eg3: Function that does not returns anything polynomial (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("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); printf("c = "); scanf("%d",&c);       /*calculate and display the maximum value*/       d=maximum(a,b); printf("maximum =%d",maximum(c,d)); getch();       }
Function Prototypes In general, all function in C must be declared But function main, must not be declared. Function prototype consist of A function type A function name 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. 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 Definition Example of outside function definition:Global prototype If 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 Definition Example of inside function definition: Local prototype The variables that are declared inside a function are called as local variables Their 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 execution The initial values of local variables are garbage values
Do and Don’t in Function
Passing Arguments to a Function List 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. Example if 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 constant A variable A mathematical or logical expression or event another function( one with a return value)
[object Object],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 argument Finally, 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",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("Enter the two numbers:"); scanf("%d%d",&iNum1,&iNum2); iSum = iNum1 + iNum2; printf("The sum is %d",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("Enter 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("The sum is %d",iSum); }

More Related Content

What's hot

Function lecture
Function lectureFunction lecture
Function lecture
DIT University, Dehradun
 
Functions in c
Functions in cFunctions in c
Functions in c
Innovative
 
Function in c program
Function in c programFunction in c program
Function in c program
CGC Technical campus,Mohali
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions in c
Functions in cFunctions in c
Functions in c
KavithaMuralidharan2
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
imtiazalijoono
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
C function presentation
C function presentationC function presentation
C function presentation
Touhidul Shawan
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
psaravanan1985
 
C functions
C functionsC functions
Presentation on function
Presentation on functionPresentation on function
Presentation on function
Abu Zaman
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functionsvinay arora
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
Dr-Dipali Meher
 

What's hot (19)

Function lecture
Function lectureFunction lecture
Function lecture
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Functions
FunctionsFunctions
Functions
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
Functions
FunctionsFunctions
Functions
 
C function presentation
C function presentationC function presentation
C function presentation
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
C functions
C functionsC functions
C functions
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
 
Function in C
Function in CFunction in C
Function in C
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
 
C Prog - Functions
C Prog - FunctionsC Prog - Functions
C Prog - Functions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 

Viewers also liked

Rèdais & IED_Piovano
Rèdais & IED_PiovanoRèdais & IED_Piovano
Rèdais & IED_PiovanoRèdais
 
Ance_D'Annibale_24052011
Ance_D'Annibale_24052011Ance_D'Annibale_24052011
Ance_D'Annibale_24052011Rèdais
 
Que saben de_ciencias_os_nosos_estudantes
Que saben de_ciencias_os_nosos_estudantesQue saben de_ciencias_os_nosos_estudantes
Que saben de_ciencias_os_nosos_estudantesjuanapardo
 
Existence
ExistenceExistence
Existence
Haleem Khan
 
Ance_Gallesio_24052011
Ance_Gallesio_24052011Ance_Gallesio_24052011
Ance_Gallesio_24052011Rèdais
 
Metabolismo agueda
Metabolismo aguedaMetabolismo agueda
Metabolismo aguedajuanapardo
 
A Design Thinking Approach to Online Engagement
A Design Thinking Approach to Online EngagementA Design Thinking Approach to Online Engagement
A Design Thinking Approach to Online Engagement
Cloud View Pte Ltd
 
Rèdais & IED_Cugusi
Rèdais & IED_CugusiRèdais & IED_Cugusi
Rèdais & IED_CugusiRèdais
 
Assistive technology web_quest_vicki_dowse
Assistive technology web_quest_vicki_dowseAssistive technology web_quest_vicki_dowse
Assistive technology web_quest_vicki_dowsevdowse
 
Teaching people how to treat you
Teaching people how to treat youTeaching people how to treat you
Teaching people how to treat you
Brad Hyde
 
Handout mid term 1 kelas x mipa sma citra kasih jkt
Handout mid term 1 kelas x mipa sma citra kasih jktHandout mid term 1 kelas x mipa sma citra kasih jkt
Handout mid term 1 kelas x mipa sma citra kasih jkt
Fajar Adinugraha
 
Nha Tran Brand Brief
Nha Tran Brand BriefNha Tran Brand Brief
Nha Tran Brand Brief
Ernest Chan
 
Proceso de cambios vip
Proceso de cambios vipProceso de cambios vip
Proceso de cambios vip
Felix J. Baute S.
 
برنامج معالجة الكلمات
برنامج معالجة الكلماتبرنامج معالجة الكلمات
برنامج معالجة الكلماتSunflower Al-mahrouqi
 
Vocabulary cards
Vocabulary cardsVocabulary cards
Vocabulary cards
Gabriela Villamarin
 
Ud 0 final juani
Ud 0 final juaniUd 0 final juani
Ud 0 final juanijuanapardo
 
Skin care massager
Skin care massagerSkin care massager
Skin care massager
ahrong
 
Videos caminando con caverncolas
Videos caminando con caverncolasVideos caminando con caverncolas
Videos caminando con caverncolasjuanapardo
 
John dahlsen
John dahlsenJohn dahlsen
John dahlsen
Krystle Levings
 

Viewers also liked (20)

Rèdais & IED_Piovano
Rèdais & IED_PiovanoRèdais & IED_Piovano
Rèdais & IED_Piovano
 
Ance_D'Annibale_24052011
Ance_D'Annibale_24052011Ance_D'Annibale_24052011
Ance_D'Annibale_24052011
 
GEOG101 Chapter 4 Lecture
GEOG101 Chapter 4 LectureGEOG101 Chapter 4 Lecture
GEOG101 Chapter 4 Lecture
 
Que saben de_ciencias_os_nosos_estudantes
Que saben de_ciencias_os_nosos_estudantesQue saben de_ciencias_os_nosos_estudantes
Que saben de_ciencias_os_nosos_estudantes
 
Existence
ExistenceExistence
Existence
 
Ance_Gallesio_24052011
Ance_Gallesio_24052011Ance_Gallesio_24052011
Ance_Gallesio_24052011
 
Metabolismo agueda
Metabolismo aguedaMetabolismo agueda
Metabolismo agueda
 
A Design Thinking Approach to Online Engagement
A Design Thinking Approach to Online EngagementA Design Thinking Approach to Online Engagement
A Design Thinking Approach to Online Engagement
 
Rèdais & IED_Cugusi
Rèdais & IED_CugusiRèdais & IED_Cugusi
Rèdais & IED_Cugusi
 
Assistive technology web_quest_vicki_dowse
Assistive technology web_quest_vicki_dowseAssistive technology web_quest_vicki_dowse
Assistive technology web_quest_vicki_dowse
 
Teaching people how to treat you
Teaching people how to treat youTeaching people how to treat you
Teaching people how to treat you
 
Handout mid term 1 kelas x mipa sma citra kasih jkt
Handout mid term 1 kelas x mipa sma citra kasih jktHandout mid term 1 kelas x mipa sma citra kasih jkt
Handout mid term 1 kelas x mipa sma citra kasih jkt
 
Nha Tran Brand Brief
Nha Tran Brand BriefNha Tran Brand Brief
Nha Tran Brand Brief
 
Proceso de cambios vip
Proceso de cambios vipProceso de cambios vip
Proceso de cambios vip
 
برنامج معالجة الكلمات
برنامج معالجة الكلماتبرنامج معالجة الكلمات
برنامج معالجة الكلمات
 
Vocabulary cards
Vocabulary cardsVocabulary cards
Vocabulary cards
 
Ud 0 final juani
Ud 0 final juaniUd 0 final juani
Ud 0 final juani
 
Skin care massager
Skin care massagerSkin care massager
Skin care massager
 
Videos caminando con caverncolas
Videos caminando con caverncolasVideos caminando con caverncolas
Videos caminando con caverncolas
 
John dahlsen
John dahlsenJohn dahlsen
John dahlsen
 

Similar to Dti2143 chapter 5

C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser823678
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
ssuser2076d9
 
Recursion in C
Recursion in CRecursion in C
Recursion in Cv_jk
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
RITHIKA R S
 
C functions list
C functions listC functions list
Function
FunctionFunction
Function
mshoaib15
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
Saranya saran
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
KarthikSivagnanam2
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdffunctionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdf
mounikanarra3
 
Functions
FunctionsFunctions
Functions
zeeshan841
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
Arpit Meena
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 

Similar to Dti2143 chapter 5 (20)

C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
functions
functionsfunctions
functions
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
C functions list
C functions listC functions list
C functions list
 
Function
FunctionFunction
Function
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdffunctionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdf
 
Functions
FunctionsFunctions
Functions
 
Function
FunctionFunction
Function
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
 
6. function
6. function6. function
6. function
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 

More from alish sha

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9
alish sha
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)
alish sha
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation
alish sha
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifah
alish sha
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifah
alish sha
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)
alish sha
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13alish sha
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13alish sha
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012alish sha
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaboratealish sha
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1alish sha
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12
alish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Attn list test
Attn list testAttn list test
Attn list testalish sha
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303alish sha
 

More from alish sha (20)

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifah
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifah
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13
 
Lab 6
Lab 6Lab 6
Lab 6
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaborate
 
Lab sheet 1
Lab sheet 1Lab sheet 1
Lab sheet 1
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Final project
Final projectFinal project
Final project
 
Final project
Final projectFinal project
Final project
 
Attn list test
Attn list testAttn list test
Attn list test
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303
 

Recently uploaded

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 

Dti2143 chapter 5

  • 2. 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.
  • 3. Overview Same book published in several volumes. Easily manageable Huge Book of 3000 pages
  • 4. Advantages of Functions Problem can be viewed in a smaller scope Program development are much faster compared to the common structure Program becomes easier to maintain
  • 5.
  • 6.
  • 7. More about Function.. Functions are used to perform a specific task on a set of values Values can be passed to functions so that the function performs the task on these values Values passed to the function are called arguments After 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 value A function can return back only one valueto the calling function
  • 8. Writing User-Defined Functions intfnAdd(int iNumber1, int iNumber2) { /* Variable declaration*/ intiSum; /* Find the sum */ iSum = iNumber1 + iNumber2; /* Return the result */ return (iSum); } Return data type Arguments (Parameters) Function header Function Body Can also be written as return isum;
  • 9. Example1: Writing User-Defined Functions void fnDisplayPattern(unsigned intiCount) { unsigned intiLoopIndex; for (iLoopIndex = 1; iLoopIndex <= iCount; iLoopIndex++) { printf(“*”); } /* return is optional */ return; }
  • 10. Example: Writing User-Defined Functions Example2 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.
  • 12. Return statement is used to return a value to the calling function
  • 13.
  • 14. Function Terminologies Function Prototype void fnDisplay() ; int main(int argc, char **argv) { fnDisplay(); return 0; } void fnDisplay() { printf(“Hello World”); } Calling Function Function Call Statement Function Definition Called Function
  • 15.
  • 16. The variables or constants that are passed in the function call are called as actualparameters
  • 17.
  • 18. Types of Function in C Language Function Definition Function Calls Function Prototypes
  • 19. Element Of Functions Function definitions The first line A function type A function name An optional list of formal parameters enclosed in parenthesis Eg: function_type function_name(formal parameters) The body of the function The 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 Function Definition void 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.”); printf(“Enter 1 to draw a rectangle.”); printf(“Enter 2 to draw a triangle.”); } /*end function print_menu*/
  • 21. Function Calls A 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 ()
  • 22. The actual parameters may be expressed as constants, single variables or more complex expressions. Eg2: Function that return value to y y=polynomial(x); Eg3: Function that does not returns anything polynomial (a,b,c)
  • 23. 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("a="); scanf("%d",&a); printf("b="); scanf("%d",&b); printf("c = "); scanf("%d",&c); /*calculate and display the maximum value*/ d=maximum(a,b); printf("maximum =%d",maximum(c,d)); getch(); }
  • 24. Function Prototypes In general, all function in C must be declared But function main, must not be declared. Function prototype consist of A function type A function name 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. Eg format: function_typefunction_name(parameters);
  • 25. Example of Function Prototype Format: function_typefunction_name(parameters); Example: void print_menu(void); double squared (double number); intget_menu_choice(void);
  • 26. Function prototype can be placed in the source file outside function definition and in a function definition.
  • 27. Outside Function Definition Example of outside function definition:Global prototype If 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 Definition Example of inside function definition: Local prototype The variables that are declared inside a function are called as local variables Their 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 execution The initial values of local variables are garbage values
  • 29. Do and Don’t in Function
  • 30. Passing Arguments to a Function List 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. Example if a function is defined to take two type intarguments, you must pass it exactly two intarguments.
  • 31. Each argument cab be any valid C expression such as: A constant A variable A mathematical or logical expression or event another function( one with a return value)
  • 32.
  • 33. The following is an equivalent piece of code: a= half(y); b=square(a); c= third(b); x= half(c);
  • 34. 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.
  • 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",x,f);} return 0; } unsigned int factorial (unsigned int a){ if (a==1) return 1; else{ a *=factorial(a-1); return a; } }
  • 37. 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("Enter the two numbers:"); scanf("%d%d",&iNum1,&iNum2); iSum = iNum1 + iNum2; printf("The sum is %d",iSum); }
  • 38. 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("Enter 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("The sum is %d",iSum); }
  • 39. Example – Finding the sum of two numbers using functions ( parameter passing and returning value) #include <stdio.h> #include <conio.h> intfnSum( int iNumber1, int iNumber2); int main( intargc, char **argv ){ int iNumber1,iNumber2,iSum; printf("Enter the two numbers:"); scanf("%d%d",&iNumber1,&iNumber2); iSum = fnSum(iNumber1,iNumber2); printf("The sum is %d",iSum); getch(); return 0; } intfnSum(int iNum1,int iNum2){ intiTempSum; iTempSum=iNum1 + iNum2; return iTempSum; }
  • 40. Simple Example 1 #include<stdio.h> #include<conio.h> int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); printf("The result is %d",z); getch(); return 0; }
  • 41. #include<stdio.h> #include<conio.h> int subtraction (int a, int b) { int r; r=a-b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); printf("The first result is %d",z); printf("The second result is %d",subtraction (7,2)); printf("The third result is %d",subtraction (x,y)); z= 4 + subtraction (x,y); printf("The fourth result is %d",z); getch(); return 0; }
  • 42. Thank you ! 38 38