0% found this document useful (0 votes)
60 views

2 Function

Functions allow programmers to organize code into reusable blocks to perform tasks. There are two types of functions: library functions which are pre-defined, and user-defined functions which are created by the programmer. User-defined functions are declared with a return type and parameter list, defined with a block of code, and called by their name. Functions can return values or be void. Recursion occurs when a function calls itself, requiring a base case to end the recursion.

Uploaded by

AKASH PAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

2 Function

Functions allow programmers to organize code into reusable blocks to perform tasks. There are two types of functions: library functions which are pre-defined, and user-defined functions which are created by the programmer. User-defined functions are declared with a return type and parameter list, defined with a block of code, and called by their name. Functions can return values or be void. Recursion occurs when a function calls itself, requiring a base case to end the recursion.

Uploaded by

AKASH PAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 2

Functions

LEARNING OBJECTIVES

 Functions  Pass by value


 Library functions  Pass by address
 User defined functions  Scope
 Defining user defined functions  Life time
 Recursion  Binding
 Parameter passing

functions • A function receives zero (or) more parameters, performs a spe-


cific task, and returns zero or one value.
A function is a block of code that performs a specific task. It has a
• A function is invoked by its name and parameters.
name and is reusable, i.e., it can be executed from as many differ-
• No two functions have the same name in a single C program.
ent parts in a program as required.
• The communication between the function and invoker is through
Functions make possible top down modular programming. In this
the parameter and the return value.
style of programming, the high-level logic of overall problem is solved
• A function is independent.
first, whereas the detail of each lower-level function is addressed later.
• It is “completely” self-contained.
This approach reduces the complexity in writing program.
• It can be called at any place of your code and can be ported to
1. Every C program can be thought of collection of functions. another program.
2. main( ) is also a function. • Functions make programs reusable and readable.
Types of Functions Example 3: Return the largest of two integers.
Library functions int maximum (int a, int b)
{
These are the in-built functions of ‘C’ library. These are already
if (a > b)
defined in header files.
return a;
Example 1: printf( ); is a function which is used to print at output. else
It is defined in ‘stdio.h’ file. return b;
}
User-defined functions
Note: Function calls execute with the help of execution stack.
Programmers can create their own function in ‘C’ to perform spe-
Execution of ‘C program’ starts with main( ) function. Main( ) is a
cific tasks.
user-defined function.
Example 2: # include <stdio.h>
main( )
{ Defining User-defined Functions
message( ); In order to work with user-defined functions, it requires the follow-
} ing concepts about functions:
message( )
{ • Declaration of a function
printf(“Hello”); • Definition of a function
} • Function call
Chapter 2  •  Functions  |  3.15

Declaration specifies what printf (“\n function Hello”);


return;
•• is the name of the function }
•• are the parameters to pass (type, order and number of
A return statement has two important uses:
parameters).
•• it returns on completion of execution 1. first, it causes an immediate exit from the function.
Example 4: int maximum (int, int); int maximum (int a, 2. second, it may be used to return a value.
int b);
If a function does not return any value, then the return
Syntax: statement is optional.
Return_type Function_Name(Parameter_list);

•• Names of parameters are optional in declaration.


•• Default return type for ‘C’ functions is ‘int’. Recursion
•• A function, whose return type is void returns nothing. In general, programmers use two approaches to write repeti-
•• Empty parenthesis after a function name in declaration tive algorithms. One approach using loops, the other is
says, function does not accept any parameters. recursion.
Recursive functions typically implement recurrence
Definition specifies how relations, which are mathematical formula in which the
•• to perform the specified task desired expression (function) involving a positive integer, n,
•• to accept passed parameters is described in terms of the function applied to correspond-
•• to process parameters or execute instruction to producer ing values for integers less than ‘n’.
equired results (return value).
1. The function written in terms of itself is a recursive
Function definition is a self-contained block of instructions, case.
will be executed on call: 2. The recursive case must call the function with a
decreasing ‘n’.
Syntax:
3. Recursion in computer programming is exemplified
Return _type Function -Name(paralist)
when a function defined in terms of itself.
{
4. Recursion is a repetitive process in which a function
Local declaration(s);
calls itself.
Executable statements(s);
} Note: Recursive function must have an if condition to force
int maximum (int a, int b) the function to return without recursive call being executed.
{ If there is no such condition, then the function execution
if (a > b) falls into infinite loop.
  return a;
else
  return b; Rules for designing recursive function
} 1. Determine base case
2. Determine general case
Function call specifies 3. Combine, base and general case into a function

1. where to execute the function
2. when to execute the function
Example 5:  Recursive factorial function
Note: If the function definition provided before use (call),
the declaration is optional. 1. int factorial (int n)
2. {
The following example describes control flow during
3. if (n = = 0)
function call: 4. return 1;
void hello(); // Declaration 5. else
void main() 6. return (n ‫ ٭‬factorial (n − 1));
{ 7. }
printf(“\n function”);
The statement 3 is a base condition, which stops the recur-
hello();
sive call of function.
printf(“\n Main after call to hello”)
The statement 6 reduces the size of problem by recur-
void hello()//Definition sively calling the factorial with (n − 1).
{
3.16 |  Unit 3  •  Programming and Data Structures

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)

Table 1  Comparison of pass-by-value and pass-by-address

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 (4 &x) G G 4 15 fun (3, &x) 2 3 3 2.


fun (5 &x) G G 5 15 fun (4, &x) G G 4 2.
main() − − − 15 fun (5, &x) G G 5 2.
t f n x(fp ) main() − − − 1.

t f n x(fp)

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.

There are four storage classes in C.


Storage class Storage Area Default Initial Value Lifetime Scope Keyword

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

Note: Default storage class is auto.

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

Example 5:  Consider the following C program: foo (513, 2)

int f(int n) 0 + foo (256, 2)


{
static int r; 0 + foo (128, 2)
if (n<=0) return 1;
if (n> 3) 0 + foo (64, 2)
{
r=n; 0 + foo (32,2)
return (f(n−2)+2));
} 0 + foo (16,2)
return f(n−1) + r;
} 0 + foo (8, 2)

What is the value of f(5)? 0 +


(a) 15 (b) 17
(c) 18 (d) 19 foo (8, 2)

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 +

Solution:  (D) result 5 + 4 + 3 = 12


Chapter 2  •  Functions  |  3.21

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

ret += 2.5; ptr[2]();


return (ret); }
} (A) hi (B) hello
(A) Value is 6 (B) Value is 6.5 (C) bye (D) Garbage value
(C) Value is 7 (D) Value is 7.5 12. What is the output?
9. The following program void main()
main( ) {
{ static int i = 5;
pt( ); pt( );pt( ); if(--i)
} {
pt( ) main();
{ printf(“%d”, i);
static int a; }
printf(“%d”, ++a) ; }
} (A) 5 (B) 5 5 5 5
prints (C) 0 0 0 0 (D) 1 1 1 1
(A) 0 1 2 1 3. If the following function gets compiled, what error
(B) 1 2 3 would be raised?
(C) 3 consecutive, but unpredictable numbers double fun(int x, double y)
(D) 1 1 1 {
10. What is the output of the following program? int x;
main( ) { x = 100;
int i = 0; return y;
while (i < 4) { }
sum(i); (A) Function should be defined as int fun(int x, double y)
i++; (B) Missing parenthesis in return
} (C) Redeclaration of x
} (D) All of these
void sum(int i) { 1 4. Consider the following function:
static int k; fun(int x)

printf (“%d”, k + i); {
k++; if ((x/2)! = 0)
  } return (fun (x/2) 10 + x%2);
(A) 0 2 4 6 (B) 0 1 2 3 else return 1;
(C) 0 2 0 0 (D) 1 3 5 7 }
11. What will be the output of following code? What will happen if the function ‘fun’ called with value
# include <stdio.h> 16 i.e., as fun(16).
aaa() { (A) Infinite loop
printf(“hi”); (B) Random value will be returned
} (C) 11111
bbb() { (D) 10000
printf(“hello”); 15. What is the output of the following program?
} void main( )
ccc() {
{ static int x = 5;
printf(“bye”); printf(“%d”, x – – );
} if (x ! = 0)
main () main( );
{ }
int *ptr[3]( ); (A) error:main( ) cannot be called from main( )
ptr[0] = aaa; (B) Infinite loop
ptr[1] = bbb; (C) 5 4 3 2 1
ptr[2] = ccc; (D) 0
Chapter 2  •  Functions  |  3.23

Practice Problems 2 return 1;


else if (x > 5)
Directions for questions 1 to 15:  Select the correct alterna-
{
tive from the given choices.
i = x;
1. An external variable return fun (x – 3) +2;
(A) is globally accessible by all functions }
(B) has a declaration “extern” associated with it when return fun (x – 2) + i;
declared within a function }
(C) will be initialized to 0, if not initialized What is the value of fun(7)?
(D) all of the above (A) 17 (B) 10
2. The order in which actual arguments are evaluated in a (C) 11 (D) 9
function call 8. Consider the following C program:
(A) is from the left (B) is from the right void rearrange( )
(C) is unpredictable (D) none of the above {
3. In C language, it is necessary to declare the type of a char ch;
function in the calling program if the function if (X)
(A) returns an integer (B) Returns a float rearrange( );
(C) both (A) and (B) (D) none of the above Y;
4. What is the output? }
void main() void main ( )
{ {
int k = ret(sizeof(int)); printf(“\n enter text to print reverse
printf(“%d”, ++k); order :”);
} rearrange( ) ;
int ret (int ret) }
{ Choose the correct option to fill X and Y, so that the
ret + = 2.5; program prints the entered text in reverse order. As-
return (ret); sume that input string terminates with new line.
} (A) X: (getchar(ch) = = ‘\n’)
(A) 3.5 (B) 5 Y: putchar(ch);
(C) 4 (D) logical error X:
(B) (getchar(ch)! = ‘\n’)
Y: ch = putchar( );
5. When a recursive function is called, all its automatic
X: ((ch = getchar( ) )! = ‘\n’)
(C)
variables are
Y: putchar(ch);
(A) maintained in stack
X: ((ch = getchar( )) = = ‘\n’)
(D)
(B) retained from last execution
Y: putchar (ch);
(C) initialized during each call of function
(D) none of these 9. Consider the following C function:
6. Consider the following program segment: int f(int n)
{
int fun(int x, int y)
static int i = 1;
{
if (n > = 5) return n;
if(x > 0)
n = n + i;
return ((x % y) + fun(x/y, y));
i++ ;
else
return f(n);
return 0;
}
}
What will be the output of the program segment if the The value returned by f(1) is
function is called as fun(525, 25)? (A) 5 (B) 6
(A) 25 (B) 12 (C) 7 (D) 8
(C) 21 (D) 42 10. Consider the following C function:
7. Consider the following C program segment: int incr (int i)
{
int fun (int x)
static int count = 0;
{
count = count + i;
static int i = 0;
return (count);
if (x < = 0)
3.24 |  Unit 3  •  Programming and Data Structures

} (A) The above code computes HCF of two numbers a


main ( ) and b
{ (B) The above code computes LCM of a and b
int i, j; (C) The above code computes GCD of a and b
for (i = 0; i < =4; i++) (D) None of the above
j = incr (i);
} 13. 1. main ( )
2. {int a = 10, *j;
The j value will be 3. void *k;
(A) 10 4. j = k = &a;
(B) 4 5. j++;
(C) 6 6. k++;
(D) 7 7. printf(“\n %u, %u”, j, k);
8. }
11. The following function
Which of the following is true in reference to the above
int Trial (int a, int b, int c)
code?
{
(A) The above code will compile successfully
if ((a > = b) && (c < b))
(B) Error on line number 6
return b;
(C) Error on line number 3
else if(a > = b)
(D) Error on line number 4
return Trail(a, c, b);
else return Trail (b, a, c); 14. Aliasing in the context of programming language refers
} to
(A)  multiple variables having the same memory
(A) finds the maximum of a, b, c location
(B) finds the middle value of a, b, c after sorting (B) multiple variables having the same value
(C) finds the minimum of a, b, c (C) multiple variables having the same identifier
(D) none of the above (D) multiple uses of the same variable
12. Consider the following pseudo code 15. Match the following:
f(a, b) X: m = malloc (5); 1: Using dangling pointers
{ m = NULL;
while(b! = 0) Y: free (n); n → 2: Using un initialized pointers
{ value = 5;
t = b; Z: char *p; *p = ‘a’; 3: Lost memory
b = a % b;
a = t; (A) X – 1 Y – 3 Z–2
} (B) X – 3 Y – 1 Z–2
return a; (C) X – 3 Y – 2 Z–1
} (D) X – 2 Y – 1 Z–3
Chapter 2  •  Functions  |  3.25

Previous Years’ Questions


1. In the following C function, let n ≥ m. *f_p =1;
int gcd(n,m) return 1;
{ }
if (n%m ==0) return m; t = fun (n-1, f_p);
n = n%m;
f = t+*f_p;
return gcd(m,n);
} *f_p = t;
How many recursive calls are made by this function? return f;
 [2007] }
(A) Θ(log 2 n) (B) Ω(n) int main( ) {
Θ(log 2 log 2 n) (D)
(C) int x = 15;
Θ( n )
printf (“%d\n”, fun(5,&x));
2. What is the time complexity of the following recursive return 0;
function?
}
int DoSomething (int n) { The value printed is [2009]
if (n <= 2) (A) 6 (B) 8
return 1; (C) 14 (D) 15
else
5. What is the value printed by the following C program?
return(DoSomething(floor(sqrt(n)))+ n);}
#include <stdio.h>
 [2007]
int f(int *a, int n)
(A) Θ( n log 2 n)
Θ( n ) (B)
2
{
(C) Θ(log 2 n) (D) Θ(log 2 log 2 n) if (n <= 0)return 0;
3. Choose the correct option to fill ? 1 and ? 2 so that else if(*a % 2 = = 0) return * a + f(a+1,
the program below prints an input string in reverse n­–1);
order. Assume that the input string is terminated by a else return *a–f(a+1, n­
–1);
newline character. }
void reverse (void) {
int main( )
int c; {
if (?1) reverse( ); int a[ ] = {12, 7, 13, 4, 11, 6};
?2 printf(“%d”, f(a,6));
} return 0;
main ( ) { } [2010]
printf (“Enter Text”) ; printf (“\ n”); (A) -9 (B) 5
reverse ( ); printf (“\ n”) ; (C) 15 (D) 19
}[2008]
?1 is (getchar( )! = ‘\n’)
(A) Common data for questions 6 and 7:  Consider the fol-
?2 is getchar(c); lowing recursive C function that takes two arguments.
?1 is (c = getchar( ))! = ‘\n’)
(B) unsigned int foo (unsigned int n, unsigned int r)
?2 is getchar(c); {
?1 is (c! = ‘\n’)
(C) if ( n > 0 ) return ((n % r) + foo (n /r,
?2 is putchar(c); r));
?1 is ((c = getchar( ))! = ‘\n’)
(D) else return 0;
?2 is putchar(c); }
4. Consider the program below:
6. What is the return value of the function foo when it is
# include < stdio.h >
called as foo (513, 2)? [2011]
int fun(int n, int * f_p) { (A) 9 (B) 8
int t, f; (C) 5 (D) 2
if (n <=1) {
3.26 |  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

5. Consider the following C function


1 [2015] DOSOMETHING (c, a, n)
int fun(int n) { z ← 1
int x = 1, k; for i ← 0 to k – 1
if (n = = 1) return x; do z ← z2 mod n
for (k = 1; k < n; ++k) if c[i] = 1
x = x + fun(k)  * 
fun(n then z ← (z × a) mod n
– k); return z
return x; If k = 4, c = <1, 0, 1, 1>, a = 2 and n = 8, then the
} output of DOSOMETHING(c, a, n) is ______
The return value of fun(5) is _____
1 9. What will be the output of the following C program?
16. Consider the following recursive C function
[2016]
void get (int n)
void count (int n) {
{
if (n < 1) return; static int d = 1;
get (n – 1); printf(“%d ”,n);
get (n – 3); printf(“%d ”,d);
printf(“%d”, n);
} d ++;
If get (6) function is being called in main ( ) then how if (n > 1) count (n -1);
many times will the get ( ) function be invoked before printf(“%d ”, d);
returning to the main ( )? }
(A) 15 (B) 25 void main ( ) {
(C) 35 (D) 45 count (3);
17. Consider the following C program [2015] }
#include<stdio.h> (A) 3 1 2 2 1 3 4 4 4
int f1(void); (B) 3 1 2 1 1 1 2 2 2
int f2(void); (C) 3 1 2 2 1 3 4
int f3(void); (D) 3 1 2 1 1 1 2
int x = 10;
int main ( ) 20. The following function computes XY for positive inte-
gers X and Y.[2016]
{
int exp (int X, int Y)
int x = 1;
{
x += f1( ) + f2 ( ) + f3 ( ) + f2 (
); int res = 1, a = X, b = Y;
printf(“%d”, x); while (b! = 0)
return 0; {
} if (b%2 = = 0) {a = a*a; b = b/2;}
int f1 () { int x = 25; else {res = res *a; b = b -1;}
x++; return x;} }
int f2 () { static int x
return res;
= 50; x++; return x;}
}
int f3 () { x *= 10; return
x}; Which one of the following conditions is TRUE
The output of the program is ______ before every iteration of the loop?
18. Suppose c = < c[0],…,c[k – 1]> is an array of length (A) XY = ab
k, where all the entries are from the set {0, 1}. For (B) (res *a)Y = (res* X)b
any positive integers a and n, consider the following (C) XY = res *ab
pseudo code. [2015] (D) XY = ( res*a)b
3.28 |  Unit 3  •  Programming and Data Structures

21. Consider the following two functions. static int x = 0;


void fun1 (int n) { void fun2 (int n) { int i = 5;
if (n == 0) return; if (n == 0) return; for (; i > 0,i−−) {
printf (“%d”, n); printf (“%d”, n); x = x + total (i);
fun2 (n − 2) ; fun1(++n) }
printf (“%d”, n); printf (“%d”, n); printf (“%d\n”, x);
} } }
The output printed when fun1 (5) is called is[2017] [2017]
(A) 53423122233445 (B) 53423120112233
24. Consider the following C program:
(C) 53423122132435 (D) 53423120213243
#include <stdio.h>
22. Consider the C functions foo and bar given below: int counter = 0;
int foo (int val) { int calc (int a, int b) {
int x = 0; int c;
while (val > 0) {
counter++;
x =x + foo (val−−);
if (b==3) return (a*a*a);
}
else {
return val;
} c = calc (a, b/3);
int bar (int val) { return (c*c*c);
int x = 0; }
while (val > 0) { }
x =x +bar (val − 1); int main () {
} calc (4, 81);
return val; printf (“%d”, counter);
} }
Invocations of foo (3) and bar (3) will result in: The output of this program is ______.[2018]
[2017]
25. Consider the following program written in pseudo-
(A) Return of 6 and 6 respectively.
code. Assume that x and y are integers.
(B) Infinite loop and abnormal termination respec-
Count (x,y) {
tively.
if (y ! = 1) {
(C) Abnormal termination and infinite loop respec-
if (x ! = 1) {
tively.
(D) Both terminating abnormally. print (“*”);
Count (x/2, y);
23. The output of executing the following C program
}
is______.
else {
# include <stdio.h>
int total (int v) { y = y–1;
static int count = 0; Count (1024, y);
while (v) { }
count + = v&1; }
v >> = 1; }
} The number of times that the print statement is exe-
return count; cuted by the call count (1024, 1024) is ______.
} [2018]
void main ( ) {
Chapter 2  •  Functions  |  3.29

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

Previous Years’ Questions


1. C 2. - 3.  -D 4. B 5. C 6. D 7. B 8. D 9. C 10. B
11. C 12. 9 13.  1.72 to 1.74 14. B 15. 51 16. B 17. 230 18. 0 19. A
20. C 21. A 22. C 23. 23 24. 4 25. 10230

You might also like