0% found this document useful (0 votes)
23 views50 pages

Lecture5 Functions

The document discusses functions in C programming. It explains what functions are, how to define and call functions, and covers topics like function parameters, return values, scope of variables, and recursion. Examples of recursive functions like factorial and Fibonacci are provided.

Uploaded by

0jonnypapa0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views50 pages

Lecture5 Functions

The document discusses functions in C programming. It explains what functions are, how to define and call functions, and covers topics like function parameters, return values, scope of variables, and recursion. Examples of recursive functions like factorial and Fibonacci are provided.

Uploaded by

0jonnypapa0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

Mythili Vutukuru

IIT Bombay

Reference: “C How to Program”, Deitel and Deitel, 8th Edition, Chapter 5


 A way to write code in a modular manner instead of as one
big giant blob
 Construct a bigger program out of small pieces / building blocks
 Reuse code efficiently instead of repeating same logic at multiple
places
 Function: a piece of code that takes some inputs and
produces some outputs
 Functions are invoked from another part of program using a
function call
 Example:
 Function sqrt takes one argument
 Returns a value equal to square root of argument

 Function may take 0, 1, 2, … arguments


 Function returns one value or no value
 C library provides functions that users can invoke
 Example: printf, scanf (examples of functions that do not return any value)
 Other: math library functions, string functions

 Programmers can also write their own functions


Function prototype / declaration
Specifies type or arguments and type of return value

Function call

Main also has int return value but return 0 done here automatically
Function definition / implementation

Function body + return statement


 Local variables: variables declared inside a function,
available only within function body, not outside of it
 Arguments: variables passed to the function in function call
 Number and types of arguments in the function implementation
must match with function prototype, else compilation error
 Arguments and local variables are stored in a part of
program memory called stack temporarily
 Available only when function is running, not afterwards
Local variable: max
Arguments: x, y, z
 Passing arguments by value: a copy of the argument’s value is
made and passed to the function
 Changes made to value in function does not effect original
 In maximum example, argument x is set to number1, and changing x
inside the function does not change the value of number1
 Another way exists (passing by reference), more later

 Function can return only one value or none at all


 No return value if return type is void and only simple “return;”
statement is used
 How to return more than one value? More on this later
 Function declarations can be placed in a separate header
file whose filename ends with “.h”, and it can be included
in the C code file at the top of the program
 User defined header files included with “…”

 C library header files included with <…>


 Number, order and type of arguments must match across:
 Function prototype declared in header file or at the top of the C file
 Function call which invokes the functions
 Function implementation

 If function prototype or implementation not found, or


mismatch detected, compiler error
 Compiler can apply its “usual” conversion rules to convert
arguments from one type to another
 Example, sqrt can be given integer argument, will be converted to
double
 Implement the bisection method to find the roots of a
function f(x) = x sin(x)
 How does bisection method work?
 Pick two points a, b where f(x) has opposite signs. We know at
least one root should lie in [a, b]
 Next we pick the midpoint c = (a+b)/2
 If f(c) close to 0 (epsilon), we have found the root
 If f(a) and f(c) have opposite signs, look for root in [a,c]
 If f(b) and f(c) have opposite signs, look for root in [c, b]
 Repeat this process until some maximum iterations N

 Experiment with different values of a, b, epsilon, N


 The function rand() generates a random number between 0
and a maximum value called RAND_MAX (max value depends
on underlying machine)
 Can shift and scale this random number to any range
 Scaling: rand() % 6 gives a random number between 0 and 5
 Shifting: 1 + rand() % 6 gives a random number between 1 and 6 (dice)

 The sequence of random numbers generated by rand()


repeats itself (pseudorandom numbers)
 To get a fresh batch of random numbers in every run, new
“seed” to the random number generator using srand(seed)
Enumeration constants to easily
represent integers by identifiers

Randomize using seed

Switch to test various cases


First roll of dice completed
While loop to let player continue game
Rolling dice done in separate function
 Recursive function is a function that calls itself, directly or
indirectly, to complete its work
 Consider a function to solve a specific task
 Break down the task into simpler smaller tasks, and call the same
function for the simpler tasks (recursion step)
 At some point, problem becomes simple enough to return result
directly without calling itself (base case)
 Example: calculating factorials
 Recursion step: factorial(n) = n * factorial(n-1)
 Keep doing the above until n becomes 1, in which case result is 1,
easy to calculate (base case)
 Note: factorial can also be calculated iteratively
Unsigned long long to hold large values
Functions return one after the
other after reaching base case

Ensure recursive calls


eventually terminates
 Popular example of recursion (can be done iteratively too)
Data type unsigned long long

Function call to
recursive fibonacci
 At each level, the number of function calls doubles, rises exponentially (2^n)
 During recursion, multiple copies of variables will be present on the stack,
consuming memory
 Recursion and iteration are both valid ways to solve problems
 Any problem that can be solved recursively can also be solved iteratively

 Both of ways of doing repetition in programs


 Iteration: repeated execution of statements
 Recursion: repeated function calls

 Both must ensure repetition terminates


 Iteration: loop termination condition must be hit, else infinite loop
 Recursion: base case must be hit, else infinite recursion

 Recursion consumes more memory resources than iteration


 Multiple copies of the function on stack

 But, recursion may be more intuitive to solve some problems than iteration
 Note: main is also like any other function with integer return value
 Why do we not have a return statement? Compiler automatically
inserts return 0 at end of main
 Variables related to a function are stored in a region of
program memory called a stack
 What are the other regions in program memory? More later
 When function is called, function data is pushed on to stack
 Local variables and arguments
 Return address, that is, where a function should return to

 When function returns, data is popped off the stack


 Local variables not accessible after function returns, values erased
 Scope = part of a program where a variable can be
referenced or used
 Global variables declared outside of any function have file
scope, i.e., can be used anywhere in the file
 Local variables declared inside a function (main or any other)
have function scope, i.e., can be used only within the function
 Variables declared inside any block of code within { } have
block scope, i.e., can be used only within that block of code
 If a variable with same name exists in outer and inner blocks,
the outer variable remains hidden until the inner block ends
 Local variables in functions (or in any block of code) are
initialized every time the function is run
 They are stored on stack, erased after function returns, do
not retain value when function called next time
 Static variables are initialized only once, and retain value
even when out of scope
 Note: static variable cannot be used when out of scope, but
value is retained for next use
 How? Stored in different area, not on stack
 Local variable initialized to 25 every time function is called
 Static variable retains its value across function calls

You might also like