Programming in C: Learning Objectives
Programming in C: Learning Objectives
Programming in C
LEARNING OBJECTIVES
}
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
%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
{ {
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
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
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
LEARNING OBJECTIVES
Execution sequences for factorial (3): void swap2 (int *, int *); /* function to
swap two numbers by passing Address * /
Factorial (3) Factorial (3) void main ()
= 3* factorial (2) 3* 2 = 6 {
int a = 10, b = 15, c = 5, d = 25;
printf(“value of a and b before swapping
Factorial (2) Factorial (2) :%d, %d” a , b );
= 2* factorial (1) 2* 1 = 2 swap1(a, b);
printf(“values of a and b after swapping :
%d, %d”, a, b);
Factorial (1)
printf (“values of c and d before swapping
Factorial (1)
1* factorial (0) 1* 1 = 1 :%d%d”, c,d );
Swap2(&c, &d);
printf(“values of c and d after swapping
%d, %d”, c, d);
Factorial (0) = 1 }
void swap1(int x, int y )
{
Disadvantages: int temp;
1. Recursive programs increase the execution time of temp = x;
program. x = y;
2. Recursive programs typically use a large amount of y = temp;
computer memory and the greater the recursion, the }
void swap2 (int *x, int *y)
more memory is used.
{
3. Recursive programs can be confusing to develop and int temp;
extremely complicated to debug. temp = *x;
*x = *y:
PARAMETER PASSING *y = temp;
There are two ways of passing parameters to functions in }
‘C’ language. Output:
1. Pass-by-value: When parameters are passed by value, Value of a and b before swapping: 10, 15
create copies in called function. This mechanism Value of a and b after swapping: 10, 15
is used when we do not want to change the value of Value of c and d before swapping: 5, 25
actual parameters. Value of c and d after swapping: 25, 5
2. Pass-by-address: In this case, only the addresses
of parameters are passed to the called function.
Therefore, manipulation of formal parameters affects Solved Examples
actual parameters.
Examples 6: Example 1: Consider the program below:
void swap1(int, int); /* function – to swap #include<stdio.h>
two numbers by passing values */ int fun (int n, int *fp)
Pass-by-value Pass-by-address
1. Also known as call-by-value 1. Also known as call-by-address or call by-reference
2. Pass the values of actual parameters 2. Pass the address of actual parameters
3. Formal parameters act as duplicates or as a copy to actual 3. Formal parameters acts as references to the actual
parameters parameters
4. Operations on formal parameter does not affect actual 4. Operations on formal parameters affect actual parameters
parameters
5. Passing of parameters is time consuming as the data size 5. The size of parameters does not affect the time for transfer-
increases ring references.
6. Actual parameters are secured 6. Helps to return multiple parameters
Chapter 2 • Functions | 3.17
{
int t,f; fun (2, &x) G G 2 15
if (n < =1) fun (3, &x) G G 3 15
{ fun (4, &x) G G 4 15
*fp=1; fun (5, &x) G G 5 15
return 1; main() − − − 15
} t f n x(fp )
t = fun(n−1, fp);
f = t+ *fp; Note: ‘–’ indicates no memory allocated to variable. ‘G’
*fp = t; indicates garbage value.
return f;
}
int main () fun (1, &x) G G 1 15
{ fun (2, &x) G G 2 15
int x = 15; fun (3, &x) G G 3 15
printf (“%d\n”, fun(5,&x)); fun (4, &x) G G 4 15
return 0; fun (5, &x) G G 5 15
} main() − − − 15
t f n x(fp)
What is the output?
(A) 2 (B) 4
(C) 8 (D) 16 For the function call fun(1, &x) condition (n<=1) is true. So
Assigns ‘1’ to fp and returns ‘1’.
Solution: (C)
Execution stack
fun (1, &x) G G 1 1.
Function call Corresponding fun (2, &x) G G 2 1.
sequence values of t, f, n, x fun (3, &x) G G 3 1.
fun (4, &x) G G 4 1.
fun (5, &x) G G 15 1.
main() − − − 1.
t f n x(fp )
main()
− − − 15
t f n x
fun (2, &x) 1 2 2 1.
fun (3, &x) G G 3 1.
fun (4, &x) G G 4 1.
fun (5 &x) fun (5, &x) G G 15 1.
G G 5 15
main() − − − 1.
main() − − − 15
t f n x(fp)
t f n x(f p )
fun (3 &x) G G 3 15
fun (4 &x) G G 4 15 fun (4, &x) 3 5 4 3.
fun (5 &x) G G 5 15 fun (5, &x) G G 5 3.
main() − − − 15 main() − − − 1.
t f n x(fp ) t f n x(fp)
3.18 | Unit 3 • Programming and Data Structures
Solution: (C)
fun (5, &x) 5 8 5 5. 0 1 2 3 4 5
main() − − − 5. a 12 7 13 4 11 6
t f n x(fp)
f (a, 6) is the first call to function f ( ).
The array _ name refers to base address of array, i.e., address
of first element.
main() 8
Thus,
t f n x(fp)
F (a, 6)
12 % 2 = 0. So,
Finally, x contains ‘8’, so printf prints ‘8’.
Example 2: What does the following program prints? n −1
( a + 1),
#include < stdio.h> 12 + f 5 [*a is even ]
void f (int *p, int *q)
{
↓7
p=q; n −1
*p=12; f ( a + 1),
} 12 + 7 − 4 [*a is odd ]
int i = 0, j=1; ↓ 13
int main()
{ ( a + 1) n −1
f(&i, &j); 12 + 7 − 13 − f , [*a is odd]]
↓ 4 3
printf(“ %d%d “, i, j);
return 0 ;
} ( n − 1)
( a + 1),
(A) 2 12 (B) 12 1 12 + 7 − 13 − 4 + f 2 , [*a is even ]
(C) 0 1 (D) 0 12
↓ 11
Solution: (D)
main( ) 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.
Automatic Memory Till the control remains in block Till the control remains in block Local auto
Register CPU register An unpredictable value (or) gar- Till the control remains in block Local register
bage value
Static Memory Zero Value of variable persist between Local static
function calls
External Memory Unpredictable or garbage value Throughout program execution Global extern
Example 4: What will be the output for the program? (A) error
int i = 33; (B) 11 22 33
main( ) (C) 11 22 garbage
{ (D) 11 11 11
extern int i;
{ Solution: (B)
int i = 22;
‘{‘ introduces new block and thus new scope. In the inner-
{
const volatile unsigned i most block, i is declared as const volatile unsigned which
= 11; is a valid declaration. i is assumed of type int. So printf
printf (“ %d ”, i); prints 11. In the next block, i has value 22 and so printf
} prints 22. In the outermost block, i is declared as extern,
printf (“ %d ”, i); so no storage space is allocated for it. After compilation is
} over, the linker resolves it to global variable, i since it is
printf (“%d “, i) ; the only variable visible there. So it prints its value as 33.
}
3.20 | Unit 3 • Programming and Data Structures
0 + foo (4, 2)
Solution: (C)
0 + foo (2, 2)
Call Sequence r Return Sequence
f (5) 5 18 0 + f (1, 2)
0 + 0
f (1)+r 5 6+5
Choice D
f (0)+r 5 1+5
Result = 1
EXERCISES
Practice Problems 1 t = a;
Directions for questions 1 to 15: Select the correct alterna- a = b;
tive from the given choices. b = t;
}
1. What will be the output of the following program? In order to exchange the values of two variables w and
main( )
z,
{
(A) call swap (w, z)
main( );
(B) call swap (and w, and z)
}
(C) swap (w, z) cannot be used as it does not return any
(A) overflow error (B) syntax error value
(C) returns 0 (D) returns 1 (D) swap (w, z) cannot be used as the parameters are
2. Output of the following program is passed by value
main( )
6. Choose the correct option to fill? x and? y so that the
{
program below prints an input string in reverse order.
static int var = 6;
Assume that the input string is terminated by a new line
printf(“%d\t”, var--);
character:
if(var)
void Rev(void) {
main( );
int a;
}
if (?x) Rev( );
(A) 5 4 3 2 1 0 (B) 6 6 6 6 6 6 ?y
(C) 6 5 4 3 2 1 (D) Error }
3. Which of the following will be the output of the main( ) {
program? printf(“Enter the text”);
main( ) printf(“ \n”);
{ Rev( );
char str[ ] = “Hello”; printf(“\n”);
display( str ); }
} (A) ? x is (getchar( )! = ‘\n’)
void display (char *str) ? y is getchar (A);
{ (B) ? x is((A = getchar( )) ! = ‘\n’)
printf ( “%s”, str) ; ? y is getchar(A) ;
} (C) ? x is (A! = ‘\n’)
(A) compilation error (B) hello ? y is putchar (A);
(C) print null string (D) no output (D) ? x is (A = getchar ( )) ! = ‘\n’)
4. Consider the following C function ? y is putchar(A) ;
int fun (int n) 7. main ( )
{ {
static int x = 0; extern int a;
if (n<=0) return 1; a = 30;
if (n>3) printf (“%d”, a);
{ }
x = n; What will be the output of the above program?
return fun(n-2)+3; (A) 30 (B) Compiler error
} (C) Runtime error (D) Linker error
return fun(n-1)+ x;
8. Which of the following will be the output of the
}
program?
What is the value of fun(5)? void main ( )
(A) 4 (B) 15 {
(C) 18 (D) 19 int n = ret(sizeof(float));
5. For the following C function printf(“\n value is %d ”, ++n);
void swap (int a, int b) }
{ int ret(int ret)
int t; {
3.22 | Unit 3 • Programming and Data Structures
7. What is the return value of the function foo when it is 11. Consider the following pseudo code. What is the total
called as foo (345, 10)? [2011] number of multiplications to be performed? [2014]
(A) 345 (B) 12 D = 2
(C) 5 (D) 3
for i = 1 to n do
Common data for questions 8 and 9: Consider the fol-
for j = i to n do
lowing C code segment
for k = j +1 to n do
int a, b, c = 0;
D = D * 3
void prtFun (void);
(A) Half of the product of the three consecutive inte-
main ( ) gers.
{ static int a = 1; (B) One-third of the product of the three consecutive
prtFun( ); integers.
(C) One-sixth of the product of the three consecutive
a+ = 1;
integers.
prtFun( ); (D) None of the above.
printf(“\n %d %d”, a, b); 12. Consider the function func shown below:
} int func (int num) {
void prtFun(void) int count = 0;
{static int a = 2; while (num) {
int b = 1; count ++;
a+ = ++b; num>>=1;
printf(“\n %d %d”, a, b); }
} return (count);
8. What output will be generated by the given code seg- }
ment if: [2012] The value returned by func(435) is ______ [2014]
Line 1 is replaced by auto int a = 1; 13. Consider the following function
Line 2 is replaced by register int a = 2;
double f (double X)
(A) (B) (C) (D)
3 1 4 2 4 2 4 2 if (abs(X*X – 3) < 0.01)return X;
4 1 6 1 6 2 4 2 else return f(X/2 + 1.5/X);
4 2 6 1 2 0 2 0 }
9. What output will be generated by the given code seg- Give a value q(to two decimals) such that f(q) will
ment? [2012] return q:________ [2014]
(A) (B) (C) (D) 14. Consider the following pseudo code, where x and y
3 1 4 2 4 2 3 1 are positive integers [2015]
4 1 6 1 6 2 5 2
begin
4 2 6 1 2 0 5 2
q := 0
10. What is the return value of f (p, p), if the value of p r := x
while r ≥ y do
is initialized to 5 before the call? Note that the first
begin
parameter is passed by reference, whereas the second r := r – y
parameter is passed by value. q := q + 1
int f(int &x, int c) { end
c = c – 1; end
if (c == 0) return 1; The post condition that needs to be satisfied after the
x = x + 1;
program terminates is
return f(x, c) * x;
(A) {r = qx + y ∧ r < y}
(B) {x = qy + r ∧ r < y}
} [2013]
(A) 3024 (B) 6561 (C) {y = qx + r ∧ 0 < r < y}
(C) 55440 (D) 161051 (D) {q + 1 < r – y ∧ y > 0}
Chapter 2 • Functions | 3.27
ANSWER KEYS
EXERCISES
Practice Problems 1
1. A 2. C 3. A 4. D 5. D 6. D 7. D 8. C 9. B 10. A
11. C 12. C 13. C 14. D 15. C
Practice Problems 2
1. D 2. C 3. B 4. B 5. C 6. C 7. A 8. C 9. C 10. A
11. B 12. C 13. B 14. A 15. B
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
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
*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;
*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
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
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
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
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
LEARNING OBJECTIVES
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
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
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
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
LEARNING OBJECTIVES
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
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
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
−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
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.
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
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
(D) ↓
0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
↓ 2
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