SlideShare a Scribd company logo
1 of 18
Unit IV
Function & Recursion
Functions
 A function is a self-contained block of
statements that perform a coherent
task of some kind. If you have a task
that is always performed in the same
way than instead of putting the same
functionality at every point we should
make function and can call by just
declaring function name.
#include<stdio.h>
void func1();
int main()
{
func1();
printf("nthis is first program with funtion");
return 0;
}
void func1()
{
printf("nthis is func1");
}
Output:
This is func1
This is the first program with function
Important points about function
 A function gets called when the function name is followed by a semincolon.
 A function is defined when function name is followed by a pair of braces in
which one or more statements may be present.
 Any function can be called from any other function. Even main can be called
from other function.
 A function calls itself such process known as recursion.
Elements of Functions
 Function Definition
 Function Call
 Function Declaration
Definition of Function
int func1()
{
int a;
printf("nthis is func1");
return 0;
}
Function Definition-
1. Function name
2. Function type
3. List of parameters
4. Local variable declaration
5. Function statement
6. A return statement
Return values and their type
A function may or may not send back any value to the calling function. If it does it is done through return
statement. Called function can only return only one value per call.
return;
or
return(expression)
return: will not return any value but will return the control back to the calling function.
If(error)
{
return(0);
}
Return expression: will return some value of the function back to the called function.
return(p);
return(x*y);
…
So basically, return serves two purposes:
 On executing the return statement, it immediately transfers the control back to
the calling function.
 It returns the value present in the parentheses after return, to the calling function.
Passing values between functions-
 Passing the vales to the function allows us to communicate with the function. Using this
we can pass our values in order to get the results, for that we need to specify the
function name with arguments.
 Example:
void main()
{
Funtion1();
Function2(a);
}
Function1()
{ }
Function2(int a)
{ }
Categories of Function-
 Functions with no arguments and no return value.
 Functions with arguments and no return value.
 Functions with no arguments and return a value.
 Functions that return multiple return values.
Swapping a Number – General
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integersn");
scanf("%d%d", &x, &y);
printf("Before SwappingnFirst integer = %dnSecond integer = %dn", x, y);
t = x;
x = y;
y = t;
printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y);
return 0;
}
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integersn");
scanf("%d%d", &x, &y);
printf("Before SwappingnFirst integer = %dnSecond integer = %dn", x, y);
swap(x,y);
printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y);
return 0;
}
void swap(int x, int y) //Swap function definition
{
int t;
t = x;
x = y;
y = t;
printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y);
}
Swapping a number
#include <stdio.h>
void swap(int*, int*); //Swap function declaration
int main()
{
int x, y;
printf("Enter the value of x and yn");
scanf("%d%d",&x,&y);
printf("Before Swappingnx = %dny = %dn", x, y);
swap(&x, &y);
printf("After Swappingnx = %dny = %dn", x, y);
return 0;
}
void swap(int *a, int *b) //Swap function definition
{
int t;
t = *b;
*b = *a;
*a = t;
}
Recursion
 Recursion is a special case where
function calls itself again and
again.
main()
{
printf(“this is the example of recursion”);
main();
}
…
Another example is factorial:
Factorial of n=n(n-1)(n-2)…….1
Factorial of 4=4*3*2*1 =24
factorial(int n)
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return(fact);
}
fact=3*factorial(2)
fact=3*2*factorial(1)
fact=3*2*1
fact=6
Tower of Hanoi
 Tower of Hanoi is a mathematical puzzle where we have three rods and n
disks. The objective of the puzzle is to move the entire stack to another
rod, obeying the following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
3. No disk may be placed on top of a smaller disk.
…
…
Desired Input/output
 Input : 2
Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
 Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
#include <stdio.h>
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n==1)
{
printf("nMove disk 1 from rod : %d",from_rod);
printf("nMove disk 1 to rod : %d",to_rod);
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
printf("nMove disk %d from rod : %d",n,from_rod);
printf("nMove disk %d to rod : %d",n,to_rod);
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 3; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

More Related Content

What's hot (20)

sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Heap sort
Heap sortHeap sort
Heap sort
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Linklist
LinklistLinklist
Linklist
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
skip list
skip listskip list
skip list
 
Linked lists
Linked listsLinked lists
Linked lists
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data Structure
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Hashing
HashingHashing
Hashing
 
Introduction to stack
Introduction to stackIntroduction to stack
Introduction to stack
 

Similar to Functions & Recursion

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Ziyauddin Shaik
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202Mahmoud Samir Fayed
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Recursion in C
Recursion in CRecursion in C
Recursion in Cv_jk
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptxajajkhan16
 
Recursion concepts by Divya
Recursion concepts by DivyaRecursion concepts by Divya
Recursion concepts by DivyaDivya Kumari
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181Mahmoud Samir Fayed
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageJenish Bhavsar
 

Similar to Functions & Recursion (20)

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
functions of C++
functions of C++functions of C++
functions of C++
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
 
functions
functionsfunctions
functions
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Pro
ProPro
Pro
 
Unit-I Recursion.pptx
Unit-I Recursion.pptxUnit-I Recursion.pptx
Unit-I Recursion.pptx
 
Scala functions
Scala functionsScala functions
Scala functions
 
Function in c
Function in cFunction in c
Function in c
 
Recursion concepts by Divya
Recursion concepts by DivyaRecursion concepts by Divya
Recursion concepts by Divya
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181
 
C++ lecture 03
C++   lecture 03C++   lecture 03
C++ lecture 03
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
 
Functions
FunctionsFunctions
Functions
 

More from Nishant Munjal

Database Management System
Database Management SystemDatabase Management System
Database Management SystemNishant Munjal
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointerNishant Munjal
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computersNishant Munjal
 
Shell Programming Concept
Shell Programming ConceptShell Programming Concept
Shell Programming ConceptNishant Munjal
 
Asynchronous Transfer Mode
Asynchronous Transfer ModeAsynchronous Transfer Mode
Asynchronous Transfer ModeNishant Munjal
 
Overview of Cloud Computing
Overview of Cloud ComputingOverview of Cloud Computing
Overview of Cloud ComputingNishant Munjal
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries InformationNishant Munjal
 
Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization TechniquesNishant Munjal
 
Transaction Processing Concept
Transaction Processing ConceptTransaction Processing Concept
Transaction Processing ConceptNishant Munjal
 
Database Management System
Database Management SystemDatabase Management System
Database Management SystemNishant Munjal
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model IntroductionNishant Munjal
 
Virtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudVirtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudNishant Munjal
 
Technical education benchmarks
Technical education benchmarksTechnical education benchmarks
Technical education benchmarksNishant Munjal
 

More from Nishant Munjal (20)

Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
 
Programming in C
Programming in CProgramming in C
Programming in C
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computers
 
Unix Administration
Unix AdministrationUnix Administration
Unix Administration
 
Shell Programming Concept
Shell Programming ConceptShell Programming Concept
Shell Programming Concept
 
VI Editor
VI EditorVI Editor
VI Editor
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 
Routing Techniques
Routing TechniquesRouting Techniques
Routing Techniques
 
Asynchronous Transfer Mode
Asynchronous Transfer ModeAsynchronous Transfer Mode
Asynchronous Transfer Mode
 
Overview of Cloud Computing
Overview of Cloud ComputingOverview of Cloud Computing
Overview of Cloud Computing
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Database Design and Normalization Techniques
Database Design and Normalization TechniquesDatabase Design and Normalization Techniques
Database Design and Normalization Techniques
 
Concurrency Control
Concurrency ControlConcurrency Control
Concurrency Control
 
Transaction Processing Concept
Transaction Processing ConceptTransaction Processing Concept
Transaction Processing Concept
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Relational Data Model Introduction
Relational Data Model IntroductionRelational Data Model Introduction
Relational Data Model Introduction
 
Virtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of CloudVirtualization, A Concept Implementation of Cloud
Virtualization, A Concept Implementation of Cloud
 
Technical education benchmarks
Technical education benchmarksTechnical education benchmarks
Technical education benchmarks
 
Bluemix Introduction
Bluemix IntroductionBluemix Introduction
Bluemix Introduction
 

Recently uploaded

Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 

Recently uploaded (20)

Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 

Functions & Recursion

  • 1. Unit IV Function & Recursion
  • 2. Functions  A function is a self-contained block of statements that perform a coherent task of some kind. If you have a task that is always performed in the same way than instead of putting the same functionality at every point we should make function and can call by just declaring function name. #include<stdio.h> void func1(); int main() { func1(); printf("nthis is first program with funtion"); return 0; } void func1() { printf("nthis is func1"); } Output: This is func1 This is the first program with function
  • 3. Important points about function  A function gets called when the function name is followed by a semincolon.  A function is defined when function name is followed by a pair of braces in which one or more statements may be present.  Any function can be called from any other function. Even main can be called from other function.  A function calls itself such process known as recursion.
  • 4. Elements of Functions  Function Definition  Function Call  Function Declaration
  • 5. Definition of Function int func1() { int a; printf("nthis is func1"); return 0; } Function Definition- 1. Function name 2. Function type 3. List of parameters 4. Local variable declaration 5. Function statement 6. A return statement
  • 6. Return values and their type A function may or may not send back any value to the calling function. If it does it is done through return statement. Called function can only return only one value per call. return; or return(expression) return: will not return any value but will return the control back to the calling function. If(error) { return(0); } Return expression: will return some value of the function back to the called function. return(p); return(x*y);
  • 7. … So basically, return serves two purposes:  On executing the return statement, it immediately transfers the control back to the calling function.  It returns the value present in the parentheses after return, to the calling function.
  • 8. Passing values between functions-  Passing the vales to the function allows us to communicate with the function. Using this we can pass our values in order to get the results, for that we need to specify the function name with arguments.  Example: void main() { Funtion1(); Function2(a); } Function1() { } Function2(int a) { }
  • 9. Categories of Function-  Functions with no arguments and no return value.  Functions with arguments and no return value.  Functions with no arguments and return a value.  Functions that return multiple return values.
  • 10. Swapping a Number – General #include <stdio.h> int main() { int x, y, t; printf("Enter two integersn"); scanf("%d%d", &x, &y); printf("Before SwappingnFirst integer = %dnSecond integer = %dn", x, y); t = x; x = y; y = t; printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y); return 0; }
  • 11. #include <stdio.h> int main() { int x, y, t; printf("Enter two integersn"); scanf("%d%d", &x, &y); printf("Before SwappingnFirst integer = %dnSecond integer = %dn", x, y); swap(x,y); printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y); return 0; } void swap(int x, int y) //Swap function definition { int t; t = x; x = y; y = t; printf("After SwappingnFirst integer = %dnSecond integer = %dn", x, y); }
  • 12. Swapping a number #include <stdio.h> void swap(int*, int*); //Swap function declaration int main() { int x, y; printf("Enter the value of x and yn"); scanf("%d%d",&x,&y); printf("Before Swappingnx = %dny = %dn", x, y); swap(&x, &y); printf("After Swappingnx = %dny = %dn", x, y); return 0; } void swap(int *a, int *b) //Swap function definition { int t; t = *b; *b = *a; *a = t; }
  • 13. Recursion  Recursion is a special case where function calls itself again and again. main() { printf(“this is the example of recursion”); main(); }
  • 14. … Another example is factorial: Factorial of n=n(n-1)(n-2)…….1 Factorial of 4=4*3*2*1 =24 factorial(int n) { int fact; if(n==1) return 1; else fact=n*factorial(n-1); return(fact); } fact=3*factorial(2) fact=3*2*factorial(1) fact=3*2*1 fact=6
  • 15. Tower of Hanoi  Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1. Only one disk can be moved at a time. 2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3. No disk may be placed on top of a smaller disk.
  • 16.
  • 17. … Desired Input/output  Input : 2 Output : Disk 1 moved from A to B Disk 2 moved from A to C Disk 1 moved from B to C  Input : 3 Output : Disk 1 moved from A to C Disk 2 moved from A to B Disk 1 moved from C to B Disk 3 moved from A to C Disk 1 moved from B to A Disk 2 moved from B to C Disk 1 moved from A to C
  • 18. #include <stdio.h> void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n==1) { printf("nMove disk 1 from rod : %d",from_rod); printf("nMove disk 1 to rod : %d",to_rod); return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); printf("nMove disk %d from rod : %d",n,from_rod); printf("nMove disk %d to rod : %d",n,to_rod); towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } int main() { int n = 3; // Number of disks towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; }