2 Function
2 Function
Functions
LEARNING OBJECTIVES
Execution sequences for factorial (3): void swap2 (int *, int *); /* function to
swap two numbers by passing Address * /
Factorial (3) Factorial (3) void main ()
= 3* factorial (2) 3* 2 = 6 {
int a = 10, b = 15, c = 5, d = 25;
printf(“value of a and b before swapping
Factorial (2) Factorial (2) :%d, %d” a , b );
= 2* factorial (1) 2* 1 = 2 swap1(a, b);
printf(“values of a and b after swapping :
%d, %d”, a, b);
Factorial (1)
printf (“values of c and d before swapping
Factorial (1)
1* factorial (0) 1* 1 = 1 :%d%d”, c,d );
Swap2(&c, &d);
printf(“values of c and d after swapping
%d, %d”, c, d);
Factorial (0) = 1 }
void swap1(int x, int y )
{
Disadvantages: int temp;
1. Recursive programs increase the execution time of temp = x;
program. x = y;
2. Recursive programs typically use a large amount of y = temp;
computer memory and the greater the recursion, the }
void swap2 (int *x, int *y)
more memory is used.
{
3. Recursive programs can be confusing to develop and int temp;
extremely complicated to debug. temp = *x;
*x = *y:
Parameter Passing *y = temp;
There are two ways of passing parameters to functions in }
‘C’ language. Output:
1. Pass-by-value: When parameters are passed by value, Value of a and b before swapping: 10, 15
create copies in called function. This mechanism Value of a and b after swapping: 10, 15
is used when we do not want to change the value of Value of c and d before swapping: 5, 25
actual parameters. Value of c and d after swapping: 25, 5
2. Pass-by-address: In this case, only the addresses
of parameters are passed to the called function.
Therefore, manipulation of formal parameters affects Solved Examples
actual parameters.
Examples 6: Example 1: Consider the program below:
void swap1(int, int); /* function – to swap #include<stdio.h>
two numbers by passing values */ int fun (int n, int *fp)
Pass-by-value Pass-by-address
1. Also known as call-by-value 1. Also known as call-by-address or call by-reference
2. Pass the values of actual parameters 2. Pass the address of actual parameters
3. Formal parameters act as duplicates or as a copy to actual 3. Formal parameters acts as references to the actual
parameters parameters
4. Operations on formal parameter does not affect actual 4. Operations on formal parameters affect actual parameters
parameters
5. Passing of parameters is time consuming as the data size 5. The size of parameters does not affect the time for transfer-
increases ring references.
6. Actual parameters are secured 6. Helps to return multiple parameters
Chapter 2 • Functions | 3.17
{
int t,f; fun (2, &x) G G 2 15
if (n < =1) fun (3, &x) G G 3 15
{ fun (4, &x) G G 4 15
*fp=1; fun (5, &x) G G 5 15
return 1; main() − − − 15
} t f n x(fp )
t = fun(n−1, fp);
f = t+ *fp; Note: ‘–’ indicates no memory allocated to variable. ‘G’
*fp = t; indicates garbage value.
return f;
}
int main () fun (1, &x) G G 1 15
{ fun (2, &x) G G 2 15
int x = 15; fun (3, &x) G G 3 15
printf (“%d\n”, fun(5,&x)); fun (4, &x) G G 4 15
return 0; fun (5, &x) G G 5 15
} main() − − − 15
t f n x(fp)
What is the output?
(A) 2 (B) 4
(C) 8 (D) 16 For the function call fun(1, &x) condition (n<=1) is true. So
Assigns ‘1’ to fp and returns ‘1’.
Solution: (C)
Execution stack
fun (1, &x) G G 1 1.
Function call Corresponding fun (2, &x) G G 2 1.
sequence values of t, f, n, x fun (3, &x) G G 3 1.
fun (4, &x) G G 4 1.
fun (5, &x) G G 15 1.
main() − − − 1.
t f n x(fp )
main()
− − − 15
t f n x
fun (2, &x) 1 2 2 1.
fun (3, &x) G G 3 1.
fun (4, &x) G G 4 1.
fun (5 &x) fun (5, &x) G G 15 1.
G G 5 15
main() − − − 1.
main() − − − 15
t f n x(fp)
t f n x(f p )
fun (3 &x) G G 3 15
fun (4 &x) G G 4 15 fun (4, &x) 3 5 4 3.
fun (5 &x) G G 5 15 fun (5, &x) G G 5 3.
main() − − − 15 main() − − − 1.
t f n x(fp ) t f n x(fp)
3.18 | Unit 3 • Programming and Data Structures
Solution: (C)
fun (5, &x) 5 8 5 5. 0 1 2 3 4 5
main() − − − 5. a 12 7 13 4 11 6
t f n x(fp)
f (a, 6) is the first call to function f ( ).
The array _ name refers to base address of array, i.e., address
of first element.
main() 8
Thus,
t f n x(fp)
F (a, 6)
12 % 2 = 0. So,
Finally, x contains ‘8’, so printf prints ‘8’.
Example 2: What does the following program prints? n −1
( a + 1),
#include < stdio.h> 12 + f 5 [*a is even ]
void f (int *p, int *q)
{
↓7
p=q; n −1
*p=12; f ( a + 1),
} 12 + 7 − 4 [*a is odd ]
int i = 0, j=1; ↓ 13
int main()
{ ( a + 1) n −1
f(&i, &j); 12 + 7 − 13 − f , [*a is odd]]
↓ 4 3
printf(“ %d%d “, i, j);
return 0 ;
} ( n − 1)
( a + 1),
(A) 2 12 (B) 12 1 12 + 7 − 13 − 4 + f 2 , [*a is even ]
(C) 0 1 (D) 0 12
↓ 11
Solution: (D)
main( )
f (&i, &j)
n −1
( a + 1),
address of ‘i’ is stored in to p. 12 + 7 − 13 − 4 + 11 − f 1 [*a is odd ]
and address of ‘j’ is stored into ‘q’. ↓ 6
i.e., *p and*q refers i and j.
The statement:
p = q; updates pointer ‘p’, so that both ( n − 1)
pointers refer to parameter ‘j’. f ( a + 1),
*p = 12 12 + 7 − 13 − 4 + 11 − 6 + 0 [*a is even ]
Changes value of ‘j’ to ‘12’ But ‘i’ does ↓0
not effected. So, prints 0 12.
Example 3: What is the value printed by the following
program? 12 + (7 (13 - (4 + (11 - (6 + 0))))) = 15
# include <stdio.h>
int f(int *a, int n)
{
Scope, Lifetime and Binding
if (n<=0) return 0 ; Storage classes specify the scope, lifetime and binding of
else if(*a%2 = = 0) variables. To fully define a variable, one needs to mention
return *a + f(a+1, n−1); not only its ‘type’ but also its ‘storage class’.
else A variable name identifies some physical location within
return *a – f(a+1, n−1); computer memory where a collection of bits are allocated
}
for storing value of variable.
int main ( )
{ Storage class tells us:
int G [ ] = { 12, 7, 13, 4, 11, 6}; 1. Where the variable would be stored (either in memory
printf(“%d”, f (a,b)); or CPU registers)?
return 0;
2. What will be the initial value of a variable, if no value
}
is specifically initialized?
(a) −9 (b) 12
3. What is the scope of a variable (where it can be accessed)?
(c) 15 (d) 20
4. What is the life of a variable?
Chapter 2 • Functions | 3.19
Scope Binding
The scope defines the visibility of an object. It defines Binding finds the corresponding binding occurrence (dec-
where an object can be referenced/accessed; generally, the laration/definition) for an applied occurrence (usage) of an
scope of variable is local or global. identifier. For Binding.
1. The variables defined within a block have local scope. 1. Scope of variables should be known. What is the block
They are visible only to the block in which they are structure? In which block the identifier is variable?
defined. 2. What will happen if we use same identifier name
2. The variables defined in global area are visible from again? ‘C forbids use of same identifier name in the
their definition until the end of program. It is visible same scope’. Same name can be used in different
everywhere in program. scopes.
Examples:
Lifetime
1. double f,y;
The lifetime of a variable defines the duration for which
int f( ) // error
the computer allocates memory for it (the duration between {
allocation and deallocation of memory). .
In C, variable can have automatic, static or dynamic .
lifetime. .
}
1. Automatic: Variables with automatic lifetime are cre- double y; // error
ated each time their declaration are encountered and
are destroyed each time their blocks are exited. 2. double y;
2. Static: A variable is created when the declaration is int f( )
executed for the first time and destroyed when the exe- {
double f;// legal
cution stops/terminates.
int y; //legal
3. Dynamic: The variable’s memory is allocated and deal- }
located through memory management functions.
Automatic Memory Till the control remains in block Till the control remains in block Local auto
Register CPU register An unpredictable value (or) gar- Till the control remains in block Local register
bage value
Static Memory Zero Value of variable persist between Local static
function calls
External Memory Unpredictable or garbage value Throughout program execution Global extern
Example 4: What will be the output for the program? (A) error
int i = 33; (B) 11 22 33
main( ) (C) 11 22 garbage
{ (D) 11 11 11
extern int i;
{ Solution: (B)
int i = 22;
‘{‘ introduces new block and thus new scope. In the inner-
{
const volatile unsigned i most block, i is declared as const volatile unsigned which
= 11; is a valid declaration. i is assumed of type int. So printf
printf (“ %d ”, i); prints 11. In the next block, i has value 22 and so printf
} prints 22. In the outermost block, i is declared as extern,
printf (“ %d ”, i); so no storage space is allocated for it. After compilation is
} over, the linker resolves it to global variable, i since it is
printf (“%d “, i) ; the only variable visible there. So it prints its value as 33.
}
3.20 | Unit 3 • Programming and Data Structures
0 + foo (4, 2)
Solution: (C)
0 + foo (2, 2)
Call Sequence r Return Sequence
f (5) 5 18 0 + f (1, 2)
↓
f (3)+2 5 16+2 0 + foo (1, 2)
↑
f (2)+r 5 11+5 Result = 1 0 + f (0, 2)
↑
0 + 0
f (1)+r 5 6+5
↑ Choice D
f (0)+r 5 1+5
Result = 1
↑
Example 7: What is return value for the function call foo
Common data for questions 6 and 7: Consider the fol- (345, 10)?
lowing recursive ‘C’ function that takes two arguments. (A) 345 (B) 12
unsigned int foo (unsigned int n, unsigned int r) (C) 5 (D) 3
{ Solution: (B)
if (n>0)
return ((n%r)+ foo(n/r,r)); foo (345, 10)
else
return 0; 5 + foo (34, 10)
}
4 + foo (3, 10)
Example 6: What is the return value of the function foo
when it is called as foo (512,2)? 3 + foo (0, 10)
(A) 9 (B) 8
0 0
(C) 2 (D) 1 +
Exercises
Practice Problems 1 t = a;
Directions for questions 1 to 15: Select the correct alterna- a = b;
tive from the given choices. b = t;
}
1. What will be the output of the following program? In order to exchange the values of two variables w and
main( ) z,
{
(A) call swap (w, z)
main( );
(B) call swap (and w, and z)
}
(C) swap (w, z) cannot be used as it does not return any
(A) overflow error (B) syntax error value
(C) returns 0 (D) returns 1 (D) swap (w, z) cannot be used as the parameters are
2. Output of the following program is passed by value
main( ) 6. Choose the correct option to fill? x and? y so that the
{
program below prints an input string in reverse order.
static int var = 6;
Assume that the input string is terminated by a new line
printf(“%d\t”, var--);
character:
if(var)
void Rev(void) {
main( );
int a;
}
if (?x) Rev( );
(A) 5 4 3 2 1 0 (B) 6 6 6 6 6 6 ?y
(C) 6 5 4 3 2 1 (D) Error }
3. Which of the following will be the output of the main( ) {
program? printf(“Enter the text”);
main( ) printf(“ \n”);
{ Rev( );
char str[ ] = “Hello”; printf(“\n”);
display( str ); }
} (A) ? x is (getchar( )! = ‘\n’)
void display (char *str) ? y is getchar (A);
{ (B) ? x is((A = getchar( )) ! = ‘\n’)
printf ( “%s”, str) ; ? y is getchar(A) ;
} (C) ? x is (A! = ‘\n’)
(A) compilation error (B) hello ? y is putchar (A);
(C) print null string (D) no output (D) ? x is (A = getchar ( )) ! = ‘\n’)
4. Consider the following C function ? y is putchar(A) ;
int fun (int n) 7. main ( )
{ {
static int x = 0; extern int a;
if (n<=0) return 1; a = 30;
if (n>3) printf (“%d”, a);
{ }
x = n; What will be the output of the above program?
return fun(n-2)+3; (A) 30 (B) Compiler error
} (C) Runtime error (D) Linker error
return fun(n-1)+ x;
8. Which of the following will be the output of the
}
program?
What is the value of fun(5)? void main ( )
(A) 4 (B) 15 {
(C) 18 (D) 19 int n = ret(sizeof(float));
5. For the following C function printf(“\n value is %d ”, ++n);
void swap (int a, int b) }
{ int ret(int ret)
int t; {
3.22 | Unit 3 • Programming and Data Structures
7. What is the return value of the function foo when it is 11. Consider the following pseudo code. What is the total
called as foo (345, 10)? [2011] number of multiplications to be performed? [2014]
(A) 345 (B) 12 D = 2
(C) 5 (D) 3
for i = 1 to n do
Common data for questions 8 and 9: Consider the fol-
for j = i to n do
lowing C code segment
for k = j +1 to n do
int a, b, c = 0;
D = D * 3
void prtFun (void);
(A) Half of the product of the three consecutive inte-
main ( ) gers.
{ static int a = 1; (B) One-third of the product of the three consecutive
prtFun( ); integers.
(C) One-sixth of the product of the three consecutive
a+ = 1;
integers.
prtFun( ); (D) None of the above.
printf(“\n %d %d”, a, b); 12. Consider the function func shown below:
} int func (int num) {
void prtFun(void) int count = 0;
{static int a = 2; while (num) {
int b = 1; count ++;
a+ = ++b; num>>=1;
printf(“\n %d %d”, a, b); }
} return (count);
8. What output will be generated by the given code seg- }
ment if: [2012] The value returned by func(435) is ______[2014]
Line 1 is replaced by auto int a = 1; 13. Consider the following function
Line 2 is replaced by register int a = 2;
double f (double X)
(A) (B) (C) (D)
3 1 4 2 4 2 4 2 if (abs(X*X – 3) < 0.01)return X;
4 1 6 1 6 2 4 2 else return f(X/2 + 1.5/X);
4 2 6 1 2 0 2 0 }
9. What output will be generated by the given code seg- Give a value q(to two decimals) such that f(q) will
ment? [2012] return q:________ [2014]
(A) (B) (C) (D) 14. Consider the following pseudo code, where x and y
3 1 4 2 4 2 3 1 are positive integers [2015]
4 1 6 1 6 2 5 2
begin
4 2 6 1 2 0 5 2
q := 0
10. What is the return value of f (p, p), if the value of p r := x
while r ≥ y do
is initialized to 5 before the call? Note that the first
begin
parameter is passed by reference, whereas the second r := r – y
parameter is passed by value. q := q + 1
int f(int &x, int c) { end
c = c – 1; end
if (c == 0) return 1; The post condition that needs to be satisfied after the
x = x + 1;
program terminates is
return f(x, c) * x;
(A) {r = qx + y ∧ r < y}
(B) {x = qy + r ∧ r < y}
} [2013]
(A) 3024 (B) 6561 (C) {y = qx + r ∧ 0 < r < y}
(C) 55440 (D) 161051 (D) {q + 1 < r – y ∧ y > 0}
Chapter 2 • Functions | 3.27
Answer Keys
Exercises
Practice Problems 1
1. A 2. C 3. A 4. D 5. D 6. D 7. D 8. C 9. B 10. A
11. C 12. C 13. C 14. D 15. C
Practice Problems 2
1. D 2. C 3. B 4. B 5. C 6. C 7. A 8. C 9. C 10. A
11. B 12. C 13. B 14. A 15. B