C Programming Week6
C Programming Week6
Functions = Outsourcing
• Break large computing tasks into small ones
• Helps you to build on what others have done
– You and others write functions
CS1100
– When you want to build a program, find out how to
Introduction to Programming use the function and use it
• Using standard functions provided by the library
Functions
– You are hidden from the implementation
Madhu Mutyam – Example – you don’t have to worry about how
Department of Computer Science and Engineering
Indian Institute of Technology Madras pow(m, n) is implemented
• As engineers from different disciplines you will
Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1
use and develop different set of functions
SD, PSK, NSN, DK, TAG – CS&E, IIT M 2
1
04/10/17
return 3
SD, PSK, NSN, DK, TAG – CS&E, IIT M 7 SD, PSK, NSN, DK, TAG – CS&E, IIT M 8
Basics Basics
• Function is a part of your program • Transfer of control is affected by calling a
– It cannot be a part of any other function function
– main( ) is a function: it is the main function – With a function call, we pass some parameters
• Execution starts there or the control flow starts there – These parameters are used within the function
– From there it can flow from one function to another, – A value is computed
return after a computation with some values, probably, – The value is returned to the function which initiated
and then flow on the call
– The calling function can ignore the value returned
– It could use it in some other computation
– A function could call itself, these are called recursive
function calls
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11 SD, PSK, NSN, DK, TAG – CS&E, IIT M 12
2
04/10/17
function-name(exp1,exp2,…,expn);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 15 SD, PSK, NSN, DK, TAG – CS&E, IIT M 16
3
04/10/17
int fact(int n)
Pending Computations {
if (n == 1) return 1;
Tail Recursion
• In this recursive version the calling }
return n * fact(n - 1);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 23 SD, PSK, NSN, DK, TAG – CS&E, IIT M 24