0% found this document useful (0 votes)
22 views70 pages

Programming in C: Learning Objectives

Uploaded by

bump.stillarya
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)
22 views70 pages

Programming in C: Learning Objectives

Uploaded by

bump.stillarya
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/ 70

Chapter 1

Programming in C

LEARNING OBJECTIVES

• Basic concepts • Precedence decreases as we move from top to bottom


• Character set • Type conversion
• Identifier • Documentation section
• Declaring a variable • Preprocessing
• Visualization of declaration • Global declaration
• Constants • Control statements
• Single character constants • Selection/Decision making statement
• String constants • Looping statements
• Using const keyword • Unconditional jump statements

BASIC CONCEPTS Variable


The name itself represents value, is not constant. Variable is a
Character Set data name whose value varies/changes during program execution.
Variable name is a name given to memory cell (may be one or
A character refers to an alphabet, digit or a special symbol. multiple bytes).
Alphabets: A – Z, a – z
Digits: 0 -9
Special symbols:
DATA TYPES
∼ ! # % ∧ and * ( ) - + { } [ ] - < > , . | ? \ | : ; ” ’ White space Represents type of data and set of operations to perform on data .
Data Type
Identifier Primitive/Basic Derived User defined Valueless
Identifier is a user-defined name used for naming a variable or a – Char – Array – Structure
function. – float – pointer – union – void
Rules for naming an identifier
– double Enumeration
• Consists only letters, digits and underscore – integer
• Starts only with an alphabet or underscore
• Keywords cannot be used.
Type Keyword Number of Bytes
• Can be as long as you like, first 31 characters are significant.
Integer int 2

Example: Valid identifiers: RollNo, Roll_No, _Roll_No Floating float 4


rollno, Name2; Double double 8
Invalid: 2name, Roll No. Character char 1
3.4 | Unit 3 • Programming and Data Structures

Declaring a Variable Constants


A constant value is one which does not change during the
• Before using a variable, you must give some information
execution of a program.
to compiler about the variable. i.e., you must declare it.
C supports several types of constants:
• Declaration statement includes the type and variable
name. 1. Integer constants
2. Real constants
Syntax:
3. Single character constants
Datatype Var_name;
4. Strings constants
Example:
int roll_no;
char ch; Integer constants
float age;
An integer constant is a sequence of digits. It consists of
• When we declare a variable a set of digits 0 to 9 preceded by an optional + or - sign
• memory space is allocated to hold a value of specified spaces, commas, and non-digit characters are not permitted
type. between digits.
• space is associated with variable name Examples for valid decimal integer constants are
• space is associated with a unique Address. 123
-31
Table 1 Visualization of declaration 0
roll no 562321
int roll no; garbage
+78
Examples for invalid integer constants are
2002
20,000
marks `1000
int marks = 10; 10
3008 Real constants
diameter Real constants consist of a fractional part in their represen-
float diameter = 5.9 5.9 tation. Integer constants are inadequate to represent quanti-
4252 ties that vary continuously.
ch → variable name Examples of real constants are
char ch : ‘A’ A → value
0.0026
-0.97
2820 → address
435.29
Note: The default value is garbage, i.e., an unknown value +487.0
is assigned randomly.
Renaming data types with typedef Typedef is a keyword,
Single character constants
which can form complex types from the basic type, and will A single character constant represents a single character
assign some simpler names for such combinations. This is which is enclosed in a pair of quotation symbols.
more helpful when some declaration is very tough, confus- Examples for character constants are
ing or varies from one implementation to another. ‘5’
For example, the data type unsigned long int is redefined ‘x’
as LONG as follows: ‘;’
typedef unsigned long int LONG;
String constants
Uses of enumerated data types Enumerated data types are
A string constant is a set of characters enclosed in dou-
most useful when one is working over small, discrete set
ble quotation marks. The characters in a string constant
of values, in which each is having a meaning and it is not
sequence may be alphabet, number, special character and
a number.
blank space.
A best example can be given on months jan, feb, mar, …,
dec, which are 12 in number, with assigning consecutive num- Examples of string constants are
bers for it. “VISHAL”
The main advantages are storage efficiency, the c-code “1234”
can become readable “C language”
“!….?”
Chapter 1 • Programming in C | 3.5

Naming constants 2. int a, b = 55, c = 10;


A name given to a constant value. Value of name does not initializes ‘b’ with 55 and ‘c’ with ‘10’.
change during program execution. b + c = a; // Invalid
Only variable is allowed on left side of assignment.
Using const keyword 3. int a = 15, b = 20, c = 2, d = 5, e = 10, f, g, h, i;
When we use ‘const’ with data type, memory will be allo- f = a << c;
cated to variable and the initialized value does not change. ‘a’ is left shifted for ‘c’ times and result stored in ‘f’
const int x = 10; i.e.,
const float pi = 3.141; a = 15 = (1 1 1 1)2
↓↓↓↓
Using # define 1 1 1 1 0 (After first shift)
# define x 10 ↓↓↓↓
# define pi 3.141 1 1 1 1 0 0 (After second shift)
Where ‘# define’ is instruction to preprocessor so memory One left shift multiplies 15 by 2 = 30
is allocated. The preprocessor replace each occurrence of Again the 2nd left shift multiplies 30 by 2 = 60
name with value in program before execution. Thus 15 × 22 = 60, where the power of 2 is the number
of times shift is made. Value of ‘f ’ becomes 60.
OPERATOR Note: Left shift multiplies the value by 2. Right shift divides
An operator is a symbol which performs operations on the value by 2.
given data elements. g = a and b;
a-01111
Table 2 Precedence and Associativity b-10100
( ) Parenthesis ______________
[ ] Index 00100=4
L-R ______________
→ Member of ‘&’ performs bitwise AND. So ‘g’ value is ‘4’.
• Member of h = a|b; a - 0 1 1 1 1
Pre ++, - - b-10000
(unary) - , &(address of ) R-L _______________
* (Indirection ) 1 1 1 1 1 = 31
_______________
Arithmetic * , /, % L-R “I ” performs bitwise ‘OR’. R value is ‘31’.
Arithmetic: +, - L-R i=a^d: a-1111
Bitwise shift : ≪, ≫ L-R b-0101
_____________
Relational: <, >, =. >, > = = =, ! = L-R
1 0 1 0 = 10
Bitwise ex -OR : ∧ L-R _____________
‘^’ performs bit-wise ex - OR. i value is ‘10’.
Logical AND : && L-R
4. int a = 100 , b = 200, c = 300, x;
Logical OR : || L-R
x = (a > b)?((a > c)? a:c):((b > c)? b:c);
Conditional: ? : R-L false c
Assignment & compound Assignment x = c
R-L
=, + =, - =, * =, / = ; % = so, x = 300
Separation operator: , (comma) L-R 5. int i = 10, j = 10, x, y;
x = i+++++i+i+++++i+++i
Note: For Assignment operator, only a variable is allowed executes as

}
on its left. ++ i
++ i pre-increments
Precedence Decreases as We Move from ++ i
Top to Bottom X = i + i + i + i + i
i ++ ; post-increments
Examples:
i ++ ; }
1. int a,b,c; so x = 65, i = 15.
a = b = c = 0; y = j - - + - - j + j - - + - - j +
Assigns ‘0’ to a,b,c; - - j
3.6 | Unit 3 • Programming and Data Structures

executes as Notes: ‘C’ allows both implicit and explicit type conversion.
- - j;

- - j; }
- - j; pre decrements

y = j + j + j + j + j ;
Type conversion is of two types:
1. Narrowing: Conversion of ‘higher’ type to ‘lower’
type.
2. Widening: Conversion of ‘lower’ type to ‘higher’ type.
j - -;
}
j - -; post decrements.
y = 35; j = 5
Widening
Char – int ¬– long – float – double – long double

6. int i = 10; Narrowing

printf(“%d%d%d%d%d”, i++, ++i, ++i, Note: Narrowing causes loss of data.


i++, ++i); Input/output Functions
evaluates the values in printf from Function Purpose
right to left.
printf prints formatted string
So
scanf reads formatted string
i++, ++i, ++i, i++, ++i
getchar reads character
Prints 14 14 13 11 11 putchar displays a character
Printf (“%d”, i) gets reads a string
Prints 15:
puts displays a string

TYPE CONVERSION Format Specifier Purpose


‘C’ allows mixed mode operations, i.e., variables of differ- %c single character
ent type may appear in same expression. To perform the
operation, the data need to convert into compatible type. %d decimal integer

The conversion takes place in two ways: %e floating point

%f floating point
Implicit
%h short int
C automatically converts any intermediate values to proper
type so that the expression can be evaluated without losing %o octal integer

any significance. %x hexa decimal


For mixed mode operations, generally the ‘lower’ type is
%s string
automatically converted to ‘higher’ type before the opera-
tion proceeds. %u unsigned decimal integer

Note: scanf(“%s”, string_var); does not read string which


Explicit
contains white space. Hence to read multi word string use
‘C’ allows programmer to use type conversion operator to gets(string_var);
convert a data value to the required type.
Example 1: Which of following comment regarding the
Syntax: reading of a string using scanf( ) and gets ( ) is true?
V1 = (type) V2; (A) Both can be used interchangeably
Type in parenthesis represents the destination type. (B) scanf is delimited by end of line, gets is delimited by
Example: int a = 3, b = 2, float x, y; blank space
(C) scanf is delimited by blank, gets is delimited by end of
Case I: x = a/b;
line
results x = 1.000000
(D) None of these
Case II: y = (float) a/b; Ans: (C)
results y = 1.500000.
Because, in case 1, the integer division is performed and
so returns an integer by division operator. While assigning the
PROGRAM STRUCTURE
integer value implicitly converted to 1.000000, then assigns /* Documentation section */
to float variable x where as in case 2, (float)a converts value Preprocessor commands;
of ‘a’ to float, the second variable ‘b’ is integer. The compiler Global declaration;
implicitly converts integer to float. Then it performs float main ()
division. So 1.500000 is stored into floating variables.
Chapter 1 • Programming in C | 3.7

{ {
Body of main; Statement2(s);
} }
User defined function area; else
{
Documentation section/comments Ignored by com- Statement3(s);
piler, provides additional information to user to improve }
readability.
Nested if:
Preprocessing Tells the compiler to do pre-processing if (expression1)
before doing compilation. For example {
Statement(s)1;
#include < stdio.h > tells to include stdio header file.
if (expression(s)2)
else
Global declaration It contains variable declarations, these
Statement(s)3;
are accessible in more than one function.
}
Function Functions are main building blocks of ‘C’ pro- else
gram. Every ‘C’ program contains one or more functions. A Statement(s)4;
mandatory function called ’main( )’ instructs the compiler Note: If the expression evaluates to true then the statements
to start execution from here. of if block gets executed otherwise else block statements
will execute.
User defined area Here user can define his own functions.
Example 2: Consider the following program segment:
if (a > b) printf (“a > b”);
CONTROL STATEMENTS else
The statement that controls the execution sequence of a pro- printf (“else part”);
gram is called “control statement”. printf (“a < = b”);
a < = b will be printed if
The control statements are classified as:
(A) a > b (B) a < b
1. Selection statement: if, switch (C) a = b (D) all of these
2. Iterative/looping statement: While, do-while, for Ans: (D)
3. Unconditional jump statements: break, continue, Because the statement, printf(“a < = b”); is not the part of
return, goto either if block or else block.
The switch statement Switch is a multi-way (n-way)
Selection/Decision-making Statement selection statement.
Makes a decision to select and execute statement(s) based
on the condition. ‘C’ supports if and switch selection Syntax:
statements. switch (var_name/exp)
{
The if statement “if ” is called two-way selection statement. case const1: stmts1;
Syntax: break;
if (expression) // simple-if case const2: stmts2;
statement(s); break;
if (expression) // if-else .
{ .
statement1(s); .
} case constn: stmts n;
else break;
{ default: statements;
statements(s); }
} Notes:
if (expression) // ladder else-if. • For switch only the integral (integer/char) type variables
{ or expression evaluates to integral allowed.
Statement1(s); • Absence of break after case statements leads continua-
} tion execution of all case statements followed by match-
else if (expression2) ing case block.
3.8 | Unit 3 • Programming and Data Structures

Example 3: do-while is same as ‘while; except that the statement(s) will


main () execute for at least once.
{ Notes:
int i = 10; • The condition will not be evaluate to execute the block
switch(i) for first time.
{ • ‘do-while’ is called exit-control loop.
case 10 : printf (“case 10”);
Example 5:
case 15 : printf (“case 15”);
main ( )
case 20 : printf (“case 20”);
{
default : printf (“default case”);
int i = 0;
}
while (i! = 0)
}
{
Output: Case 10 case 15 case 20 default case printf(“%d”, i);
Reason: Missing break after each case, leads to execution i++;
of all the cases from matching case. }
Example 4: }
main ( ) No output, because the condition is false for the first time.
{ main ( )
int i = 10; {
switch (i) int i = 0;
{ do
case 10 : printf(“case 10”); {
break ; printf(“%d”, i);
case 8 + 2 : printf(“case 8+2”); i++;
break; } while (i! = 0);
default : printf(“ No matching case”); }
} Output: Displays 0 to 32767 and-32768 to-1
}
The for loop ‘for’ provides more concise loop control
Program raises an error called ‘Duplicate case’ while com-
structure.
piling because the expression ‘8 + 2’ evaluates to ‘10’.
Syntax:
Looping Statements for(exp1; exp2; exp3)
{
Sometimes, there is a situation to execute statement(s) repeat-
Statement(s);
edly for a number of times or until the condition satisfies. C’
}
supports following looping statements: while, do-while, for.
Expression 1: Initialization expression may contain mul-
While Statement tiple initializations. It executes only once before executing
the loop for first time.
Syntax: while (condition)
{ Expression 2: Condition expression. Only one condition
Statement(s); expression is allowed. That may be single or compound
} condition, evaluates before every execution.
If the condition is true the block of statements will execute Expression 3: Modification statement may contain multi-
and control returns to condition, i.e., the statement(s) exe- ple statements. It executes on completion of loop body for
cutes till the condition becomes false. every iteration.
Notes: Note: All the expressions in parenthesis are optional. Two
• ‘While’ executes the block either ‘0’ or more times. semi-colons (;) are compulsory even though there are no
• ‘While’ is called entry control loop. expressions.
Odd loops In the for loop, while loop, the condition speci-
Do-while Statement. fies the number of times a loop can be executed. Sometimes
Syntax: a user may not know, about the number of times a loop is
do to be executed. If we want to execute a loop for unknown
{ number of times, then the concept of odd loops should be
Statement(s); implemented, these can be done using the for, while (or)
} while (condition); do-while loops. Let us illustrate odd-loop with a program
Chapter 1 • Programming in C | 3.9

# include <stdio.h> Reverse jump, executes the statements repeatedly where as


main() in forward jump, the statements are skipped from execution.
{
int num, x; Example 6:
num = 1; main( )
while (num = = 1) {
{ int i ;
printf (“enter a number“); for (i=1; i<=10; i++)
scanf (“%d”, & x); {
if((x % 2) = = 0) if (i = = 5)
printf(“number is even”); break;
else printf(“%d” , i);
printf(“number is odd”); }
printf(“do u want to test any num.”); }
printf(“for yes-enter ‘1’, No-enter ‘0’”); output: 1 2 3 4
Scanf(“%d”,& num); if i = 5, then the loop will break.
}
} Example 7:
main( )
Unconditional Jump Statements {
int i ;
• “C” language permits to jump from one statement to for (i = 1; i<=10; i++)
another. {
• ‘C’ supports break, continue, return and goto jump if (i = = 5)
statements. continue;
printf(“%d” , i);
Break statement Breaks the execution sequence. That is
}
when the break statement executes in a block (loop) it’ll
}
come out from block (loop).
o/p: 1 2 3 4 6 7 8 9 10
Syntax: if i = 5, the loop statements skipped for that iteration. So it
break; does not print ‘5’.
Continue statement Used to skip a part of the loop under Example 8:
certain conditions. Output for the following program segment
Syntax: for (i = 1, j = 10 ; i < 6; ++i, --j)
continue; printf(“\n %d %d”, i, j);

Return statement Terminates the execution of a function Output:


and returns the control to the calling function. 1 10
Syntax: 2 9
return [exp/value];
3 8
Goto statement Jumps from one point to another with in a
4 7
function.
5 6
Syntax:
label1: goto label2:
Statement(s); Statement(s); Note: Since for statement allows multiple initialization and
goto label1; label2; multiple update statements, expression 1 and expression 3,
reverse jump forward jump does not raise any error.
3.10 | Unit 3 • Programming and Data Structures

EXERCISES
Practice Problems 1 printf ( “%d \n”, clrscr());
Directions for questions 1 to 15: Select the correct alterna- }
tive from the given choices. Output of the above program will be?
(A) error (B) No output
1. What will be the output of the following program? (C) 1000 (D) 1
void main()
{ 6. Output of the following program is
int i; main( )
char a[ ] =” \0 ”; {
if (printf(“%s\n”, a)) int i = -2;
printf (“ok \n”); +i;
else printf(“i = %d, +i = %d\n”, i, +i);
printf(“program error \n”); (A) error (B) -2, +2
} (C) -2, -2 (D) -2, 2
(A) ok (B) progam error 7. main( )
(C) no output (D) compilation error {
2. Output of the following will be int n;
# define FALSE-1 printf(“%d”, scanf (“%d”, & n));
# define TRUE 1 }
# define NULL 0 For the above program if input is given as 20. What will
main( ) be the output?
{ (A) 20 (B) 1
if(NULL) (C) 2 (D) 0
puts(“NULL”); 8. How many times will the following code be executed?
else if(FALSE) {
puts(“TRUE”); x = 10;
else while (x = 1)
puts(“FALSE”); x ++;
} }
(A) NULL (B) TRUE (A) Never
(C) FALSE (D) 1 (B) Once
3. main( ) (C) 15 times
{ (D) Infinite number of times
printf(“%x”,-1 << 4) ; 9. The following statement
} printf(“%d”, 9%5); prints
For the above program output will be (A) 1.8 (B) 1.0
(A) FFF0 (B) FF00 (C) 4 (D) 2
(C) 00FF (D) 0FFF 10. int a;
4. For the following program printf(“%d”, a);
# define sqr (a) a*a What is the output of the above code fragment?
main( ) (A) 0 (B) 2
{ (C) Garbage value (D) 3
int i; 11. printf(“%d”, printf(“time”));
i = 64 / sqr(4); (A) syntax error
printf( “%d”, i); (B) outputs time 4
} (C) outputs garbage
output will be (D) prints time and terminates abruptly
(A) 4 (B) 16 12. The following program
(C) 64 (D) compilation error main( )
5. #define clrscr ( ) 1000 {
main ( ) int i = 2;
{ {
clrscr(); int i = 4, j = 5;
Chapter 1 • Programming in C | 3.11

printf (“%d%d”,i,j); 14. What is the output of the following program segment?
} int a = 4, b = 6;
printf (“%d%d”,i,j); printf(“%d”, a = b);
} (A) Outputs an error message
(A) Compiler error: unrecognised symbol j; (B) Prints 0
(B) Prints 2545 (C) Prints 1
(C) Print 4525 (D) None of these
(D) None of the above
15. The statements:
13. What is the output of the following program fragment? a = 7;
for (i = 3; i < 15; i + = 3); printf(“%d”, (a++));
printf (“%d”, i); prints
(A) a syntax error (B) an execution error (A) Value of 8 (B) Value of 7
(C) prints 12 (D) prints 15 (C) Value of 0 (D) None of the above

Practice Problems 2 9. An unrestricted use of ‘goto’ statement is harmful because


Directions for questions 1 to 12: Select the correct alterna- (A) it results in increasing the executing time of the
tive from the given choices. program
(B) it increases the memory of the program
1. If the condition is missing in a FOR loop of a C pro- (C) it decreases the readability and testing of program
gram then (D) None of the above
(A) It is assumed to be present and taken to be false
(B) It is assumed to be present and taken to be true 10. What will be the output?
(C) It results in syntax error main()
(D) Execution will be terminated abruptly {
int i = 0, j = 0;
2. Which of the following operators in ‘C’ does not asso-
if(i && j ++)
ciate from the right?
printf(“%d..%d”, i++, j);
(A) = (B) + =
printf(“%d..%d”, i, j);
(C) postfix++ (D) >
}
3. In a C programming language x - = y + 1 means (A) 1..1 (B) 2..2
(A) x = -x - y - 1 (B) x = x - y + 1 (C) 0..0 (D) 1..1, 1..1
(C) x = x - y - 1 (D) x = -x + y + 1
11. What is the output?
4. Minimum number of temporary variables needed to main ()
swap two variables is {
(A) 1 (B) 2 int a = 0;
(C) 3 (D) 0 int b = 20;
5. A preprocessor command char x = 1;
(A) need not start on a new line char y = 10;
(B) need not start on the first column if(a, b, x, y);
(C) has # as the first character printf(“hello”);
(D) comes after the first executable statement }
6. printf (“%d”, printf (“%d”, printf(“time4kids”))); (A) logical error (B) Garbage value
(A) Outputs time (B) Syntax error (C) hello (D) 20
(C) Outputs 9 (D) None of the above 12. What will be the value of count after executing the
7. for (i = 1; i < 5; i++) below program:
if (i!=3) main ( ) {
int count = 10, digit = 0;
printf(“%d”, i); while (digit < = 9) {
Outputs: printf (“%d\n”, ++count);
(A) 12345 (B) Error ++digit;
(C) 1245 (D) 0000 }
8. Which operand in ‘C’ takes only integer operands? }
(A) * (B) / (A) 10 (B) 11
(C) % (D) + (C) 20 (D) 21
3.12 | Unit 3 • Programming and Data Structures

PREVIOUS YEARS’ QUESTIONS


1. Which one of the following are essential features of 4. Suppose n and p are unsigned int variables in a C pro-
an object-oriented programming language? gram. We wish to set p to nC3. If n is large, which one of
(i) Abstraction and encapsulation the following statements is most likely to set p correctly?
(ii) Strictly-typedness [2014]
(iii) Type-safe property coupled with sub-type rule (A) p = n * (n - 1) * (n - 2)/6;
(iv) Polymorphism in the presence of inheritance (B) p = n * (n - 1) /2* (n - 2)/3;
[2005] (C) p = n * (n - 1) /3 * (n - 2)/2;
(A) (i) and (ii) only (D) p = n * (n - 1) * (n - 2)/6.0;
(B) (i) and (iv) only 5. The secant method is used to find the root of an equa-
(C) (i), (ii) and (iv) only tion f (x) = 0. It is started from two distinct estimates
(D) (i), (iii) and (iv) only xa and xb for the root. It is an iterative procedure
involving linear interpolation to a root. The iteration
2. Which of the following are true? stops if f (xb) is very small and then xb is the solution.
(i) A programming language which does not permit The procedure is given below. Observe that there is
global variables of any kind and has no nesting of an expression which is missing and is marked by ?.
procedures/functions, but permits recursion can be Which is the suitable expression that is to put in place
implemented with static storage allocation of ? so that it follows all steps of the secant method?
[2015]
(ii) Multi-level access link (or display) arrangement is
Secant
needed to arrange activation records only if the pro-
gramming language being implemented has nesting Initialize: xa, xb, ε, N // ε = convergence indicator
of procedures/functions // N = maximum no. of
iterations
(iii) Recursion in programming languages cannot be
fb = f (xb)
implemented with dynamic storage allocation
i=0
(iv) Nesting procedures/functions and recursion require while (i < N and | fb | > ε) do
a dynamic heap allocation scheme and cannot be i=i+1 // update counter
implemented with a stack-based allocation scheme xt = ? // missing expression for
for activation records // intermediate value
(v) Programming languages which permit a function to xa = xb // reset xa
return a function as its result cannot be implemented xb = xt // reset xb
with a stack-based storage allocation scheme for acti- fb = f (xb) // function value at new xb
vation records end while
[2008] if | fb | > ε then // loop is terminated with i = N
(A) (ii) and (v) only (B) (i), (iii) and (iv) only write “Non-convergence”
(C) (i), (ii) and (v) only (D) (ii), (iii) and (v) only else
write “return xb”
3. What will be the output of the following C program end if
segment? (A) xb – ( fb – f (xa) ) fb / (xb – xa)
char inChar = ‘A’; (B) xa – (fa – f(xa) ) fa / (xb – xa)
switch(inChar) { (C) xb – (xb – xa) fb / ( fb – f (xa))
case ‘A’: printf(“choice A\n”): (D) xa – (xb – xa) fa / ( fb – f (xa))
case ‘B’: 6. Consider the following C program:
case ‘C’: printf(“choice B”); #include<stdio.h>
case ‘D’ int main( )
case ‘E’: {
default: printf(“No Choice”);} [2012] int i, j, k = 0;
(A) No choice j = 2 * 3 / 4 + 2.0 / 5 + 8 / 5;
(B) Choice A k -= --j;
(C) Choice A for (i = 0; i < 5; i ++)
Choice B No choice {
(D) Program gives no output as it is erroneous switch(i + k)
Chapter 1 • Programming in C | 3.13

{ ensure that the loop terminates in a state satisfying the


case 1: condition x == (y*q + r)? [2017]
case 2: printf(“\n%d”, i + k); (A) (q == r) && (r == 0)
case 3: printf(“\n%d”, i + k); (B) (x > 0) && (r == x) &&(y > 0)
default: printf((“\n%d”, i + k); (C) (q == 0) && (r == x) && (y > 0)
} (D) (q == 0) && (y > 0)
}
8. Consider the following C Program.
return 0;
#include<stdio.h>
}
int main () {
The number of times printf statement is executed is int m = 10;
_______. [2015] int n, nl ;
7. Consider the C program fragment below which is n = ++m;
meant to divide x by y using repeated subtractions. nl = m++;
The variables x, y, q and r are all unsigned int. n−−;
while (r >= y) { −−nl;
r = r - y; n −= nl;
q = q + 1; printf (“%d”, n) ;
} return 0;
Which of the following conditions on the variables x, }
y, q and r before the execution of the fragment will The output of the program is ___________. [2017]

ANSWER KEYS
EXERCISES
Practice Problems 1
1. A 2. B 3. A 4. C 5. C 6. C 7. B 8. D 9. C 10. C
11. B 12. A 13. D 14. D 15. B

Practice Problems 2
1. B 2. D 3. C 4. D 5. C 6. D 7. C 8. C 9. C 10. C
11. C 12. C

Previous Years’ Questions


1. B 2. D 3. C 4. B 5. C 6. 10 7. C 8. 0
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( )       n −1      
f (&i, &j)      ( 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)     
     f ( a + 1), 
0      [*a is even ]
pointers refer to parameter ‘j’.
*p = 12 12 +  7 − 13 −  4 + 11 −  6 + 
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 13. 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) { 14. 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 (B) X: (getchar(ch)! = ‘\n’)
Y: ch = putchar( );
5. When a recursive function is called, all its automatic
variables are (C) X: ((ch = getchar( ) )! = ‘\n’)
Y: putchar(ch);
(A) maintained in stack
(B) retained from last execution (D) X: ((ch = getchar( )) = = ‘\n’)
Y: putchar (ch);
(C) initialized during each call of function
(D) none of these 9. Consider the following C function:
int f(int n)
6. Consider the following program segment:
{
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:
int incr (int i)
7. Consider the following C program segment:
{
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( ) {
(C) Θ(log 2 log 2 n) (D) Θ( n ) int x = 15;
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) Θ( n2 ) (B) Θ( n log 2 n) {
(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]
(A) ?1 is (getchar( )! = ‘\n’) Common data for questions 6 and 7: Consider the fol-
?2 is getchar(c); lowing recursive C function that takes two arguments.
(B) ?1 is (c = getchar( ))! = ‘\n’) unsigned int foo (unsigned int n, unsigned int r)
?2 is getchar(c); {
(C) ?1 is (c! = ‘\n’) if ( n > 0 ) return ((n % r) + foo (n /r,
?2 is putchar(c); r));
(D) ?1 is ((c = getchar( ))! = ‘\n’) 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

15. Consider the following C function [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 _____
19. 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
Chapter 3
Arrays, Pointers and Structures
LEARNING OBJECTIVES

 Arrays  Dynamic memory management


 Array initialization  Memory allocation function
 Passing array elements to function  Realloc
 Two dimensional arrays  Structures
 Syntax for 3D array declaration  Nesting of structures
 Pointers  Array of structures
 Pointer to pointer  Structures & functions
 Pointer to void (generic pointer)  Union
 Array of pointers  Declaration
 Pointer to function  Bit fields

ARRAYS Example: int marks[6];


Here, ‘int’ specifies the type of variable, marks specifies name of
In C we have the following derived data types:
variable. The number 6 tells the dimension/size. The ‘[ ]’ tells the
• Arrays compiler that we are dealing with array.
• Pointers Accessing array elements: All the array elements are num-
• Structures bered, starting from 0, thus marks [3] is not the third, but the fourth
• Unions element.
Imagine a problem that requires to read, process, and print 10 Example: marks[2] – 3rd element
integers. We can declare 10 variables, each with different name. marks[0] – 1st element
Having 10 different names creates a problem; we need 10 read and We can use the variable as index.
10 write statements each for different variable. Thus marks[i] – ith element. As the value of i changes, refers dif-
ferent elements in array.
Definition
An array is a collection of elements of same data type. Array is a Summary about Arrays
sequenced collection. So, we can refer to the elements in array as 0th • An array is a collection of similar elements.
element, 1st element, and so on, until we get the last element. The • The first element in array is numbered 0, and the last element is
array elements are individually addressed with their subscripts/indi- one less than the total size of the array.
ces along with array name. We place subscript value in square brack- • An array is also known as subscripted variable.
ets ([ ]) followed by array name. This notation is called indexing. • Before using an array, its type and dimension must be
There is a powerful programming construct, loop, that makes declared.
array processing easy. It does not matter if there are 1, 10, 100 or • How big an array is, its elements are always stored in contiguous
1000 elements. memory locations.
We can also use a variable name in subscript, as the value of • Individual elements accessed by index indicating relative posi-
variable changes; it refers different elements at different times. tion in collection.
• Index of an array must be an integer.
Syntax of Array Declaration
Data_type array_name_[size]; Array Initialization
Here, data type says the type of elements in collection, array_name
is the name given to collection of elements and size says the num- Syntax
ber of elements in array. Data_type array_name[size] = {values};
Chapter 3 • Arrays, Pointers and Structures | 3.31

Example: Output:
int n[6]= {2,4,8,12,20,25}; // Array ini- 10 15 20 25 30
tialized with list of values
Here, we are passing the entire array by name. The formal
int num[10] = {2,4,12,20,35};
parameter to receive is declared as an array, so it receives
// remaining 5 elements are initialized with
entire array elements.
0
To pass the individual elements of an array, we have to
// values
int b[10] = {0}; // Entire array elements
use index of element with array name.
initialized with 0. Example: display (marks[ i ] ); sends only the ith element
Note: as parameter.
• Till the array elements are not given any specific value, Example: A program to demonstrate call by reference:
they are supposed to contain garbage values. void main( )
• If the number of elements used for initialization is lesser {
than the size of array, then the remaining elements are void display (int *);
initialized with zero. int marks[ ] = {5, 10 15, 20, 25};
• Where the array is initialized with all the elements, men- display(&marks[0]);
tioning the dimension is optional. }
void display(int *p)
{
Array Elements in Memory int i;
Consider the following declaration – int num[5]. for(i = 0; i < 5; i++)
printf(“%d “,*(p+i));
What happens in memory when we make this declaration?
}
• 10 bytes get received in memory, 2 bytes each for
5 integers. Output:
• Since array is not initialized, all five values in it would be 5 10 15 20 25
garbage. This happens because the default storage class Here, we pass the address of very first element. Hence, the
is auto. If it is declared as static, all the array elements variable in which this address is collected (p) is declared as
would be initialized with 0. a pointer variable.
Note: Array elements are stored in contiguous memory
20012 20014 20016 20018 20020
location, by passing the address of the first element; entire
Note: In C, the compiler does not check whether the sub- array elements can be accessed.
script used for array exceeds the size of array.
Data entered with a subscript exceeding the array
size will simply be placed in memory out size the array, TWO-DIMENSIONAL ARRAYS
and there will be no error/warning message to warn the In C a two-dimensional array looks like an array of arrays,
programmer. i.e., a two-dimensional array is the collection of one-dimen-
sional arrays.
Passing array elements to function Example: int x[4][2];
Array elements can be passed to a function by value or by
reference. 0 1

Example: A program to pass an array by value: 0


void main( ) 1
{
void display(int[ ]);// Declaration 2
int marks[ ] = {10,15,20,25,30}; 3
display (marks);// function call
} By convention, first dimension says the number of rows in
void display(int n[ ] )// function definition array and second dimension says the number of columns in
{
each row.
int i;
for(i = 0 ; i < 5 ; i++)
In memory, whether it is one-dimensional or a two-
printf(“%d “, n[ i ] ); dimensional array, the array elements are stored in one con-
} tinuous chain.
3.32 | Unit 3 • Programming and Data Structures

The arrangement of array elements of a two-dimensional array in memory is shown below:


X [0][0] x [0][1] x [1][0] x [1][1] x [2][0] X [2][1] X [3][0] X [3][1]

6000 6002 6004 6006 6008 6010 6012 6014

Initialization Example:
We can initialize two-dimensional array as one-dimensional void main( )
array: {
int i, j, k;
int a[4] [2] = {0,1,2,3,4,5,6,7}
int arr [3] [3] [3] =
The nested braces can be used to show the exact nature {
of array, i.e., {11, 12, 13},
int a[4][2] = {{0,1},{2,3}{4,5},{6,7}} {14, 15, 16},
{17, 18, 19}
Here, we define each row as a one-dimensional array of },
two elements enclosed in braces. {21, 22, 23},
Note: If the array is completely initialized with supplied {24, 25, 26},
values, then we can omit the size of first dimension of an {27, 28, 29}
},
array (the left most dimension).
{31, 32, 33},
• For accessing elements of multi-dimensional arrays, we {34, 35, 36},
must use multiple subscripts with array name. {37, 38, 39}
• Generally, we use nested loops to work with multi- }
dimensional array. };
printf(“3D Array Elements \n”);
for (i = 0; i<3; i++)
MULTIDIMENSIONAL ARRAYS {
C allows array of two or more dimensions and maximum for(j =0; j <3; j++)
numbers of dimensions a C program can have depends on {
the compiler, we are using. Generally, an array having one for (k= 0; k<3; k++)
dimension is called 1D array; array having two dimensions {
printf (“% d\t”, arr[i][j][k]);
is called 2D array and so on.
}
Syntax: printf (“\n”);
type array-name[d1] [d2] [d3] [d4]…[dn]; }
where dn is the size of last dimension. printf (“\n);
}
Example: }
int table[5][5][20];
Output: 3D Array Elements
float arr[5][6][5][6][5];
In our example array “table” is a 3D. (A 3D array is an array 11 12 13
of array of array) 14 15 16
17 18 19
Declaration and Initialization of 3D array
A 3D array can be assumed as an array of arrays; it is an 21 22 23
array of 2D arrays and as we know 2D array itself is an array 24 25 26
of 1D arrays. A diagram can help you to understand this. 27 28 29

31 32 33 2nd 2D array 31 32 33
21 22 23 1st 2D array 34 35 36
0th 2D array
37 38 39
11 12 13

14 15 16 Syntax for 3D Array Declaration


17 18 19 data–type array–name [table] [row] [column];
To store values in any 3D array, first point to table number,
Figure 1 3D array conceptual view row number and lastly to column number.
Chapter 3 • Arrays, Pointers and Structures | 3.33

POINTERS Here, p, x and ch are pointer variables, i.e., variables capa-


ble of holding address. Since addresses are always whole
Pointer is a variable which contains address of another varia-
numbers, pointers would always contain whole numbers.
ble. C’s clever use of pointers makes it the excellent language.
The declaration float *x does not mean that x contains
Consider the declaration:
floating value, x will contain address of floating point vari-
int i = 3;
able. Similarly, ‘ch’ contains address of char value.
The declaration tells the C compiler to:
• Reserve space in memory to hold in integer value.
• Associate the name i with this memory location.
Pointer to Pointer
• Store the value 3 at this location. We know, pointer is a variable that contains address of
another variable. Now this variable address might be stored
Memory map is: in another pointer. Thus, we now have a pointer that con-
i Location Name
tains address of another pointer, known as pointer to pointer.
Example:
3 Value at location void main()
{
2568 Location Number int i = 3, *p, **q;
(address)
p = &i;
q =&p;
Computer may choose different location at different times printf(“\n Address of i = %u”, &i);
for same variable. The important point is the address is a printf(“\n Address of i = %u”, p);
number. printf(“\n Address of i = %u”, *q);
The expression ‘&i’ gives the address of variable ‘i’. printf(“\n Address of p= %u”, &p);
p = &i; printf(\n Address of p= %u, q);
Assigns the address of ‘i’ to variable ‘p’. printf(“\n Address of q = %u”, &q)
The variable ‘p’ is declared as: printf(‘\n value of i= %d”,i);
printf(‘\n value of i= %d”,*(&i));
int *p;
printf(‘\n value of i= %d”,*p);
* tells the compiler that variable ‘p’ is an address variable. printf(‘\n value of i= %d”,**q);
Memory map of i, *p is – }

*p i
If the memory map is
2568 3 **q *p i
2720 2568 2010 2000 3

Now, pointer ‘p’ is referring to the variable ‘i’. 2050 2010 2000
The variable ‘i’ can be accessed in two ways: Then the output is:
• By using the name of variable. Address of i = 2000
• By using the pointer variable referring to location ‘i’. Address of i = 2000
Address of i = 2000
The operator ‘*’ can also be used along with pointer variable Address of p = 2010
in expressions. The operator ‘*’ acts as indirection operator. Address of p = 2010
Address of q = 2050
int x, *p; x ? p ? Value of i = 3
Value of i = 3
Value of i = 3
p = & x; x ?
p
Value of p has Value of i = 3
Note: We can extend pointer to a pointer to pointer. In prin-
cipal, there is no limit on how far we can go on extending
*p = 4 x 4 Value of x has
p been changed this definition.

Usage of ‘p’ refers to value of ‘p’, where as ‘*p’ refers to Pointers for Inter-function Communication
value at the address stored in ‘p’, i.e., value of ‘i’. We know that functions can be called by value and called
by reference.
Example: int *p;
float *x; • If the actual parameter should not change in called func-
char *ch ; tion, pass the parameter-by value.
3.34 | Unit 3 • Programming and Data Structures

• If the value of actual parameter should get changed in Operations can be Performed on Pointers
called function, then use pass-by reference. 1. Addition of a number to a pointer.
• If the function has to return more than one value, return
Example: int i = 4, *j, *k;
these values indirectly by using call-by-reference.
j =&i;
Example: The following program demonstrates how to j = j +1;
return multiple values. k = j +5;

void main( ) 2. Subtraction of a number from a pointer.


{ Example: int i = 4, * j, * k;
void areaperi(int, int *, int *); j = &i; j = j −1;
int r; k = j – 3;
float a,p;
printf(“\n Enter radius of a circle”); 3. Subtraction of one pointer from another. One pointer
scanf(“%d”, &r); variable can be subtracted from another (provided both
areaperi(r, &a, &p); variables point to same array elements). The resulting
printf(“Area = %f”, a); value indicates the number of bytes (elements) separat-
printf(“\n Perimeter = %f”, p); ing (the corresponding array elements).
}
void areaperi(int x, int *p, int *q) Example:
{ void main ( )
*p = 3.14*x*x; {
*q = 2 * 3.14*x; int a[ ] = {5,10,15,20,25} ,*i, *j;
} i = &a[0];
Output: j = &a[4];
Enter radius of circle 5 printf(“%d, %d”, j−i,*j−*i);
Area = 78:500000 }
Perimeter = 31.400000 Output: 4, 20
Compatibility: Pointers have a type associated with them. The expression j-i prints 4 but not 8. because j and i pointing
They are not just pointer types, but rather are pointers to to integers that are 4 integers apart.
a specific type. The size of all pointers is same, which is 4. Comparison of two pointer variables. Pointer variables
equal to size of int. Every pointer holds the address of one can be compared provided both pointing to the same
memory location in computer, but size of variable that the data type.
pointer references can be different.
Notes: Do not attempt the following operations on pointers:
1. Addition of two pointers.
Pointer to Void (Generic Pointer) 2. Multiplication of a pointer with a number or another
A pointer to void is a generic type; this can point to any pointer.
type. Its limitation is that the pointed data cannot be refer- 3. Division of a pointer with a number or another pointer.
enced directly. Since void pointer has no object type, so its
length is undetermined; it cannot be dereference unless it
is cast. Important points about pointer arithmetic
• A pointer when incremented always points to an immedi-
Example: The following example demonstrates generic
ately next location.
pointer.
• A pointer when decremented always points to an element
void main ( ) precedes the current element.
{
int a = 10; Notice the difference with:
float x = 5.7; (*p)++
void *p; Here, the expression would have been evaluated as the value
p = &a; pointed by p increased by one. The value of p would not be
printf(“\n value of a = %d”, *((int*)p));
modified if we write
p= &x;
printf (“\n value of x = % f”, *((float *)p));
} *p++ = *q++;

Output: Because ++ has a higher precedence than *, both p and q


value of a = 10 are increased, but because both increase operators (++) are
value of x = 5.700000 used as postfix and not prefix, the value assigned to *p is
Chapter 3 • Arrays, Pointers and Structures | 3.35

*q before both p and q are increased. And then both are Example 4: Array of pointers pointing to 0th element of
increased, it would be equivalent to each row of a two-dimensional array
*p = *q int a[3][2] = {{1,2} {3,4}, {5,6}};
++p; int *p[3];
++q; p[0] = a[0]; p[1] =a[1];p[2] = a[2];

Implementation of arrays in C
POINTER TO FUNCTION
Array name is the pointer to the first element in array. The
Function is a set of instructions stored in memory, so the
following discussion explains how pointers are used for
function also contains the base address. This address can
implementing arrays in C.
hold by using a pointer called pointer to function.
int n[ ] = {10,20,30,40,50};
Syntax:
n 10 20 30 40 50
5512 5514 5516 5518 5520 return_type (*function_pointer)(parameter –
list );
• We know that mentioning the array name gets the base Example: int (*fp)(float, char, char);
address.
int *p = n;
Example:
// pointer to functions
Now ‘p’ points to 0th element of array ‘n’. # include <iostream>
• 0th element can be accessed as *array_ name. Using name space std;
int x = *n; int addition(int a, int b)
stores n[0] into ‘x’. {
• we can say that *array _ name and *(array _ name+0) are return (a + b);
same. This indicates the following are same. }
num[i] int subtraction(int a, int b)
*(num + i) {
*(i+num) return (a – b) ;
}
(num is an array; i is an index)
int operation (int x, int y, int (*funtocall)
(int, int))
ARRAY OF POINTERS {
The way there can be an array of ints or array of floats, sim- int g;
ilarly there can be an array of pointers. An array of pointers g = (*functocall)(x, y);
is the collection of addresses. return (g);
These arrays of pointers may point to isolated elements }
or an array element. int main( )
Example 1: Array of pointers pointing to isolated elements: {
int m, n;
int i = 5, j=10, k =15; int (*minus)(int, int) = substraction;
int *ap[3]; m = operation(7, 5, addition);
ap[0] = &i; ap[1] = &j; ap[2] = &k; n = operation(20, m, minus);
Example 2: Array of pointers pointing to elements of an cout < < n;
array: return 0;
int a[ ] = {0,20,45,50,70}; }
int *p[5], i ; In the example, minus is a pointer to a function that has two
for(i = 0; i <5 ; i++ ) parameters of type int. It is immediately assigned to point to
p[i] = &a[i] ; the function subtraction, all in a single line.
Example 3: Array of pointers pointing to elements of dif- Example: Program to demonstrate function pointer
ferent arrays; int add(int, int);
int a[ ] = {5,10,20,25}; int sub(int, int);
int b[ ] = {0,100,200,300,400}; void main( )
int c[ ] = {50,150,250,350,450}; {
int *p[3]; Int (*fp) (int, int);
p[0] = a; p[1] = b; p[2]=c; fp = add;
3.36 | Unit 3 • Programming and Data Structures

printf(“\n 4+5=%d”, fp(4,5)); Memory Allocation Function


fp = sub; • Static memory allocation uses stack memory for variables.
printf (“\n 4 − 5 = %d”, fp(4,5)); • Dynamic memory management allocates memory from
} heap.
int add(int x, int y)
{
The following are the four memory management functions
return x + y;
available in alloc.h and stdlib.h.
} 1. Malloc (Block memory allocation): Malloc function
int sub(int x,int y) allocates block of memory that contained the num-
{ ber of bytes specified in parenthesis. It returns ‘void’
return x – y; pointer to the first byte of allocated memory. The allo-
} cated memory is not initialized. If the memory alloca-
Output: 4 + 5 = 9 tion is not successful then it return NULL pointer.
4 – 5 = –1 Declaration
void *malloc (size_t size);
Pointer to structure The main usage of pointer to structure The type size_t is defined as unsigned int in several
is we can pass structure as parameter to function as call by header files including stdio.h.
reference.
Syntax: pointer = (type*) malloc(size );
The other usage is to create linked lists and other dynamic
data structures which depend on dynamic allocation. 2. Calloc (contiguous memory allocation): Calloc is
Consider the declaration primarily used to allocate memory for arrays. It initial-
struct employee izes the allocated memory with null characters.
{ Declaration: void *calloc (size_t ele_count, size_t
char name[20]; ele_size);
Int age; Syntax: ptr = (type*)calloc(ele-count,ele-size);
float salary; 3. Realloc (reallocation of memory): The realloc func-
}; tion is highly inefficient. When given a pointer to a
struct employee ∗ p; previously allocated block of memory, realloc changes
Variable of structures can be accessed using ‘.’ Operator (or) the size of block by deleting or extending the memory
→ operator that is at the end of block. If the memory cannot be extended,
(∗p).age = 20 ; (or) p → age = 20; then realloc allocates completely new block, copies the
(∗p).salary = 40, 231.0; (or) p → salary = 40,231.0; contents from existing memory location to new loca-
tion, and deletes the old location.
DYNAMIC MEMORY MANAGEMENT Declaration: void *realloc (void *ptr, size_t new_
We can allocate the memory to objects in two ways—static size);
and dynamic allocation. Static memory allocation requires Syntax: ptr = (type*)realloc(ptr, new_ size);
declaration and definition of memory fully specified in the 4. Free (Releasing memory): When the memory allo-
source program. The number of bytes required cannot be cated by malloc, calloc or realloc is no longer needed,
changed during run time. Dynamic memory allocation uses they can be freed using the function free( ).
predefined functions to allocate and de-allocate memory for Declaration: void free(void *ptr);
data dynamically during the execution of program.
We can refer to dynamically allocated memory only Syntax: free(ptr);
through pointers. Conceptual view of memory: Free function de-allocates complete memory referenced by
the pointer. Part of the memory block cannot be de-allocated.

Main( ) Functions STRUCTURES


Arrays are used to store large set of data and manipulate
Program memory
them but the disadvantage is that all the elements stored in
an array are to be of the same data type. When we require
using a collection of different data items of different data
Global Heap Stack types, we can use a structure.
Data Memory • Structure is a method of packing data of different types.
• A structure is a convenient method of handling a group of
Memory related data items of different data types.
Chapter 3 • Arrays, Pointers and Structures | 3.37

Syntax for declaration char address[20];


struct sturct_name char combination[3];
{ int age;
Data_type_1 var1; } newstudent;
Data_type_2 var2; printf (“ Enter student Information”);
: printf (“Enter student id – no”);
Data_type_n varn; scanf (“%d”, &newstudent.id_no):
}; printf (“ Enter the name of the student”);
scanf (“%s”, & newstudent.name);
Example: printf (“ Enter the address of the student”);
struct lib – books scanf (“%s”, &newstudent.address);
{ printf(“Enter the combination of the
char title [20]; student”)’;
char author[15]; scanf(“%s”, &newstudent.combination”);
int pages; printf (“ Enter the age of student);
float price; scanf (“%d “, &newstudent.age”);
}; printf (“ student information”);
The keyword struct declares a structure to hold the details printf (“ student id–no = %d”, newstudent.
of four fields namely title, author, pages and price, these are id – no);
printf(“student name = %s”, newstudent.
members of the structures.
name);
We can declare structure variables using the tag name printf(“student address = %s“, newstudent.
anywhere in the program. address);
Example: struct lib – books book1, book2, book3; printf (“students combination = %s”, newstu-
• Declares book1, book2, book3 as variables of type struct dent. combination);
lib – books, each declaration has four elements of the printf(“Age of student = %d”, newstudent.
age);
structure lib– books.
}
Memory map of book1:

Book1 Title 20 bytes Nesting of Structures


Author 15 bytes The structures can be nested in two ways:
Pages 2 bytes
Price 4 bytes • Placing the structure variable as a member in another
structure declaration.
• Memory will not be allocated to the structure until it • Declaration of the entire structure in another structure.
is instantiated. i.e., till the declaration of a variable to
Example:
structure.
struct date
• To access the members of a structure variable, C provides
{
the member of (.) operator.
int day;
Example: To access author of book 1 – book1. author int month;
int year;
Syntax: structure_var.member_name;
};
• The structures can also be initialized as any other variable struct student
of C. {
Example: struct lib-books book4={“Let us C”, int id–no;
“yashwanth”, 450, 200.95}; char name[20];
Note: The values must provide in the same order as they char address [20];
appear in structure declaration. int age;
• One structure variable can be assigned to another struc- structure date doa;
ture variable. } oldstudent, newstudent;
• Structure variables cannot be compared. The structure ‘student’ contains another structure date as
Example: one of its members.
# include <stdio.h> To access the day of date of admission (doa) of old stu-
void main( ) dent – oldstudent.doa.day.
{
Struct s1{ Example:
int id–no; struct outer
char name[20]; {
3.38 | Unit 3 • Programming and Data Structures

int o1; Structures and Functions


float o2;
• An entire structure can be passed as a parameter like any
struct inner
other variable.
{
• A function can also return a structure variable.
int i1;
float i2; Example:
}; # include <stdio.h>
} out1, out2; struct employee
{
The innermost members in a nested structure can be int emp–id;
accessed by chaining all the concerned structure variables, char name[25];
from outermost to innermost; accessing i1 for out1-out1. char department[10];
inner.i1; float salary;
};
Array of Structures void main( )
{
It is possible to define an array of structures. For example, static struct employee emp1 = {
if we are maintaining information of all the students in the 12, “shyam”, “computer”, 7500.00};
college and if 100 students are studying in the college, we /* sending entire employee structure */
need to use an array than single variables. display(emp1);
}
Example: /* function to pass entire structure vari-
structure information able */
{ display(empf)
int id – no; struct employee empf
char name[20]; {
char address[20]; printf (“ %d %s % s %f”, empf.empid, empf.
char combination[3]; name, empf.department, empf.salary);
int age; }
}
student[100]; UNION
Example: Union, like structure contains members whose individual
# include <stdio.h> data types may differ from one another. The members that
{ compose union all share the same storage area within the
struct info computer’s memory whereas each member within a struc-
{ ture is assigned its own unique storage area. Thus, unions
int id _ no; are used to conserve memory.
char name[20];
Declaration
char address[20];
char combination[3]; union item
int age; {
} int m;
struct info std[100]; float p;
int, i ,n; char c;
printf (“ Enter the number of students”); }Code;
scanf (“%d”, &n); This declares a variable code of type union item.
scanf(“Enter id–no, name, address, combina- The union contains three members each with a differ-
tion and age”); ent data type. However, we can use only one of them at a
for (i = 0; i<n; i ++) time. The compiler allocates a piece of storage that is large
scanf(“ %d %s %s %s %d”, &std[i].id_no, enough to access a union member; we can use the same syn-
std[i].name, std[i].address, tax that we use to access structure members, i.e.,
std[i]. combination,&std [i].age); Code.m
printf(“student information”); Code.p
for (i = 0 ; i < n; i ++) Code.c
printf(“%d %s %s % s % d”, std[i].id_no, are all valid member variables. During accessing, we should
std[i].name, std[i].address, std[i]. combi- make sure that we are accessing the member whose value is
nation, std[i]. age); currently stored.
Chapter 3 • Arrays, Pointers and Structures | 3.39

Example: U1.decval = 1000.5f;


union marks printf(“decval = %f pnum = %d my-value = % lf
{ “, U1. decval, U1.pnum, U1.my–value);
float perc; printf(“ U1 size = %d decval size =%d,
char grade; pnum size = %d my-value size = % d”,
} sizeof (U1), sizeof (U1.decval), sizeof
main( ) (U1.pnum), sizeof (U1.my-value));
{ }
union marks student1;
student1.perc = 98.5; Bit Fields
printf(“marks are %f address is %16ℓu”, stu- When a program variable ‘x’ is declared as int, then ‘x’ takes
dent1.perc, &student1. perc); the values from (-215) to (215 – 1), if x in the program takes
student1. grade = ‘c’; only two values, 1 and 0, which requires only one bit, then
printf(“grade is %c address is %16ℓu”, stu- the remaining 15 bits are waste.
dent1. grade, &student1. grade); In order to not to have this wastage, we can use bit fields
} with the several variables with the small enough maximal
values, which can pack into a single memory location
Example:
# include <stdio.h> Example:
void main ( ) struct student
{ {
Union u–example Int gender : 1 ; // gender takes only 0,1
{ values
float decval; Int marriage : 2 ; // marriage takes 4(0, 1,
int p-num; 2, 3) values
double my–value; Int marks : 7 ; // marks takes values from
}U1; 0 – 127
U1.my–value = 125.5; }
U1.pnum = 10;

EXERCISES
Practice Problems 1 (A) 30 (B) 22
Directions for questions 1 to 15: Select the correct alterna- (C) 20 (D) Error
tive from the given choices. 2. main( )
{
1. Output of the following C program is char *ptr;
intF(int x, int *py, int **pz) ptr = “Hello World”;
{ printf(“%c\n”,*&*ptr);
int y, z; }
** pz+= 1; Output of the above program is
z = *pz; (A) Garbage value
*py+= 2; (B) Error
y = *py; (C) H
x+ = 3; (D) Hello world
return x+y+z; 3. #include <stdio.h>
} main( )
void main( ) {
{ register a =10;
int c, *b, **a ; char b[ ] = “Hi”;
c = 4; printf(“%s %d ”, b, a);
}
b = &c;
a = &b; Output is
printf( “%d”, F(c, b, a)); (A) Hi 10 (B) Error
} (C) Hi (D) Hi garbage value
3.40 | Unit 3 • Programming and Data Structures

4. main ( ) (D) for (j=i; j<4; ++j)


{ {
int fun( ) ; M[i][j] = temp;
(*fun)( ) ; temp = M[j][i];
} M[j][i] = M[i][j] ;
int fun( ) }
{ printf(“Hello”) ; 7. Consider the C program shown below:
} # include <stdio.h>
(A) Hello (B) Error # define print(a) printf(“%d”, a)
(C) No output (D) H int a;
5. Let B be a two-dimensional array declared as void z(int n)
B : array[1...10] [1...15] of integer; {
n += a;
Assuming that each integer takes one memory location
print (n);
the array is stored in row major order and the first ele-
}
ment of the array is stored at location 100, what is the
void x(int *p)
address of the element B[i] [j]?
{
(A) 15i + 10j + 84 (B) 15i + j − 16
int a = *p+2;
(C) 15i + j (D) 15i + j + 84
z(a) ;
6. Consider the following C program which is supposed *p = a;
to compute the transpose of a given 4 × 4 matrix M. print(a);
Note that, there is a Y in the program which indicates }
some missing statements. Choose the correct option to main(void)
replace Y in the program. {
# include <stdio.h> a = 6;
int M[4][4] = { 8, 10, 9, 16, 12, 13, 11, x(&a);
15, 14, 7, 6, 3, 4, 2, 1, 5 }; print(a);
main( ) }
{ The output of this program is
int i, j, temp; (A) 14 8 6 (B) 16 6 6
for (i = 0; i<4; ++i) (C) 8 6 6 (D) 22 11 12
{
Y
8. Consider the program below:
} # include <stdio.h>
for (i=0; i<4; ++i) int fun(int n, int *p)
for (j=0; j<4; ++j) {
printf(“%d”, M[i] [j]); int x,y;
} if (n<=1)
(A) for (j=0; j<4; ++j) {
{ *p = 1;
M[j] [i] = temp; return 1;
temp = M[j][i]; }
x = fun(n-1, p);
M[j][i] = M[i][j];
y = x +p;
}
*p = x;
(B) for (j=0; j<4; ++j)
return y;
{
}
temp = M[j][i];
M[i][j] = M[j][i]; int main( )
M[j][i] = temp; {
} int a =15;
(C) for (j=i; j<4; ++j) printf( “%d\n”, fun(5, &a));
{ return 0;
temp = M[i][j]; }
M[i][j] = M[j][i]; The output value is
M[j][i] = temp; (A) 14 (B) 15
} (C) 8 (D) 95
Chapter 3 • Arrays, Pointers and Structures | 3.41

9. Consider the following C program segment main (int argc, char *argv[ ])
{
char p[20] ;
int i; int i;
char *s = “string” ; i = argv [1] + argv [2] − argv [3];
int l = strlen(s); printf ("%d", i);
for (i=0; i<l; i++) }
p[i] = s[l – i] ;
(A) 123 (B) 6
printf(“%s”, p) ;
(C) 0 (D) Error
The output of the program is
(A) string 13. The following C program is run from the command line
(B) gnirt as
(C) gnirts myprog one two;
(D) No output is printed what will be the output?
10. # include <stdio.h> main (int argc, char *argv [ ])
main( ) {
{ printf (“%c”,**++argv);
struct AA }
{ (A) m (B) o
int A = 5; (C) myprog (D) one
char name[ ] = “ANU”; 14. The following program
};
change(int *);
struct AA *p = malloc(sizeof(struct
main( ) {
AA));
int a = 4;
printf(“%d”,p–>A);
change(a);
printf(“%s”,p–>name);
printf (“%d”, a);
}
}
Output of the program is change(a)
(A) 5 ANU int a;
(B) Runtime error {
(C) Compiler error printf(“%d”, a);
(D) Linker error }
11. The declaration Outputs
union u_tag { (A) 44 (B) 55
int ival; (C) 34 (D) 22
float fval;
15. What is the output of the following program:
char sval; main( )
} u;
{
denotes u is a variable of type u_tag and const int x = 10;
(A) u can have a value of int, float and char int *ptrx;
(B) u can represent either integer value, float value or ptrx = &x;
character value at a time *ptrx = 20;
(C) u can have a value of float but not integer printf (“%d”, x);
(D) None of the above }

12. If the following program is run from command line as (A) 5 (B) 10
myprog 1 2 3, what would be the output? (C) Error (D) 20
3.42 | Unit 3 • Programming and Data Structures

Practice Problems 2 blue,


yellow = 1,
Directions for questions 1 to 11: Select the correct alterna-
green
tive from the given choices.
};
1. The following program segment
int *i; assigns the value 1 to
*i = 10; (A) Red and Yellow
(A) Results in run time error (B) Blue
(B) Is a dangling reference (C) Red and blue
(C) Results in compilation error (D) Blue and yellow
(D) Assigns 10 to i 8. What would be the output of the following program?
2. A m × n matrix is stored in column major form. The sum = 0;
expression which accesses the (ij)th entry of the same for (i = −10; i < 0; i++)
matrix is sum = sum + abs(i);
(A) n × (j − 1) + i printf ("%d", sum);
(B) m × (j − 1) + i
(C) n × (m − 1) + ij (A) 100 (B) −505
(D) m × (n − 1) + j (C) 55 (D) −55
3. int ∗ S[a] is 1D array of integers, which of the follow- 9. An integer occupies 2 bytes of memory, float occupies
ing refers to the third element in the array? 4 bytes and character occupies 1 byte. A structure is
(A) ∗(S + 2) (B) ∗(S + 3) defined as:
(C) S + 2 (D) S + 3 struct tab {
4. If an array is declared as char a[10][12]; what is referred char a;
to by a[5]? int b;
(A) Pointer to 3rd Row float c;
(B) Pointer to 4th Row } table [10];
(C) Pointer to 5th Row Then the total memory requirement (in bytes) is
(D) Pointer to 6th Row (A) 14 (B) 70
5. The following code is run from the command line as (C) 40 (D) 100
myprog 1 2 3. What would be the output? 10. What are the values of u1 and u2?
main(int argc, char *argv[ ]) int u1, u2;
{ int x = 2;
int i, j = 0; int *ptr;
for (i = 1; i < argc; i++) u1 = 2*(x + 10);
j = j + atoi (argv [i]); ptr = &x;
printf (“%d”, j); u2 = 2*(*ptr + 10);
} (A) u1 = 8, u2 = 16
(B) u1 = 23, u2 = 24
(A) 123 (B) 6
(C) u1 = 24, u2 = 24
(C) Error (D) “123”
(D) None of the above
6. What will be the following C program output?
11. What is the output?
main (int argc, char *argv[ ], char *env
func(a, b)
[ ]) {
int a, b;
int i;
{
for(i = 1; i < argc; i++)
return (a = (a = = b));
printf (“%s”, env[i]);
}
}
main ()
(A) List of all arguments {
(B) List of all path parameters int process(), func();
(C) Error printf(“The value of process is %d”, pro-
(D) List of environment variables cess (func,3,6));
7. The declaration }
process (pf, val1, val2)
enum colors {
int (*pf) ();
red,
Chapter 3 • Arrays, Pointers and Structures | 3.43

int val1, val2; (A) The value of process is 0


{ (B) The value of process is 3
return ((*pf) (val1, val2)); (C) The value of process is 6
} (D) Logical error

PREVIOUS YEARS’ QUESTIONS


1. Consider the following program in C language: void f1 (int a, int b) {
# include < stdio. h> int c;
main () c=a; a=b; b=c;
{ }
int i; void f 2(int *a, int *b) {
int *pi = &i;
int c;
scanf (“%d”, pi);
printf(“%d\n”, i + 5); c=*a; *a=*b; *b=c;
} }
Which one of the following statement is TRUE? int main ( ) {
[2014] int a=4, b=5, c=6;
(A) Compilation fails f1 (a, b);
(B) Execution results in a run-time error f2 (&b, &c);
(C) On execution, the value printed is 5 more than printf(“%d”, c-a-b);
the address of variable i. }
(D) On execution, the value printed is 5 more than
4. What is the output of the following C code? Assume
the integer value entered.
that the address of x is 2000 (in decimal) and an inte-
2. Consider the following C function in which size is the ger requires four bytes of memory. [2015]
number of elements in the array E:
int main ( ) {
int MyX (int *E, unsigned int size)
unsigned int x[4] [3] =
{
int Y = 0; { {1, 2, 3}, {4, 5, 6}, {7, 8, 9},
int Z; {10, 11, 12}};
int i, j, k; printf (“%u, %u, %u”, x + 3, *(x +
for (i = 0; i < size; i++) 3), *(x + 2) + 3);
Y = Y + E[i]; }
for (i = 0; i < size; i++)
for (j = 1; j < size; j++) (A) 2036, 2036, 2036 (B) 2012, 4, 2204
{ (C) 2036, 10, 10 (D) 2012, 4, 6
Z = 0; 5. Consider the following function written in the C pro-
for (k = i; k < = j; k++) gramming language. [2015]
Z = Z + E[k]; void foo(char *a {
if (Z > Y) if ( *a && *a != ‘ ‘){
Y = Z; foo(a + 1);
} putchar(*a);
return Y; }
} }
The output of the above function on input “ABCD
The value returned by the function My X is the [2014]
EFGH” is
(A) maximum possible sum of elements in any sub -
array of array E. (A) ABCD EFGH (B) ABCD
(B) maximum element in any sub-array of array E. (C) HGFE DCBA (D) DCBA
(C) sum of the maximum elements in all possible 6. Consider the following C program segment. [2015]
sub-arrays of array E. #include <stdio.h>
(D) the sum of all the elements in the array E. int main()
3. The output of the following C program is ______ {
[2015] char s1[7] = “1234”, *p;
3.44 | Unit 3 • Programming and Data Structures

p = s1 + 2; mystery(&c, &a);
*p = ‘0’;
mystery (&a, &d);
printf(“%s”, s1);
} printf(“%d\n”, a)
What will be printed by the program? }
(A) 12 (B) 120400 The output of the program is _____.
(C) 1204 (D) 1034 10. The following function computes the maximum value
7. Consider the following C program [2015] contained in an integer array p [ ] of size n (n > = 1).
#include<stdio.h> [2016]
int main ( ) int max (int *p, int n) {
{ int a = 0, b = n – 1;
static int a[ ] = {10, 20, 30, 40, while (_____) {
50}; if (p [a] < = p [b]) {a = a+1;}
static int *p[ ] = {a, a+3, a+4, else { b = b – 1;}
a+1, a+2}; }
int **ptr = p; return p[a];
ptr++; }
printf(“%d%d”, ptr-p, **ptr); The missing loop condition is
} (A) a ! = n
8. Consider the following C program. [2016] (B) b ! = 0
(C) b > (a +1)
void f (int, short);
(D) b ! = a
void main( )
11. The value printed by the following program is ___.
{ [2016]
int i = 100; void f (int* p, int m) {
short s = 12; m = m +5;
short *p = &s; *p = *p + m;
_____; // call to f( ) return;
} }
Which one of the following expressions, when placed void main () {
in the blank above, will NOT result in a type checking
int i = 5, j = 10;
error?
(A) f (s,*s) (B) i = f (i,s) f(&i, j);
(C) f (i,*s) (D) f (i,*p) print f (“%d”, i +j);
9. Consider the following C program. [2016] }
# include<stdio.h> 12. Consider the following program: [2016]
void mystery (int *ptra, int *ptrb) { int f (int *p, int n)
int *temp; { if (n < = 1) return 0;
temp = ptrb; else return max (f (p +1, n – 1), p [0] – p [1] );
ptrb = ptra; }
ptra = temp; int main ()
{
} int a[ ] = {3,5,2,6,4};
int main ( ) { printf (“%d”, f(a,5));
int a = 2016, b = 0, c = 4, d = 42; }
mystery (&a, &b); Note: max (x,y) returns the maximum of x and y.
if (a < c) The value printed by this program is ______
Chapter 3 • Arrays, Pointers and Structures | 3.45

13. Consider the following C code: The decimal value closest to this floating-point num-
# include <stdio.h> ber is [2017]
int *assignval (int *x, int val) { (A) 1.45 × 101 (B) 1.45 × 10-1
*x = val; (C) 2.27 × 10-1 (D) 2.27 × 101
return x; 16. Match the following:
}
(P) static char var; (i) Sequence of memory loca-
void main ( ) { tions to store addresses
int *x = malloc (sizeof (int)); (Q) m = malloc (10); (ii) A variable located in data
if (NULL == x) return; m = NULL; section of memory
x = assignval (x, 0); (R) char *ptr [10]; (iii) Request to allocate a CPU
if (x) { register to store data
x = (int *) malloc (S) register int var1; (iv) A lost memory which cannot
(sizeof (int)); be freed
if (NULL == x) return;
x = assignval (x, 10); [2017]
} (A) P → (ii), Q → (iv), R → (i), S → (iii)
printf(“%d\n”, *x); (B) P → (ii), Q → (i), R → (iv), S → (iii)
free (x); (C) P → (ii), Q → (iv), R → (iii), S → (i)
} (D) P → (iii), Q → (iv), R → (i), S → (ii)
The code suffers from which one of the following 17. Consider the following function implemented in C:
problems: [2017] void printxy (int x, int y) {
(A) compiler error as the return of malloc is not type- int ptr;
cast appropriately x = 0;
(B) compiler error because the comparison should be ptr = &x;
made as x == NULL and not as shown y = ptr;

(C) compiles successfully but execution may result ptr = 1;
in dangling pointer printf (“%d, %d” x, y);
(D) compiles successfully but execution may result }
in memory leak The output of invoking printxy (1, 1) is [2017]
14. Consider the following C program. (A) 0, 0 (B) 0, 1
(C) 1, 0 (D) 1, 1
# include <<stdio.h> 18. Consider the following snippet of a C program.
# include <<string.h> Assume that swap (&x, &y) exchanges the contents
void printlength (char *s, char *t) of x and y.
{ int main () {
unsigned int c = 0; int array[] = {3, 5, 1, 4, 6, 2};
int len = ((strlen(s) − strlen int done = 0;
(t)) > c) ? strlen (s) : strlen int i;
(t); while (done == 0) {
printf (“%d\n”, len); done = 1;
} for (i=0; i <=4; i++) {
void main ( ) { if (array[i] < array[i+1]) {
char *x = “abc”; swap(&array[i], &array[i + 1]) ;
char *y = “defgh”; done = 0;
printlength (x, y); }
} }
for (i=5; i >=l; i--) {
Recall that strlen is defined in string.h as returning
if (array[i] > array[i−l]) {
a value of type size_t, which is an unsigned int. the
swap(&array[i], & array[i−1]);
output of the program is _________. [2017]
done = 0;
15. Given the following binary number in 32-bit (single }
precision) IEEE-754 format: }
00111110011011010000000000000000 }
3.46 | Unit 3 • Programming and Data Structures

printf{“%d”, array[3]); (A) 0, c


} (B) 0, a+2
The output of the program is ________. [2017] (C) ‘0’, ‘a+2’
19. Consider the following C Program. (D) ‘0’, ‘c’
#include<stdio.h> 21. Consider the following C program:
#include<string,h> #include<stdio.h>
int main () { void fun1 (char *s1, char * s2) {
char* c = “GATECSIT2017”; char *tmp;
char* p = c; tmp = s1;
printf{“%d”, s1 = s2
(int) strlen(c+2[p]-6[p]-1)) ; s2 = tmp;
return 0; }
} void fun2 (char **s1, char **s2) {
The output of the program is __________. [2017] char *tmp;
20. Consider the following C program. tmp = *s1;
#include<stdio.h> *s1 = *s2;
struct Ournode { *s2 = tmp;
}
char x, y, z;
int main () {
} ;
char *str1 = “Hi”, *str2 = “Bye”;
Int main () {
fun1 (str1, str2);
struct Ournode p = {‘1’, ‘0’, ‘a’+2};
printf (“%s %s “, str1, str2);
struct Ournode *q = &p; fun2 (&str1, &str2);
printf (“%c, %c”, *( (char*)q+1), printf (“%s %s”, str1, str2);
* ( (char*)q+2) ); return 0;
return 0; }
} The output of the program above is: [2018]
The output of this program is: [2018] (A) Hi Bye Bye Hi (B) Hi Bye Hi Bye
(C) Bye Hi Hi Bye (D) Bye Hi Bye Hi

ANSWER KEYS
EXERCISES
Practice Problems 1
1. B 2. C 3. A 4. A 5. D 6. C 7. A 8. C 9. D 10. C
11. B 12. D 13. B 14. A 15. D

Practice Problems 2
1. B 2. B 3. A 4. D 5. B 6. D 7. D 8. C 9. B 10. C
11. A

Previous Years’ Questions


1. D 2. A 3. -5 4. A 5. D 6. C 7. 140 8. D 9. 2016 10. D
11. 30 12. 3 13. D 14. 3 15. C 16. A 17. C 18. 3 19. 2 20. A
21. A
Chapter 4
Linked Lists, Stacks and Queues

LEARNING OBJECTIVES

 Data structure  Queue


 Linked list  Double-ended queue
 Single-linked list  Circular queue
 Double-linked list  Priority queue
 Circular linked list  Array implementation
 Double circular-linked list  Linked list implementation
 Stack  Linked list implementation of priority queue

DATA STRUCTURE SINGLE-LINKED LIST


Data structure represents the logical arrangement of data in com- List in which each node contains only one link field.
puter memory for easily accessing and maintenance.
Node structure
LINKED LIST struct
A linked list is a data structure that consists of a sequence of nodes, {
each of which contains data field and a reference (i.e., link) to next int ele;
node in sequence. struct node ∗ next;
};
• Generally node of linked list is represented as self-referential typedef struct node Node;
structure.
• The linked list elements are accessed with special pointer(s) Creating a linked list with two
called head and tail.
nodes of type list node
Head Creating a linked list with 2 nodes
A B C Tail
struct node
Data Link
{
Int ele;
• The principal benefit of a linked list over a conventional array struct node ∗ next ;
is that the list elements can easily be added or removed without };
reallocation or reorganization of the entire structure because the typedef struct node Node ;
data items need not be stored contiguously in memory or on disk. Node ∗ ptr1, ∗ ptr2;
• Linked lists allow insertion and removal of nodes at any point ptr1 = getnode ();
in the list. ptr2 = getnode ();
• Finding a node that contains a given data, or locating the place if((ptr1) && (ptr2))
where a new node should be inserted may require scanning most {
or all of the list elements. Printf(“No memory”);
• The list element does not have to occupy contiguous memory. exit(1);
• Adding, insertion or deletion of list elements can be accom- }
plished with the minimal disruption of neighbouring nodes. Ptr1 → ele = 10;
3.48 | Unit 3 • Programming and Data Structures

Ptr1 → next = ptr2; • Step 4 allocates memory


Ptr2 → ele = 20; • Step 5 read data
Ptr2 → next = NULL; • Steps from 6 to 9 adjust reference
Head = ptr1; • ‘if’ condition represents first insertion
the linked list appears as below
Insert in middle/random position of list
10 20 \ 1. void ins _ mid (int n, int pos)
2. {
Head int i = 1;
3. Node ∗ temp, N, P; //N,P represent
Operations on SLL (single-linked list) previous //& next nodes
• Insert at Head 4. if (Head = = NULL)
• Insert at Tail 5. {
• Insert in Middle 6. ins _ head(n);
• Delete Head 7. return;
• Delete Tail 8. }
• Delete Middle 9. temp = (Node ∗) malloc(sizeof(Node));
• Search 10. temp → ele = n;
• Display 11. P = head;
Declare two special pointers called head and tail as follows: 12. while (i < pos -1)
Node ∗Head, ∗Tail; 13. {
Head = Tail = NULL; P = P → next;
Head or tail is NULL represents list is empty. i++;
Steps for Insertion: }
14. N = P → next;
1. Allocate memory 15. temp → next = N;
2. Read data 16. P → next = temp;
3. Adjust references 17. }
• step 4 checks, whether the insertion is into an empty
Insert head element
list.
1. void ins _ Head (int x)
• If list is empty, invokes ins–head( ) function.
2. {
• If list is not empty, then step 9 allocates memory.
3. Node ∗temp;
• Step 10 reads data.
4. temp = (Node ∗) malloc(sizeof (Node));
• Steps from 11 to 14 make the reference to the previ-
5. temp → ele = x;
ous and next nodes of new node to be inserted.
6. temp → next = Head;
• Steps 15 and 16 create the reference to new node
7. Head = temp;
from previous node and from new node to next node.
8. if (Tail = = NULL)
9. Tail = Head; Example 1: Head = Tail = NULL
10 } n = 5, P = NULL;
• Step 4 allocates memory Here the list is empty. So,
• Step 5 read data
Head
• Steps from 6 to 9 adjust reference 5
Tail
• ‘if’ condition represents first insertion

Insert tail element Example 2:


1. void ins_tail (int x)
2. { Head 5 10 15 Tail
3. Node ∗temp;
4. temp = (Node ∗) malloc (sizeof (Node)); Insert element (n) 20 at position(pos) 3.
5. temp → ele = x; In current list, element 5 is the first element, 10 is the sec-
6. temp → next = NULL; ond and 15 is the third element.
7. Tail = temp; To insert an element at pos = 3, the new node has to be
8. if (Head = = NULL) placed between elements 10 and 15.
9. Head = Tail; Condition in step 4 is false so step 9 executes and allocates
10. } memory.
Chapter 4 • Linked Lists, Stacks and Queues | 3.49

temp 5. {
6. printf("List empty");
7. return;
On completion of step 10 – 8. }
temp 9. x = Head → ele;
10. temp = Head;
20 11. if (Head = = Tail)
12. Head = Tail = NULL;
Step 11
13. else
Head
10 15 Tail
14. Head = Head → next;
5
15. printf ("Deleted element "%d", x);
p
16. free(temp);
Step 12, 13 17. }
While (i < pos – 1) Step 4 – Checks for list empty
{ Step 9 – Reads element to delete
P = P → next; Step 10 – Head referred by temp pointer
i++; Step 11 – Checks for last deletion
} Step 14 – Moves the head pointer to next
i < pos element in the list
1 < 2 Step 15 – Displays element to delete
Condition true, so Step 16 – Deallocates memory
Head
5 10 15 Delete tail element
p 1. void del _ tail()
2. {
i becomes 2, 3. int x;
2 < 2 // condition false 4. Node ∗ temp;
Step 14 makes a reference to next of previous element. 5. if (Head = = NULL)
p Tail 6. {
Head 7. printf("\n list empty")
5 10 15
N 8. return ;
9. }
Steps 15 and 16 execute as follows: 10. temp = Head;
p Step 16 N 11. while(temp → next ! = Tail)
Head
5 10 15 12. temp = temp → next;
13. x = Tail → ele;
Step 16 Tail
14. Tail = temp;
20 15. temp = temp → next;
Step 15
temp 16. Tail → next = NULL;
17. printf("\n Deleted element : %d", x)
Now the element 20 becomes the 3rd element in the list.
18. free (temp);
19. }
Deletion Step 4 – Checks for list empty
• Identify the node Step 10, 11, 12 – Move the temp pointer to last but one
• Adjust the links, such that deallocation of that node does node of the list
not make the list as unconnected components. Step 13 – Reads tail element to delete
• Return/display element to delete. Step 14 – Moves tail pointer to last but one
• Deallocate memory. node
Step 15 – Moves the temp pointer to last node
Delete head element of the list
1. void del _ head() Step 16 – Removes the reference from tail node
2. { to temp node, i.e., tail node becomes
3. int x; the last element
Node ∗ temp; Step 17 – Displays elements to delete
4. if (Head = = NULL) Step 18 – Deallocate memory
3.50 | Unit 3 • Programming and Data Structures

Delete middle element {


1. void del _ mid (int pos) Node ptr;
2. { ptr = (Node ∗) malloc (size of (struct node)):
3. int i = 1, x; return (ptr);
4. Node ∗ temp P, N; }
5. if(Head = = NULL) If ptr returns NULL, then it is underflow (there is no avail-
6. { able memory) otherwise, it returns start address of memory
7. printf ("\n list empty") location.
8. return;
Search an element
9. }
1. void search (int x)
10. P = head;
2. {
11. while (i < pos -1)
3. Node ∗ temp = head;
12. {
4. int c = 1;
P = P → next;
5. while (temp! = NULL)
i++ ;
6. {
}
7. if (temp → ele = = x)
13. temp = P → next;
8. {
14. N = temp → next;
9. printf("\n Element found at % d”, c);
15. P → next = N;
10. break;
16. x = temp → ele;
11. }
17. printf("\n Element to Delete %d", x);
12. c++;
18. free(temp);
13. }
19. } 14. if (temp = = NULL)
Step 5 – Checks for empty list 15. printf("\n search unsuccessful");
Step 10, 11, 12 – Move previous pointer P to previous 16. }
node of node to delete. Step 7 – Checks temp data with search element.
Step 13 – Temp points to node to delete Repeats this step until the element is
Step 14 – N points to temp next found or reaches the last node
Step 15 – Creates link from P to N Step 9 – Displays the position of search element
Steps 16, 17, 18 – Read and display elements to delete in the list, if found
and deallocate memory. Step 14, 15 – Represents search element not exists in
list
A B C
Display
Node Node.next Node.next.next 1. void display ( )
2. {
3. Node ∗temp = Head;
A B C 4. printf("\n list elements: ");
5. while (temp ! = NULL)
Node Node.next Node.next.next
6. {
7. printf("%d", temp → ele);
Linked list using dynamic variables 8. temp = temp → next;
9. }
Node in the linked list contains data part that is ele and link
10. }
part which points to the next node, and some other external
Step 7 – Displays temp data
pointer will be pointing to this as these take some storage,
Step 8 – Moves temp pointer to next node
a programmer when creating a list, should check with the
available storage. For this we make use of get node () Algorithm to reverse direction of all links of
Function which is defined as follows:
struct node singly liked list
{ Consider a linked list ‘L’ with head as pointer pointing
int ele to the first node contains data element ‘ele’ and a pointer
struct node ∗ next ; called ‘next’ which points to the next node.
}; Reverse is the routine which will reverse the list, there
typedef struct node Node; are three node pointers P, Q, R with P pointing to the first
Node getnode () node, Q pointing to NULL.
Chapter 4 • Linked Lists, Stacks and Queues | 3.51

1. START Stack
2. if (P = NULL)
A stack is a last in first out (LIFO) abstract data type and data
1. print (“List is null”);
2. Exit structure. A stack can have any abstract data type as an ele-
3. While (P) ment, but is characterized by only two fundamental operations.
4. R = Q; √ PUSH
5. Q = P; √ POP
6. P = P → next; • The PUSH operation adds an item to the top of the stack,
7. Q → next = R hiding any items already on the stack or initializing the
8. End While stack if it is empty.
9. Head = Q; • The POP operation removes an item from the top of the
10. STOP
stack, and returns the poped value to the caller.
• Elements are removed from the stack in the reverse order to
Double-linked List (DLL)
the order of their insertion. Therefore, the lower elements
Double-linked list is a linked list in which, each node con- are those that have been on the stack for longest period.
tains data part and two link fields.
Node structure:
struct Dnode PUSH POP
{
struct Dnode ∗prev;
int ele;
struct Dnode ∗next;
};
• prev – points to previous node in list
• next – points to next node in list Figure 1 Simple representation of a stack
• The operations which can be performed in SLL can also
be preformed on DLL. Implementation
• The major difference is that we have to adjust double ref- A stack can be easily implemented either through an array
erence as compared to SLL. or a linked list. The user is only allowed to POP or PUSH
• We can traverse or display the list elements in forward as items onto the array (or) linked list.
well as in reverse direction.
1. Array Implementation: Array implementation aims
Example: to create an array where the first element inserted is
Tail placed st[0] which will be deleted last.
Head
A B C The program must keep track of position top (last)
element of stack.
Circular-linked List (CLL) Operations
Initially Top = –1;//represents stack empty
Circular-linked list is completely same as SLL, except, in
(i) Push (S, N, TOP, x)
CLL the last (Tail) node points to first (Head) node of list.
{
So, the Insertion and Deletion operation at Head and Tail
if (TOP = = N – 1)
are little different from SLL.
printf(“overflow”);
else
Double Circular-linked List (DCL)
TOP = TOP + 1;
Double circular-linked list can be traversed in both direc- S[TOP] = x;
tions again and again. DCL is very similar to DLL, except }
the last node’s next pointer points to first node of list and (ii) POP (S, N, TOP, x)
first node’s previous pointer points to last node of list. {
So, the insertion and deletion operations at head and tail if (TOP = = –1)
in DCL are little different in adjusting the reference as com- printf(“underflow”);
pared to DLL. else
Storing ordered table as linked list: The table is stored as x = S[TOP]
a linked list, it is retrieved and stored with two pointers, one TOP = TOP – 1
pointer will point to node holding a record having the smallest return x;
key and other pointer performs the search. }
3.52 | Unit 3 • Programming and Data Structures

2. Dynamic Implementation: The Array implementa- Steps:


tion is also called static implementation, because the
1. ptr = getNode (Node)
stack size is fixed.
2. ptr.data = item
The stack implementation using linked list is called
3. ptr.next = NULL
dynamic implementation, because the stack size can
4. if (front = NULL)
grow and shrink as the elements added or removed
front = ptr
from the stack.
else
• The PUSH operation on stack is same as insert
rear.next = ptr;
head in SLL.
5. end if
• The POP operation is same as delete head in SLL.
6. rear = ptr
Algorithm to add and delete to a link stack and link 7. Stop
queue For deletion of elements from queue that is ptr dequeue ()
Link stack: is given below
Steps:
data 1 data 2
1. if (front = NULL)
1. print “underflow”.
head Top data1 2. exit
2. ptr = front;
The linked stack with head and top pointers is shown 3. front = ptr.next
above 4. Head.next = front
The algorithm to push the elements into stack is given 5. item = ptr.data
below, the method push (item) 6. free(ptr)
Steps: 7. end.

1. ptr = getnode (Node) USES OF STACK


2. ptr.data = item
3. ptr.next = Top
• Function calls: When a function is called all local storage
4. Top = new
for the function is allocated on system ‘stack’, and return
5. Head.next = Top
address also pushed on to system stack.
6. Stop.
• Recursion stacks can be used to implement recursion if
the programming language does not provide recursion
for deletion of elements from stack, its algorithm is pop(), facility.
it is given below • Reversing a list
Steps: • Parsing: Stacks are used by compilers to check the syntax
of program.
1. if (Top = NULL)
• For evaluating expressions.
1. print “stack is empty”
2. exit Expression Notations
2. Else
Infix expression: Here binary operator comes between the
1. ptr = Top.next
operands.
2. item = Top.data
3. Head.next = ptr Postfix expression: Here the binary operator comes after
4. Top = ptr both the operands.
3. End if Example: ab+
4. Stop. Prefix expression: Here the binary operator comes before
Linked queue representation both the operands.
Example: +ab
data1 next data2 datan
Infix to postfix conversion
head front rear • If operand, output to postfix expression
• If operator, push it onto stack
The linked queue with head, front and rear point is shown • In case of parenthesis, when an opening parenthesis is
above. read, it is pushed onto stack and when a closing parenthe-
The algorithm to enqueue the elements into queue is sis is read, all operators up to the first opening parenthesis
given below, the method enqueue (item) must be popped from the stack into the post fix notation.
Chapter 4 • Linked Lists, Stacks and Queues | 3.53

Example: (A + (B – C))*D Algorithm for push A(x)


Initially A[Max], top A = –1, top B = MAX;
i/p Postfix notation Stack
( ( 1. if (top A = top B)
A A ( a. print “ overflow”
+ A (+ b. exit
( A (+( 2. top A = top A + 1
B AB (+( 3. A[top A] = x
- AB (+(–
4. stop
C ABC (+(–
Algorithm for pop A(x)
) ABC– (+
) ABC–+ - 1. if (top A = – 1)
∗ ABC–+ ∗
a. print “underflow”
b. exit
D ABC–+D ∗
2. y = A[top A]
ABC–+D∗
3. top A = top A – 1
4. return y
Evaluation of postfix expression
5. stop
We use operand stack for evaluation. Scan the post fix
expression, Algorithm for push B(x)
• When an operand encounters while scanning, push on to
stack. 1. if (top B – 1 = top A)
• While scanning post fix expression, if operator found then a. print “overflow”
• Pop top two operands from stack b. exit
• Perform the operation on those two operands 2. top B = top B –1
• Push, result on to stack top 3. A[top B] = x
• Finally, the stack contains only one value, which repre- 4. stop
sents result of the expression.
Algorithm for pop B(x)
Example: 6 2 3 + – 3 8 2 / + 2 3 +
1. if (top B = max)
Symbol OP1 OP2 Value Operand stack
a. print “underflow”
6 6
b. exit
2 6, 2
2. y = A [top B]
3 6, 2, 3
3. top B = top B – 1
+ 2 3 5 6,5 4. return y
- 6 5 1 5. stop
3 1, 3
8 1, 3, 8
2 1, 3, 8, 2 QUEUE
/ 8 2 4 1, 3, 4 A queue is an ordered collection of items from which items
+ 3 4 7 1, 7 may be deleted at one end (called that front of queue) and
∗ 1 7 7 7 into which items may be inserted at the other end (called
2 7, 2 rear of queue).
∗ 7 2 14 14 Queue is a linear data structure maintains the data in first
3 14, 3
in−first out (FIFO) order.
+ 14 3 17
Result is 17. Implementation
Queue can be implemented in the following ways:
Performing add, delete operations on stack
(multiple stack) 1. Array static implementation: queue cannot be extended
beyond the array size.
Let us consider an array whose size is ‘max’
2. Linked list dynamic implementation: Queue size
with multiple stack A, B having top A and top B, push and
increases as the elements added/inserted to queue.
pop operations on one stack A is given below.
Queue shrinks when an element deleted from
queue.
3.54 | Unit 3 • Programming and Data Structures

Array Implementation 6. printf(“Queue Empty”);


const int SIZE = 10; 7. return;
int q[SIZE]; 8. }
int f = –1, r = –1; //f = r = –1 represents queue empty 9. printf (“\n Queue Elemetns”);
10. for(; i < = r; i++)
Front Rear 11. printf(“ %d”, q[i]);
12. }
Step 4 – Checks for ‘q’ empty
Insertion
Step 10 and 11 – Display ‘q’ elements
1. void insert (int x)
2. {
3. if (r = = SIZE –1) Double-ended Queue
4. { A double-ended queue (deque) is an abstract data structure
5. printf(“Q FULL”) that implements a queue for which elements can only be
6. return; added to or removed from the front (head) (or) rear (tail)
7. } end.
8. r++; Rear Rear
9. q[r] = x;
10. if (f = = –1) Front
11. f = r;
12. } Insertions and deletions are possible at both ends.
Step 3 – Checks for queue full
Step 8 – Increments rear (r) Linked List Implementation
Step 9 – Inserts ‘x’ into queue Double-ended Queue
Step 10 – Checks whether insertion is first • Insert – Front is same as insert – Head
Step 11 – If first insertion, updates front (f) • Insert – Rear is same as insert – Tail
Deletion • Delete front is same as delete – Head
1. void deletion() • Delete – Rear is same as delete – Tail
2. {
3. int x; Circular Queue
4. if (f = = –1)
As the items from a queue get deleted, the space for that
5. {
item is reclaimed. Those queue positions continue to be
6. if (“\n Q Empty”);
empty. This problem is solved by circular queues. Instead
7. return;
of using a linear approach, a circular queue takes a circu-
8. }
lar approach; this is why a circular queue does not have a
9. x = q[f];
beginning or end.
10. if (f = = r)
11. f = r = –1; 1
0 2
12. else
13. f++; 3
14. printf(“\n deleted element %d”, x); 9
15. } 4
Step 4 – Checks for queue empty 8
Step 9 – Deletes ‘q’ front element 5
Step 10 – Checks whether queue having only one element 7 6
Step 11 – Rear and front initializes to –1, if queue is having
only one element The advantage of using circular queue over linear queue is
Step 13 – Queue front points to next element efficient usage of memory.
Step 14 – Deleted element is printed Algorithm to implement addition and deletion from
Display circular queue
1. void display( ) Circular Queue Insertion:
2. { To add an element ‘X’ to a Queue ‘Q’ of size ‘N’ with front
3. int i = f; and rear pointers as ‘F’ and ‘R’ is done with insert (X),
4. if (f = = –1) Initially F = R = 0.
5. { Insert (X)
Chapter 4 • Linked Lists, Stacks and Queues | 3.55

Steps: Priority Queue


1. if (((R = N ) & & (F = 1)) or ((R + In priority queue, the intrinsic ordering of elements does
1) = F)) determine the results of its basic operations.
a. print “overflow” There are two types of priority queues.
b. exit
• Ascending priority queue is a collection of items in which
2. if (R = N)
items can be inserted arbitrarily and from which only the
then R = 0;
smallest items can be removed.
Else
• Descending priority queue is similar but allows deletion
R = R + 1;
of the largest item.
3. Q[R] = x;
4. if (F = 0) Array Implementation
F = 1
• The insertion operation on priority queue selects the posi-
5. Stop.
tion to the element to insert.
To delete an element we implement an algorithm delete ().
• Makes the position empty/free by moving the existing
‘y’ contains the deleted element.
element (if required).
delete() • Place the element in required position.
Steps: • Deletion operation simply deletes front of queue.
1. if (F = 0)
a. print “underflow” Linked-list Implementation
b. exit
• Insertion operation create a node
2. y = Q[F]
• Reads element into node
3. if (F = R)
• Find out the location
F = R = 0
• Insert the node into list, by adjusting the reference
else
• Deletion operation simply deletes head elements, making
If (F = N)
the head next as head element
F = 1
Else Linked-list Implementation of Priority
F = F + 1
4. Return y
Queue
5. Stop. • Insertion in queue is same as insert-tail of queue
• Deletion from queue is same as delete head
EXERCISES

Practice Problems 1 PUSH(D); POP; POP;


Directions for questions 1 to 16: Select the correct alterna- PUSH(E)
tive from the given choices. PUSH(F)
POP
1. If the array representation of a circular queue contains
(A) ABE (B) AE
only one element then
(C) A (D) ABCE
(A) front = rear (B) front = rear + 1
(C) front = rear − 1 (D) front = rear = NULL
4. Consider the below code, which deletes a node from
2. The five items P, Q, R, S and T are pushed in a stack, the beginning of a list:
one after another starting from P. The stack is popped void deletefront()
four times, and each element is inserted in a queue. The {
two elements are deleted from the queue and pushed if(head = = NULL)
back on the stack. Now one item is popped from the return;
stack. The popped item is _____. else
(A) P (B) Q {
(C) R (D) S ..........
3. What are the contents of the stack (initially the stack is .........
empty) after the following operations? .........
PUSH (A) }
PUSH (B) }
PUSH (C) Which lines will correctly implement else part of above
POP code?
3.56 | Unit 3 • Programming and Data Structures

(A) if (head → next = = NULL) next → n = head;


head = head → next; temp → n = NULL;
(B) if (head = = tail) 7. Which of the following program segment correctly
head = tail = NULL; inserts an element at the front of the linked list. Assume
else that Node represents linked list node structure, value is
head = head → next; the element to be inserted.
(C) if (head = = tail = = NULL) (A) temp = (Node ‫)٭‬malloc (sizeof (Node));
head = head → next; temp → data = value;
(D) head = head → next; temp → next = head;
5. When a new element is inserted in the middle of head = temp;
linked list, then the references of _____ to be adjusted/ (B) temp = (Node ‫)٭‬malloc(sizeof (Node‫)٭‬
updated. );
(A) those nodes that appear after the new node temp → data = value;
(B) those nodes that appear before the new node temp → next = head;
(C) head and tail nodes head = temp;
(D) those nodes that appear just before and after the (C) temp = (Node ‫)٭‬malloc (sizeof (Node));
new node head = temp;
6. The following C function takes double-linked list as an temp → next = head;
argument. It modifies the list by moving the head (first) temp → data = value;
element to tail of the list. (D) temp = (Node ‫)٭‬malloc (sizeof (Node
typedef struct node ‫;)٭‬
{ temp → data = value;
struct node *p; head = temp;
int data; temp → next = head;
struct node *n; 8. Consider the following program segment:
} Node; struct element
Node ⃰ Move – to – last (Node *head) {
{ int x;
Node ⃰ temp, ⃰ prev, ⃰ next; struct element ⃰link;
if (head = = NULL)||(head → n = = NULL)) }
return head; void shuffle(struct element ⃰head)
temp = head; {
prev = head; struct ⃰p, ⃰q;
head = head → n; int t;
while (prev → n! = NULL) if (!head || !head → link) return;
{ p= head ; q = head → link;
X; while(q)
} {
Y; t = p → x;
return head; p→ x = q → x;
} q → x = t;
(A) X: prev = prev → n; p = q → link;
Y: prev → n = temp; q = p? p : 0;
temp → p = prev; }
temp → n = NULL; }
head → P = NULL;
The function called with list containing 10, 15, 20, 25,
(B) X: next = prev → n;
30, 35, 40 in given order. What will the order of ele-
Y: prev → n = temp;
ments of the list, after executing the function shuffle?
temp → p = prev;
(A) 10 15 20 25 30 35 40
(C) X: prev = prev → n;
(B) 40 35 30 25 20 15 10
Y: prev → n = temp;
(C) 20 15 10 25 40 35 30
temp → n = NULL;
(D) 15 10 25 20 35 30 40
head → p = NULL;
(D) X: next = prev → n; 9. Primary ADT’s are
prev = prev → n; (A) Linked list only (B) Stack only
Y: prev → n = Next; (C) Queue only (D) All of these
Chapter 4 • Linked Lists, Stacks and Queues | 3.57

10. Linked list uses NULL pointers to signal (C) Both (A) and (B)
(A) end of list (B) start of list (D) None of these
(C) Either (A) or (B) (D) Neither (A) nor (B) 14. Linked list are not suitable for implementing
11. Which of the following is essential for converting an (A) Insertion sort
infix to postfix form efficiently? (B) Binary search
(A) Operator stack (B) Operand stack (C) Radix sort
(C) Both (A) and (B) (D) Parse tree (D) Polynomial manipulation
12. Stacks cannot be used to 15. Insertion of node in a double-linked list requires how
(A) Evaluate postfix expression many changes to previous (prev) and next pointers?
(B) Implement recursion (A) No changes (B) 2 next and 2 prev
(C) Convert infix to postfix (C) 1 next and 1 prev (D) 3 next and 3 prev
(D) Allocate resource like CPU by the operating system 16. Minimum number of stacks required to implement a
13. Linked list can be sorted queue is
(A) By swapping data only (A) 1 (B) 2
(B) By swapping address only (C) 3 (D) 4

Practice Problems 2 (A) Simple queue (B) Circular queue


Directions for questions 1 to 11: Select the correct alterna- (C) Stack (D) None of these
tive from the given choices. 7. In a circular linked list, insertion of a record involves
1. Stack is useful for implementing _____. the modification of _____.
(A) radix sort (A) no pointer (B) four pointers
(B) breadth first search (C) two pointers (D) All of the above
(C) quick sort 8. Among the following, which one is not the right opera-
(D) recursion tion on a stack?
2. Which is true about linked list? (A) Remove the item that is inserted latest into the
(A) A linked list is a dynamic data structure. stack.
(B) A linked list is a static structure. (B) Add an item to the stack.
(C) A stack cannot be implemented by a linear linked list. (C) Remove the first item that is inserted into the
(D) None of the above stack, without deleting other elements.
(D) None of the above
3. The process of accessing the data stored in a tape is
similar to manipulating data on a _____. 9. Among the following which one is not the right opera-
(A) stack (B) list tion on dequeue?
(C) queue (D) heap (A) Inserting an element in the middle of a dequeue.
(B) Inserting an element at the front of a dequeue.
4. Which of the following is used to aid in evaluating a
(C) Inserting an element at the rear of a dequeue.
prefix expression?
(D) None of the above
(A) Queue (B) Heap
(C) Stack (D) Hash 10. A linear list in which elements can be added or removed
5. Select the statement which best completes the sentence at either end but not in the middle is _____.
 ‘Abstract data type is…’ (A) queue
(A) a data type which is abstract in nature (B) dequeue
(B) a kind of data type (C) array
(C) data structure (D) tree
(D) a mathematical model together with a set of opera- 11. The post fix notation of A/B ∗ ∗ C + D ∗ E – A ∗ C is
tions defined on it (A) ABC * * /DE * + AC * –
6. Which of the following data structures may give an (B) ABC * * D/E * + AC + –
overflow error, even through the current number of ele- (C) ABC ∗ ∗ /DE ∗ AC + –
ments in it is less than its size? (D) ABC ∗ ∗ /DE ∗ + AC + –
3.58 | Unit 3 • Programming and Data Structures

PREVIOUS YEARS’ QUESTIONS


1. An abstract data type (ADT) is [2005] int temp;
(A) same as an abstract class. if (!list || !list -> next) return;
(B) a data type that cannot be instantiated. p = list; q = list -> next;
(C) a data type for which only the operations defined while (q) {
on it can be used, but none else. temp = p -> value; p -> value = q ->
(D) All of the above value;
q -> value = temp; p = q → next;
2. An implementation of a queue Q, using two stacks S1 q = p?p -> next : 0;
and S2, is given below: }
void insert (Q, x) { }
push (S1, x); [2008]
} (A) 1, 2, 3, 4, 5, 6, 7 (B) 2, 1, 4, 3, 6, 5, 7
void delete (Q) { (C) 1, 3, 2, 5, 4, 7, 6 (D) 2, 3, 4, 5, 6, 7, 1
if (stack-empty (S2)) then
5. Suppose a circular queue of capacity (n – 1) elements
if (stack-empty (S1)) then {
is implemented with an array of n elements. Assume
print (“Q is empty”);
that the insertion and deletion operations are carried
return;
out using REAR and FRONT as array index vari-
}
ables, respectively. Initially, REAR = FRONT = 0.
else while(!(stack-empty(S1)))
The conditions to detect queue full and queue empty
{
are [2012]
x = pop (S1);
(A) Full: (REAR + 1) mod n = = FRONT
push(S2, x);
Empty: REAR = = FRONT
}
(B) Full: (REAR + 1) mod n = = FRONT
x = pop (S2);
Empty: (FRONT + 1) mod n = = REAR
}
(C) Full: REAR = = FRONT
Let n insert and m (≤ n) delete operations be per-
Empty: (REAR + 1) mod n = = FRONT
formed in an arbitrary order on an empty queue Q.
(D) Full: (FRONT + 1) mod n = = REAR
Let x and y be the number of push and pop operations
Empty: REAR = = FRONT
performed respectively in the process. Which one of
the following is true for all m and n? [2006] 6. Consider the C program below [2015]
(A) n + m ≤ x < 2n and 2m ≤ y n + m #include <stdio.h>
(B) n + m ≤ x < 2n and 2m ≤ y 2n int *A, stkTop;
(C) 2m ≤ x < 2n and 2m ≤ y n + m int stkFunc (int opcode, int val)
(D) 2m ≤ x < 2n and 2m ≤ y 2n {
static int size=0, stkTop=0;
3. The following postfix expression with single digit
switch (opcode) {
operands is evaluated using a stack:
case -1: size = val; break;
8 2 3∧ / 2 3 ∗ + 5 1 ∗ –
case 0: if (stkTop < size)
Note that ∧ is the exponentiation operator. The top
A[stkTop++] =
two elements of the stack after the first ∗ is evaluated
val; break;
are: [2007]
default: if (stkTop) return A[-
(A) 6 and 1 (B) 5 and 7
-stkTop];
(C) 3 and 2 (D) 1 and 5
}
4. The following C function takes a single-linked list of return -1;
integers as a parameter and rearranges the elements of }
the list. The function is called with the list containing int main ( )
the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What {
will be the contents of the list after the function com- int B[20]; A = B; stkTop = -1;
pletes execution? stkFunc (-1, 10);
struct node { stkFunc (0, 5);
int value; stkFunc (0, 10);
struct node *next; printf (“%d\n”, stkFunc(1, 0) +
}; stkFunc(1, 0));
void rearrange (struct node *list) { }
struct node *p, *q; The value printed by the above program is _____
Chapter 4 • Linked Lists, Stacks and Queues | 3.59

7. The result of evaluating the postfix expression 10 5 + 9. The attributes of three arithmetic operators in some
60 6/* 8 – is [2015] programming language are given below.
(A) 284 (B) 213
Operator Precedence Associativity Arity
(C) 142 (D) 71
8. Let Q denote a queue containing sixteen numbers and + High Left Binary
S be an empty stack. – Medium Right Binary
Head (Q) returns the element at the head of the queue * Low Left Binary
Q without removing it from Q. Similarly Top(S) The value of the expression
returns the element at the top of S without removing
2 – 5 + 1 – 7 * 3 in this language is ______. [2016]
it from S.
10. A circular queue has been implemented using a sin-
Consider the algorithm given below.
gly linked list where each node consists of a value
and a single pointer pointing to the next node. We
while Q is not Empty do maintain exactly two external pointers FRONT and
if S is Empty OR Top(S) ≤ Head (Q) REAR pointing to the front node and the rear node of
then the queue, respectively. Which of the following state-
x : = Dequeue (Q) ments is/are CORRECT for such a circular queue,
Push (S, x); so that insertion and deletion operations can be per-
else formed in O (1) time?
x : = Pop (S); I. Next pointer of front node points to the rear
enqueue (Q, x); node.
end II. Next pointer of rear node points to the front
end node.
[2017]
The maximum possible number of iterations of the (A) I only (B) II only
while loop in the algorithm is ____ . [2016] (C) Both I and II (D) Neither I nor II

ANSWER KEYS
EXERCISES
Practice Problems 1
1. A 2. C 3. B 4. B 5. D 6. A 7. A 8. D 9. D 10. A
11. A 12. D 13. C 14. B 15. B 16. B

Practice Problems 2
1. D 2. A 3. C 4. C 5. D 6. A 7. C 8. C 9. A 10. B
11. A

Previous Years’ Questions


1. C 2. A 3. A 4. B 5. 6. 15 7. C 8. 256 9. 9 10. B
Chapter 5
Trees

LEARNING OBJECTIVES

 Tree  Binary search tree


 2-Tree  Binary tree traversing methods
 Binary tree  AVL tree
 Properties of binary trees  Binary heap
 Complete binary tree  Max-heap
 Full binary tree  Min-heap
 Binary tree representation  Expression tree
 Linked representation

TREE • B is parent of E and C is parent of F.


• Number of children of a node is called degree of node.
Tree is non-linear data structure designated at a special node called
root and elements are arranged in levels without containing cycles.
(or)
2-TREE
A tree in which every node contains either 0 or 2 children.
The tree is
1. Rooted at one vertex BINARY TREE
2. Contains no cycles
3. There is a sequence of edges from any vertex to any other It is a special type of tree where each node of tree contains either
4. Any number of elements may connect to any node (including 0 or 1 or 2 children.
root) (or)
5. A unique path traverses from root to any node of tree Binary Tree is either empty, or it consists of a root with two binary
6. Tree stores data in hierarchical manner trees called left-sub tree and right sub-tree of root (left or right or
7. The elements are arranged in layers both the sub trees may be empty).
Example:
Properties of binary tree
• Binary tree partitioned into three parts.
A
• First subset contains root of tree.
• Second subset is called left subtree.
B C D
• Another subset is called right subtree.
• Each subtree is a binary tree.
E F
• Degree of any node is 0/1/2.
• The maximum number of nodes in a tree with height ‘h’ is
• Root node is A. 2h+1 -1.
• A’s children are B, C and D. • The maximum number of nodes at level ‘i’ is 2i-1.
• E, F and D are leaves. • For any non-empty binary tree, the number of terminal nodes
• Nodes B, C are called as intermediate nodes. with n2, nodes of degree 2 is N0 = n2 + 1
• A is parent of B, C and D. • The maximum number of nodes in a tree with depth d is 2d - 1.
Chapter 5 • Trees | 3. 61

Types of binary tree Application


• A binary tree is useful data structure when two way deci-
Complete binary tree It is a binary tree, in which at every sions must be made at each point of process.
level, except possibly the last, is completely filled and all
nodes at the last level are as left as possible.
Example:
Binary tree representation
The binary trees can be represented in two ways.
Level Height Depth
• Array
1 3 1 • Linked list
2 2 2
3 1 3 Array representation The elements of a binary tree are
placed in an array using the level order index of each
4 0 4
element.
1
i
A
2
B
4 3 2i + 1 2i + 2
D 5
E C
6 7
8 9
H I 10 G
F When LOI of Root is 0:
J
Example 1:
For the given tree:
0
• Having 4 levels 1 A
• Height of the tree is 3 B
2
• Depth of the tree is 4 3 D
4 E C
• The numbers at each node represents level order index. 6
8 5
• The level order Index, are assigned to nodes in the fol- 7 H I G
F
lowing manner
• Root of the tree is ‘1’
• For a node ‘x’, the LOI is (2 * LOI (parent)), if ‘x’ is left 0 1 2 3 4 5 6 7 8
child of its parent. A B C D E F G H I
• For a node ‘y’, the LOI (2 * LOI (Parent) +1), if ‘y’ is
right child of its parent. Example 2:
Now complete binary tree can be defined as a binary tree, 0
which contains a sequence of numbers to its nodes as LOI’s A
without any break in sequence. 1 2
B C
Full binary tree It is a binary tree, for which all leaf nodes
are at same level and all intermediate nodes contains exactly 5 D
12
2 children. E
(or)
A tree with depth ‘K’ contains exactly 2K – 1 nodes.
0 1 2 3 4 5 6 7 8 9 10 11 12
Strictly binary tree A binary tree in which every node con-
A B C D E
tains exactly 0 or 2 children.
Skewed binary tree A binary tree in which elements are Linked representation Each node contains one data field
added only in one direction. and two link fields. Fist link point to the left child and
Example: another point to the right child.
In absence of any child, corresponding link field con-
A A tains NULL.
B B Example:

C C A A
B C
D D
B C
Left-skewed Right-skewed
3.62 | Unit 3 • Programming and Data Structures

Trade-off’s between array and linked, reach a node where the required subtree does not exist and
representations that is where we place the new value.
• Array representation is somewhat simpler. It must ensure Example: It must go in 6’s left subtree, 3’s left subtree, 1’s
elements are placed in array at proper position. right subtree, 1 has no right subtree, so we make a singleton
• Linked representation requires pointer to its left and right with 2 and it becomes 1’s right subtree.
child.
• Array representation saves memory for almost complete 6
binary trees.
• Linked representation allocates the number and nodes 3 9
equal to the number of elements in tree.
1 4 8 11
• Array representation does not work efficiently for skewed
binary trees.
2
• Array representation limits the size of binary tree to the
array size.
• In linked representation, tree can be extended by adding Deletion:
an element dynamically and can be shrinked by deleting 1. If a leaf node has to be deleted, just delete it and the
an element dynamically. rest of the tree is exactly as it was, so it is still a BST.
2. Suppose the node we are deleting has only one sub
Binary search tree tree
It is a special type of binary tree that satisfies the following Example, In the following tree, ‘3’ has only one
properties. sub-tree
• All the elements of left sub tree of root are smaller than 6
root.
3 9
• All the elements of right sub tree of root are greater than
root. 1 8 11
• The above two properties satisfy for each subtree.
Example: 0 2

6
To delete a node with 1 subtree, we just ‘link past’ the node,
i.e., connect the parent of the node directly to the node’s
3 9 only subtree. This always works, whether the one subtree is
on the left or on the right. Deleting 3 gives us.
1 4 8 11
6
Figure 1 A data structure to encode binary search tree
9
The binary search tree node contains three fields, data field, 1
8 11
left child, right child. Left child is a pointer which points
to the predecessor of the node and right child is a pointer 0 2
which points to the successor of the node.
A data structure to encode binary search tree is 3. Deletion of node which has 2 subtrees
Left child Data Right child Example: Delete 6.

The declaration is X
Struct node
3 9
{
Struct node * left child;
1 8 11
Int data;
Struct node * Right child; 0 2
};
Choose value ‘X’
Insertion If a value to be inserted is smaller than the root,
value, it must go in the left subtree, if larger it must go in 1. Everything in the left subtree must be smaller than X.
the right subtree. This reasoning applies recursively until we 2. Everything in the right subtree must be bigger than X.
Chapter 5 • Trees | 3. 63

We must choose X to be the largest value in the left subtree. Example 2:


In our example, 3 is the largest value in the left subtree. So
6
we replace root node 6 with 3. 3
1 9
4
3 2
8 11
9

1 Pre-order: 6 3 1 2 4 9 8 11
8 11
In-order: 1 2 3 4 6 8 9 11
0 2 Post-order: 2 1 4 3 8 11 9 6

Points to remember
Note: We could do the same thing with the right subtree.
Just use the smallest value in the right subtree. • Pre-order traversal contains root element as first element
in traverse list.
Notes: • Post-order traversal contains root element as last in tra-
• The largest element in left subtree is the right most versal list.
element. • For BST, in-order traversal is a sorted list.
• The smallest element in right subtree is the left most • A unique binary tree can constructed if either pre-order or
element. post-order traversal list provided with In order traversal
list.
• If either pre-order or post-order only given then BST can-
Binary tree traversing methods
not be constructed.
The binary tree contains 3 parts:
V – root Applications
L – Left subtree
1. Binary trees can represent arithmetic expressions.
R – Right subtree
• An infix expression will have a parent operator and
Pre-order: (V, L, R) two children operands.
• Visit root of the tree first Consider the expression ((3 + (7 * 2)) -1)
• Traverse the left - subtree in pre-order Each parenthesised expression becomes a tree.
• Traverse the right - subtree in preorder Each operand is a leaf, each operator is an internal node.
In-order: (L, V, R)
• Traverse the left – subtree in in-order −
• Visit Root of the tree
• Traverse right - sub tree in in-order + 1

Post-order: (L, R, V) 3 *
• Traverse the left subtree in post-order.
• Traverse the Right - subtree in post-order 7 2
• Visit root of the tree

Example 1: 2. To evaluate the expression tree:


Take any two leaves
A Apply the parents operator to them
B C Replace the operator with the value of the sub
expression.
D E G H

F I J
*
*
+ 3 18
Pre-order: A B D F E C G I H J
6 3
In-order: F D B E A G I C H J
Post-order: F D E B I G J H C A 2 4
Pre-order, In-order and post-order uniquely identify the tree.
3.64 | Unit 3 • Programming and Data Structures

3. Binary trees in a famous file compression algorithm Example 3:


Huffman coding tree +2 40
• Each character is stored in a leaf +1
0
• The code is found by following the path 0 go left, 1 20 45
go right. 0
+1
• a is 01 10 25
• e is 1
5
0
0 1 Not an AVL tree
‘e’ Example 3 is not an AVL tree, because the balance factor of
0 1 root node is +2.
‘t ’ ‘a’
AVL tree becomes height in-balanced tree in following
cases:
1. Left-Left case: An insertion in left subtree of left child
AVL Tree of pivot node.
An AVL tree is a self-balancing binary search tree, in which Example:
the heights of the two child subtrees of any node differ by
1 A
atmost one.
1 0
Insertions and deletions may require the tree to be rebal-
G B
anced by one or more tree rotations.
0
• The balance factor of a node is the height of its left subtree P
minus the height of its right subtree (sometimes opposite)
and a node with balance factor—1, 0 or -1 is considered Insert ‘X’ as left to node ‘P’. Here ‘G’ is pivot node.
balanced. A node with any other balance factor is consid- +2 A
ered unbalanced and requires rebalancing the tree.
+2 0
• The balance factor is either stored directly at each node or
G B
computed from the heights of the subtrees. +1
P
Insert operations 0
Step I: Insert a node into the AVL tree as it is inserted in a X
BST.
Step II: Examine the search path to see if there is a pivot Solution:
node. To make the tree as balanced tree, perform Left–Left
Rotation as follows:
Three cases may arise
Case I: There is no pivot node. No adjustment required. A +1
A
Case II: The pivot node exists and the subtree of the pivot 0
node to which the new node is added has smaller G B 0
P B
height. No adjustment required. 0
0
Case III: The pivot node exists and the subtree to which P X G
the new node is added has the larger height,
X
Adjustment required.
Example: The numbers at each node represents balance In left–left rotation
factor. • Intermediate node ‘P’ becomes root of subtree.
Example 1: Example 2: • Root of subtree ‘G’ (pivot) becomes right subtree.
• New node ‘X’ remains same as left child of ‘P’.
0 −1 Left–Right Case
20 20
An insertion of left subtree of right child of pivot node.
0 0
0 +1 1 A
10 30
10 30
AVL tree 1 0
G B
25 0
AVL tree P
Chapter 5 • Trees | 3. 65

Example 1: Insert ‘X’ as right child of ‘P’. −2 −1


A A

0 −2 0 0
+2 A
B G B P
0
+2 −1 0 0
G B P G X
−1 L 0
P X
R
0
X
In Right–Right rotation:
Is not an AVL tree. Height in-balance at node ‘G’. • Intermediate node ‘P’ becomes root of subtree.
• Root of subtree ‘G’ (pivot) becomes left child of ‘P’.
Solution:
• New node ‘X’ remains as right child to ‘P’.
Perform Left–Right Rotation, to balance the height of tree.
Right–Left case
A An insertion of right subtree of left child of pivot node.
−1
G B +1 A A
L
0 0 0 −1
P X B
R B G
0 0 0
X P P
G

Insert ‘X’ as left child of ‘P’


In Left–Right rotation:
• New node ‘X’ becomes root of subtree. −2
• Root of subtree ‘G’ (pivot) becomes right child of ‘X’. A
• Intermediate node ‘P’ becomes left child of new node. 0 −2
B G
Right–Right case +1
P
An insertion of right subtree of right child of pivot node.
Example: X 0

−1
A Is not AVL tree, because height in-balance at node ‘G’.
0 −1
Solution:
B G
0
To make the above tree as balanced, perform Right–Left
P rotation as follows:

−2 −1
Insert ‘X’ as right child of ‘P’ A A
0 −2 ⇒ 0
0
−2 B G R B X
A +1 0 0
0 −2 P G P
G L
B
R 0
−1
X
P
R
0
X In Right–Left Rotation:
• New node ‘X’ becomes root of subtree.
• Root of subtree ‘G’ (pivot) becomes left child of ‘X’.
Is not an AVL tree, because of height in-balance at node ‘G’. • Intermediate node ‘P’ becomes right of ‘X’.
Solution:
To make the tree as balanced tree, perform the right–right Note: Left–Right and Right–Left rotation are also called as
rotation as follows: double rotations.
3.66 | Unit 3 • Programming and Data Structures

BINARY HEAP Delete 15:


Interchange 4 and 15
A binary heap is a heap data structure created using a binary
tree. It can be seen as a binary tree with two additional
4
constraints.
The shape property: The tree is a complete binary tree; 8 11
that is, all levels of the tree, except possibly the last one
(deepest) level of the tree is not complete, the nodes of that 3 15
level are filled, from left to right.
Max-Heap
Now delete Node ‘15’
A heap in which each node is greater than or equal to its
children is called max-heap. Max-Heap generally used for
4
heap sort.
Min-Heap 8 11
A heap in which, each node is smaller than or equal to its
children is called Min-Heap. Min-heap generally used to 3
implement priority queue.
Note: By default heap represent Max-Heap: Is not satisfying heap property. So heapify
11
11
5 8
8 4
3 4
3
Insert 15:
11 Note: Insertion or deletion operation on a heap may require
heapify process.
5 8

3 4 15 Expression Tree
The expressions can also represented by using a binary tree
Is not satisfying heap property. So Heapify called expression tree.
Expression tree contains:
⇒ 11 ⇒ 15
• Operators as intermediate nodes.
5 15 5 11 • Operands as leaf nodes (or) childs to operator nodes.
• The operator at lowest level will be having highest
3 4 8 3 4 8 priority.

Delete 5: Deletion of a node from heap is always deletes a Example: A + B * C


leaf node.
So interchange the value of last leaf node with node 5. +
15
A *
8 11
B C
3 4 5

Now delete node ‘5’ Traversing:


Pre-order: + A * B C
15
In-order: A + B * C
8 11 Post-order: A B C * +

3 4 Note: In-order traversal of expression tree generates In-fix


expression. Similarly pre-order and post-order generates
Is satisfying heap property. prefix and postfix, respectively.
Chapter 5 • Trees | 3. 67

EXERCISES
Practice Problems 1 (A) {23, 17, 14, 6, 13, 10, 1, 12, 7, 5}
Directions for questions 1 to 15: Select the correct alterna- (B) {23, 17, 14, 6, 13, 10, 1, 5, 7, 12}
tive from the given choices. (C) {23, 17, 14, 7, 13, 10, 1, 5, 6, 12}
(D) {23, 17, 14, 7, 13, 10, 1, 12, 5, 6}
1. A binary tree T has n leaf nodes. The number of nodes
8. What is the maximum height of any AVL tree with 7
of degree two in T is ____.
nodes? Assume that the height of a tree with a single
(A) n (B) n - 1
node is 0.
(C) log n (D) n + 1
(A) 2 (B) 3
2. How many numbers of binary tree can be created with (C) 4 (D) 5
3 nodes which when traversed in post-order gives the
9. A binary search tree is generated by inserting in order
sequence C, B, A?
the following integers:
(A) 3 (B) 5
(C) 8 (D) 15 55, 15, 65, 5, 25, 59, 90, 2, 7, 35, 60, 23.
The number of nodes in the left subtree and right sub-
3. A binary search tree contains the values 3, 6, 10, 22,
tree of the root respectively are
25, 30, 60, 75. The tree is traversed in pre-order and the
(A) 8, 3 (B) 7, 4
values are printed out. Which of the following sequence
(C) 3, 8 (D) 4, 7
is a valid output?
(A) 25 6 3 10 22 60 30 75 10. In a complete binary tree of n nodes, how far are the
(B) 25 6 10 3 22 75 30 60 most distant two nodes? Assume each in the path
(C) 25 6 75 60 30 3 10 22 counts as 1.
(D) 75 30 60 22 10 3 6 25 (A) about log2 n (B) about 2log2 n
(C) about 3log2 n (D) about 4log2 (n)
4. Figure shows a balanced tree. How many nodes will
become unbalanced when a node is inserted as a child 11. A complete binary tree of level 5 has how many nodes?
of the node ‘g’? (A) 20 (B) 63
(C) 30 (D) 73
a Common data for questions 12 and 13: A 3-ary max-heap
b e is like a binary max-heap, but instead of 2 children, nodes
have 3 children. A 3-ary heap can be represented by an array
c d
f as follows:
g The root is stored in the first location, a[0], nodes in the
next level from left to right is stored from a[1] to a[3] and
so on. An item x can be inserted into a 3-ary heap containing
(A) 7 (B) 2 n items by placing x in the location a[n] and pushing it up
(C) 3 (D) 8 the tree to satisfy the heap property.
5. A full binary tree with n non-leaf nodes contains 12. Which one of the following is a valid sequence of ele-
(A) 2n nodes (B) log2 n node ments in an array representing 3-ary max-heap?
(C) n + 1 nodes (D) 2n + 1 nodes (A) 1, 3, 5, 6, 8, 9 (B) 9, 6, 3, 1, 8 , 5
6. Which of the following list of nodes corresponds to a (C) 9, 3, 6, 8, 5, 1 (D) 9, 5, 6, 8, 3, 1
post order traversal of the binary tree shown below? 13. Suppose the elements 7, 2, 10 and 4 are inserted, in that
order, into the valid 3-ary max-heap found in the above
A question. Which one of the following is the sequence of
C items in the array representing the resultant heap?
B
(A) 10, 7, 9, 8, 3, 1, 5, 2, 6, 4
D E F G
(B) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
H I J (C) 10, 9, 4, 5, 7, 6, 8, 2, 1, 3
(D) 10, 8, 6, 9, 7, 2, 3, 4, 1, 5
14. Consider the nested representation of binary trees : (X
(A) A B C D E F G H I J (B) J I H G F E D C B A Y Z) indicated Y and Z are the left and right subtrees
(C) D H E B I F J G C A (D) D E H F I G J B C A respectively, of node X(Y and Z may be null (or) further
7. Which of the following sequence of array elements nested) which of the following represents a valid binary
forms as heap? tree?
3.68 | Unit 3 • Programming and Data Structures

(A) (1 2 (4 5 6 7)) (B) (1(2 3 4)5 6)7 is stored in X[ 2i ] and the right child, if any, in X[2i +
(C) (1(2 3 4) (5 6 7)) (D) (1(2 3 NULL)(4 5)) 1]. To store any binary tree on ‘n’ vertices the minimum
15. A scheme for storing binary trees in an array X is as size of X should be
follows: (A) 2n (B) n
(C) 3n (D) n2
Indexing of X starts at 1 instead of 0. The root is stored
at X[ 1 ]. For a node stored at X[i], the left child, if any,

Practice Problems 2 8. A complete n-ary tree is one in which every node has 0
Directions for questions 1 to 15: Select the correct alternative or n children. If x is the number of internal nodes of a
from the given choices. complete n-ary tree, the number of leaves in it is given by
(A) x(n - 1) + 1
1. A binary search tree contains the values 1, 2, 3, 4, 5, (B) xn + 1
6, 7, 8. The tree is traversed in pre-order and the val- (C) xn - 1
ues are printed out. Which of the following is a valid (D) x(n + 1) - 1
output?
(A) 53124786 (B) 53126487 Common data for questions 9 and 10:
(C) 53241678 (D) 53124768 9. Insert the keys into a binary search tree in the order
specified 15, 32, 20, 9, 3, 25, 12, 1. Which one of the
2. A binary search tree is generated by inserting in order
following is the binary search tree after insertion of all
the following integers : 50, 15, 62, 5, 20, 58, 91, 3, 8,
elements?
37, 60, 24. The number of nodes in the left subtree and
right subtree of the root respectively are:
(A) 15
(A) (4, 7) (B) (7, 4)
(C) (8, 3) (D) (3, 8) 32
9

3 20
3. A full binary tree (with root at level 0) of height h has a 12
total number of nodes equal to: 25
1
(A) 2h (B) 2h+1 – 1
h
(C) 2 – 1 (D) 2h – 1 (B) 15

4. The number of null pointers of a binary tree of n nodes 12 32


is :
(A) n + 1 (B) n(n + 1) 9 20 25
(C) n2 (D) 2n
3
5. Which of the following is false?
(A) A tree with n nodes has (n – 1) edges. 1
(B) A labeled rooted binary tree can be uniquely con-
structed, given its post-order, in-order traversal results. (C) 15
(C) The complete binary tree with n internal nodes has
3 20
(n + 1) leaves.
(D) The maximum number of nodes in a binary tree of 25
12
height h is (2h+1 – 1).
3 32
6. The maximum number of nodes in a binary tree at level
i is 1
(A) 2i (B) 2i – 1
(C) 2i + 1 (D) log2 i + 1 (D) 15

7. The number of leaf nodes in a rooted tree of n nodes, 1 25


with each node having 0 or 3 children is 32
n ( n −1) 9
(A) (B)
3 3 20 32
12
( n −1) ( 2n + 1)
(C) (D) 3
2 3
Chapter 5 • Trees | 3. 69

10. Which of the following is the binary tree after deleting For questions 11, 12 and 13 below, use this figure
15?
(A) 9 A

3 32
B C
1 12 20

25
D
E F
20
(B)
32
9 G H I

3 25
12
11. What is the post-order expression?
(A) ABDGCEJHIF (B) GDBHIEFCA
1
(C) DGBAHEICF (D) ABHIEFCDG
12. What is the pre-order expression?
(C) 20
(A) ABDGCEHIF (B) ABHIEFCDG
9 25 (C) DGBAHEIFCF (D) GDBHIEFCA
13. What is the in-order expression?
3 12 32 (A) ABDGCEHIF (B) GDBHIEFCA
(C) DGBAHEICF (D) ABHIEFCDG
25 14. In a 3-ary tree every internal node has exactly 3 chil-
dren. The number of leaf nodes in such a tree with 6
(D) 20 internal nodes will be
(A) 13 (B) 12 (C) 11 (D) 10
9 25
15. Minimum number of swaps needed to convert the array
3 12 32
89, 19, 14, 40, 17, 12, 10, 2, 5, 7, 11, 6, 9, 70 into a max
heap
1 (A) 2 (B) 3 (C) 1 (D) 0

PREVIOUS YEARS’ QUESTIONS


1. In a binary tree with n nodes, every node has an odd q = NULL; p = head;
number of descendants. Every node is considered to while (p-> next !=NULL) {
be its own descendant. What is the number of nodes q = p;
in the tree that have exactly one child? [2010] p = p->next;
(A) 0 (B) 1 }
(C) (n − 1)/2 (D) n – 1

2. The following C function takes a singly-linked list as return head;


input argument. It modifies the list by moving the last }
element to the front of the list and returns the modi-
Choose the correct alternative to replace the blank
fied list. Some part of the code is left blank.
line. [2010]
typedef struct node { (A) q = NULL; p->next = head; head = p;
int value; (B) q->next = NULL; head = p; p->next =
struct node *next; head;
} Node; (C) head = p; p->next = q; q->next = NULL;
Node *move_to_front(Node *head) { (D) q->next = NULL; p->next = head; head
Node *p, *q; = p;
if ((head = = NULL || (head->next = = 3. Consider two binary operators ‘↑’ and ‘↓’ with the
NULL)) return head;
3.70 | Unit 3 • Programming and Data Structures

precedence of operator ↓ being lower than that of the int height(treeptr n)


operator ↑. Operator ↑ is right associative while opera- {if (n = = NULL) return –1;
tor ↓ is left associative. Which one of the following rep- if (n → left ==NULL)
resents the parse tree for expression (7 ↓ 3 ↑ 4 ↑ 3 ↓ 2)?
if (n → right == NULL) return 0;
[2011]
else return B1 ; //Box 1

(A) ↓ else {h1 = height (n → left);


if (n → right= = NULL) return (1 + h1);

7
else {h2 = height (n → right);
3 ↓ return B2 ; //Box 2
}
4
}

}
3 2 The appropriate expressions for the two boxes B1 and
B2 are [2012]
(B) ↓ (A) B1: (1 + height (n → right))
B2: (1 + max (h1, h2))
↓ 2 (B) B1: (height (n → right))
7 B2: (1+ max(h1, h2))

(C) B1: height (n → right)
3 B2: max(h1, h2)

(D) B1: (1 + height (n → right))
B2: max(h1, h2)
4 3
5. Consider the expression tree shown. Each leaf repre-
sents a numerical value, which can either be 0 or 1.
(C) ↓ Over all possible choices of the values at the leaves,
the maximum possible value of expression repre-
7 ↓
sented by the tree is ––––––––. [2014]
2

+
↓ 3
− +
4
3
+ − − +

(D) ↓
0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
↓ 2

3 6. Consider the pseudocode given below. The function


↓ Dosomething() takes as argument a pointer to the root
4
of an arbitrary tree represented by the leftMostChild-
rightSibling representation. Each node of the tree is of

type treenode. [2014]
3
7 type def struct treeNode* treeptr;
struct treeNode
4. The height of a tree is defined as the number of edges {
on the longest path in the tree. The function shown in
treeptr leftMostChild, rightSibling;
the pseudocode below is invoked as “height(root)” to
compute the height of a binary tree rooted at the tree };
pointer “root”. int Dosomething (treeptr tree)
Chapter 5 • Trees | 3. 71

{ 10. A binary tree T has 20 leaves. The number of nodes in


int value = 0; T having two children is ______ [2015]
if (tree ! = NULL){
11. Consider a binary tree T that has 200 leaf nodes.
if (tree – > leftMostChild = = NULL)
Then, the number of nodes in T that have exactly two
value = 1;
children are ______. [2015]
else
value = Dosomething (tree – > leftMostChild); 12. While inserting the elements 71, 65, 84, 69, 67, 83
value = value +Dosomething (tree - > right in an empty binary search tree (BST) in the sequence
Sibling); shown, the element in the lowest level is [2015]
(A) 65 (B) 67
}
(C) 69 (D) 83
return (value);
} 13. Consider the following New–order strategy for tra-
When the pointer to the root of a tree is passed as the versing a binary tree: [2016]
argument to DoSomething, the value returned by the • Visit the root;
function corresponds to the
(A) Number of internal nodes in the tree • Visit the right subtree using New – order;
(B) Height of the tree • Visit the left subtree using New – order;
(C) Number of nodes without a right sibling in the tree
(D) Number of leaf nodes in the tree The New – order traversal of the expression tree cor-
responding to the reverse polish expression
7. The height of a tree is the length of the longest root-
to-leaf path in it. The maximum and minimum num- 3 4 * 5 – 2 ∧ 6 7 * 1 + – is given by:
ber of nodes in a binary tree of height 5 are (A) + – 1 6 7 * 2 ∧ 5 – 3 4 *
[2015] (B) – + 1 * 6 7 ∧ 2 – 5 * 3 4
(C) – + 1 * 7 6 ∧ 2 – 5 * 4 3
(A) 63 and 6, respectively (D) 1 7 6 * + 2 5 4 3 * – ∧ –
(B) 64 and 5, respectively 14. Let T be a binary search tree with 15 nodes. The mini-
(C) 32 and 6, respectively mum and maximum possible heights of T are: [2017]
(D) 31 and 5, respectively Note: The height of a tree with a single node is 0.
8. Which of the following is/are correct inorder traversal (A) 4 and 15 respectively
sequence(s) of binary search tree(s)? [2015] (B) 3 and 14 respectively
I. 3, 5, 7, 8, 15, 19, 25 (C) 4 and 14 respectively
II. 5, 8, 9, 12, 10, 15, 25 (D) 3 and 15 respectively
III. 2, 7, 10, 8, 14, 16, 20 15. The pre-order traversal of a binary search tree is given
IV. 4, 6, 7, 9, 18, 20, 25 by 12,8,6,2,7,9,10,16,15,19,17,20. Then the post-
(A) I and IV only (B) II and III only order traversal of this tree is: [2017]
(C) II and IV only (D) II only (A) 2, 6, 7, 8, 9, 10, 12, 15, 16, 17, 19, 20
9. Consider a max heap, represented by the array: 40, (B) 2, 7, 6, 10, 9, 8, 15, 17, 20, 19, 16, 12
30, 20, 10, 15, 16, 17, 8, 4 [2015] (C) 7, 2, 6, 8, 9,10, 20, 17, 19, 15, 16, 12
(D) 7, 6, 2, 10, 9, 8, 15, 16, 17, 20, 19, 12
Array Index 1 2 3 4 5 6 7 8 9
Value 40 30 20 10 15 16 17 8 4
16. The postorder traversal of a binary tree is 8, 9, 6, 7, 4,
5, 2, 3, 1. The inorder traversal of the same tree is 8, 6,
Now consider that a value 35 is inserted into this 9, 4, 7, 2, 5, 1, 3. The height of a tree is the length of
heap. After insertion, the new heap is the longest path from the root to any leaf. The height
(A) 40, 30, 20, 10, 15, 16, 17, 8, 4, 35 of the binary tree above is ______. [2018]
(B) 40, 35, 20, 10, 30, 16, 17, 8, 4, 15 17. The number of possible min-heaps containing each
(C) 40, 30, 20, 10, 35, 16, 17, 8, 4, 15 value from {1, 2, 3, 4, 5, 6, 7} exactly once is ______.
(D) 40, 35, 20, 10, 15, 16, 17, 8, 4, 30 [2018]
3.72 | Unit 3 • Programming and Data Structures

ANSWER KEYS
EXERCISES
Practice Problems 1
1. B 2. B 3. A 4. C 5. D 6. C 7. C 8. B 9. B 10. B
11. B 12. D 13. A 14. C 15. A

Practice Problems 2
1. D 2. B 3. B 4. A 5. C 6. B 7. D 8. A 9. A 10. B
11. B 12. A 13. C 14. A 15. B

Previous Years’ Questions


1. A 2. D 3. B 4. A 5. 6 6. D 7. A 8. A 9. B 10. 19
11. 199 12. B 13. C 14. B 15. B 16. 4 17. 80

You might also like