Disha Publication Computer Concept Notes With Exercise Programming and Data Structures. CB512871732
Disha Publication Computer Concept Notes With Exercise Programming and Data Structures. CB512871732
ISBN : 9789386629029
120
3
Page - 119 - 200
C Ø Programming in C
O Ø
Ø
Functions, Recursion
Parameter Passing
N Ø Scope, Binding
T
Ø Abstract data types, Arrays, Stacks
N
Ø Binary heaps
T
S
121
PROGRAMMING AND DATA STRUCTURES PROGRAMMING
IN C
C is a general-purpose high level language that was originally developed by Dennis
Ritchie for the Unix operating system. It was first implemented on the Digital
Equipment Corporation PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C
language. C has now become a widely used professional language for various
reasons.
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
C Program File
All the C programs are writen into text files with extension ".c" for example hello.c.
You can use "vi" editor to write your C program into a file.
This tutorial assumes that you know how to edit a text file and how to write
programming insturctions inside a program file.
C Compilers
When you write any program in C language then to run that program you need to
compile that program using a C Compiler which converts your program into a
language understandable by a computer. This is called machine language (ie. binary
format). So before proceeding, make sure you have C Compiler available at your
computer. Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
The following program is written in the C programming language. Open a text file
First.c using vi editor and put the following lines inside that file.
#include <stdio.h>
int main()
{
/* My first program */
printf("This is a C program! \n");
return 0;
}
Preprocessor Commands: These commands tells the compiler to do preprocessing
before doing actual compilation. Like #include <stdio.h> is a preprocessor command
which tells a C compiler to include stdio.h file before going to actual compilation.
Functions: are main building blocks of any C Program. Every C Program will have one
or more functions and there is one mandatory function which is called main()
function. This function is prefixed with keyword int which means this function returns
an integer value when it exits. This integer value is returned using return
statement.The C Programming language provides a set of built-in functions. In the
above example printf() is a C built-in function which is used to print anything on the
screen.
Variables: are used to hold numbers, strings and complex data for manipulation.
Statements & Expressions : Expressions combine variables and constants to create
new values. Statements are expressions, assignments, function calls, or control flow
statements which make up C programs.
Comments: are used to give additional useful information inside a C Program. All the
comments will be put inside /*...*/ as given in the example above.
Note the followings
122
• C is a case sensitive programming language. It means in C printf and Printf
will have different meanings.
• C has a free-form line structure. End of each C statement must be marked
with a semicolon.
• Multiple statements can be one the same line.
• White Spaces (ie tab space and space bar ) are ignored.
• Statements can continue over multiple lines.
C - Reserved Keywords
The following names are reserved by the C language. Their meaning is already
defined, and they cannot be re-defined to mean anything else.
Auto else Long switch
Break enum register typedef
Case extern return union
Char float Short unsigned
Const for signed void
Continue goto Sizeof volatile
Default if Static while
Do int Struct Packed
Double
While naming your functions and variables, other than these names, you can choose
any names of reasonable length for variables, functions etc.
C Preprocessor, Directives and Header Files:
C Preprocessor :
As part of compilation, the C compiler runs a program called the C preprocessor. The Syntax :
preprocessor is able to add and remove code from your source file. One of the major #define directive:
functions of C preprocessor is Tokenizing. The final step of the preprocessor is to #define identifier substitution_token
link the resulting program with necessary programs and library. For Example:
This directive is used for text substitution. Every occurrence of the identifier is #define TRUE 1
substituted by the substitution_token. The primary advantage is that it increases the #define FALSE
readability of the program. #define MAX 100
# include directive: #define PI 3.14
Syntax :
This directive searches for a header or source file, which can be processed by the #include <filename>
implementation, to be include in the program.
Header files:
Header files are a collection of macros, types, functions and constants. Any program
that needs those functions can include the corresponding header files.
List of some commonly used Header file and their purposes:
Memory
Data type Range of values Properties
Requirement
char -128 to 127 1 byte Holds a character
Int -32,768 to 32,767 2 bytes Holds an integer value
Float 3.4e-38b to 3.4e + e38 4 bytes Holds s ingle precis ion value
double 1.7e-308 to 1.7e + 308 8 bytes Holds double precis ion value
Void 0 byte Holds nothing
C Variable types
A variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable that
you are going to use and its type, or class, before you actually try to do anything
with it.
The Programming language C has two main variable types
• Local Variables
• Global Variables
Local Variables
• Local variables scope is confined within the block or function where it is
defined. Local variables must always be defined at the top of a block.
• When a local variable is defined - it is not initalised by the system, you
must initalise it yourself.
• When execution of the block starts the variable is available, and when the
block ends the variable 'dies'.
Global Variables
Global variable is defined at the top of the program file and it can be visible and
modified by any function that may reference it.
Data Type Initialser
int 0
char '\0'
float 0
pointer NULL
If same variable name is being used for global and local variable then local variable
takes preference in its scope. But it is not a good practice to use global variables and
local variables with the same name.
C - Storage Classes
A storage class defines the scope (visibility) and life time of variables and/or
functions within a C Program.
There are following storage classes which can be used in a C Program
• auto
• register
• static
• extern
auto - Storage Class
auto is the default storage class for all local variables.
{
int Count;
auto int Month;
}
124
The example above defines two variables with the same storage class. auto can only
be used within functions, i.e. local variables.
register - Storage Class
register is used to define local variables that should be stored in a register instead
of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and cant have the unary '&' operator applied to it (as it does not
have a memory location).
{
register int Miles;
}
Register should only be used for variables that require quick access - such as
counters. It should also be noted that defining 'register' goes not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
- depending on hardware and implementation restrictions.
static - Storage Class
static is the default storage class for global variables. The two variables below (count
and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the
static variables defined here will not be seen by the object modules that are brought
in.Static can also be defined within a function. If this is done the variable is initalised
at run time but is not reinitalized when the function is called. This inside a function
static variable retains its value during various calls.
NOTE : Here keyword void means function does not return anything and it does not
take any parameter. You can memoriese void as nothing. Static variables are initialized
to 0 automatically.
Definition vs Declaration : Before proceeding, let us understand the difference
between defintion and declaration of a variable or function. Definition means where
a variable or function is defined in realityand actual memory is allocated for variable
or function. Declaration means just giving a reference of a variable and function.
Through declaration we assure to the complier that this variable or function has been
defined somewhere else in the program and will be provided at the time of linking.
In the above examples char *func(void) has been put at the top which is a declaration
of this function where as this function has been defined below to main() function.
There is one more very important use for 'static'. Consider this bit of code.
char *func(void);
main()
{
char *Text1;
Text1 = func();
}
char *func(void)
{
char Text2[10]="martin";
return(Text2);
}
Now, 'func' returns a pointer to the memory location where 'text2' starts But text2 has
a storage class of 'auto' and will disappear when we exit the function and could be
overwritten but something else. The storage assigned to 'text2' will remain reserved
for the duration if the program.
125
extern - Storage Class
extern is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern' the variable cannot be initalized as all it does
is point the variable name at a storage location that has been previously defined.
File 1: main.c
int count=5;
main()
{
write_extern();
}
File 2: write.c
void write_extern(void);
void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file.
Now compile these two files as follows
gcc main.c write.c -o write
This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c
will see the new value
The same program in C ++
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
Second File: support.cpp
#include <iostream>
void write_extern(void)
{
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile these
two files as follows:
$g++ main.cpp support.cpp -o write
C - Using Constants
A C constant is usually just the written version of a number. For example 1, 0, 5.73,
12.5e9. We can specify our constants in octal or hexadecimal, or force them to be
treated as long integers.
• Octal constants are written with a leading zero - 015.
• Hexadecimal constants are written with a leading 0x - 0x1ae.
• Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b',
'c'. Some characters can't be represented in this way, so we use a 2 character sequence
as follows.
'\n' newline
'\t' tab
'\\' backslash
'\'' single quote
'\0' null ( Usedautomatically to terminate character string )
In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A
string constant is surrounded by double quotes eg "Brian and Dennis". The string
is actually stored as an array of characters. The null character '\0' is automatically
placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important poing
to note.
Defining Constants
ANSI C allows you to declare constants. When you declare a constant it is a bit like
a variable declaration except the value cannot be changed.
The const keyword is to declare a constant, as shown below:
int const a = 1;
const int a =2;
The enum Data type
enum is the abbreviation for ENUMERATE, and we can use this keyword to declare
and initialize a sequence of integer constants. Here's an example:
enum colors {RED, YELLOW, GREEN, BLUE};
I've made the constant names uppercase, but you can name them which ever way you
want.
Here, colors is the name given to the set of constants - the name is optional. Now,
if you don't assign a value to a constant, the default value for the first one in the
list - RED in our case, has the value of 0. The rest of the undefined constants have
a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and
BLUE is 3.
But you can assign values if you wanted to:
enum colors {RED=1, YELLOW, GREEN=6, BLUE };
Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don't initialize your constants, each one
would have a unique value. The first would be zero and the rest would then count
upwards.
127
#include <stdio.h>
int main() {
enum {RED=5, YELLOW, GREEN=4, BLUE};
RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5
C - Operator Types
• Arithmetic Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Lets have a look on all operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by C language:
Assume variable A holds 10 and variable B holds 20 then:
Show Examples
<= Checks if the value of left operand is less than (A <= B) is true.
or equal to the value of right operand, if yes
then condition becomes true.
&& Called Logical AND operator. If both the (A && B) is true.
operands are non zero then then condition
becomes true.
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non zero then then condition
becomes true.
! Called Logical NOT Operator. Use to reverses !(A && B) is false.
the logical state of its operand. If a condition is
true then Logical NOT operator will make
false.
Bitwise Operators:
Bitwise operator works on bits and perform bit by bit operation.
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Show Examples
There are following Bitwise operators supported by C language
129
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) will give 12 which is
result if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists (A | B) will give 61 which is
in eather operand. 0011 1101
^ Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
set in one operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary (~A ) will give -60 which is
and has the efect of 'flipping' bits. 1100 0011
<< Binary Left Shift Operator. The left A << 2 will give 240 which is
operands value is moved left by the number 1111 0000
of bits specified by the right operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15 which is
operands value is moved right by the 0000 1111
number of bits specified by the right
operand.
Assignment Operators:
There are following assignment operators supported by C language:
Co mm a , Left to rig ht
131
All above operators are similar to C++.
Operators Precedence in C++:
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.
Looping
Loops provide a way to repeat commands and control how many times they are
repeated. C provides a number of looping way.
while loop
The most basic loop in C is the while loop.A while statement is like a repeating if
statement. Like an If statement, if the test condition is true: the statments get
executed. The difference is that after the statements have been executed, the test
condition is checked again. If it is still true the statements get executed again.This
cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
while ( expression )
{
Single statement
or
Block of statements;
}
for loop
for loop is similar to while, it's just written differently. for statements are often used
to proccess lists such a range of numbers:
Basic syntax of for loop is as follows:
C++ programming language provides the following types of loop to handle looping
requirements.
{
float Miles;
Miles = 5.6;
}
double - data type
double is used to define BIG floating point numbers. It reserves twice the storage for
the number. On PCs this is likely to be 8 bytes.
{
double Atoms;
Atoms = 2500000;
}
char - data type
char defines characters.
{
char Letter;
Letter = 'x';
}
Modifiers
The data types explained above have the following modifiers.
• short
• long
• signed
• unsigned
The modifiers define the amount of storage allocated to the variable. The amount of
storage allocated is not cast in stone.
Qualifiers
A type qualifier is used to refine the declaration of a variable, a function, and
parameters, by specifying whether:
• The value of a variable can be changed.
• The value of a variable must always be read from memory rather than from
a register
Standard C language recognizes the following two qualifiers:
• const
• volatile
The const qualifier is used to tell C that the variable value can not change after
initialisation.
const float pi=3.14159;
Now pi cannot be changed at a later time within the program.
ARRAYS:
We have seen all basic data types. In C language it is possible to make arrays whose
elements are basic types. Thus we can make an array of 10 integers with the
declaration.
int x[10];
The square brackets mean subscripting; parentheses are used only for function
references. Array indexes begin at zero, so the elements of x are:
Thus Array are special type of variables which can be used to store multiple values
of same data type. Those values are stored and accessed using subscript or index.
Arrays occupy consecutive memory slots in the computer's memory.
x[0], x[1], x[2], ..., x[9]
If an array has n elements, the largest subscript is n-1.
Multiple-dimension arrays are provided. The declaration and use look like:
int name[10] [20];
n = name[i+j] [1] + name[k] [2];
136
Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by
row so the rightmost subscript varies fastest. In above example name has 10 rows and
20 columns.
Same way, arrays can be defined for any data type. Text is usually kept as an array
of characters. By convention in C, the last character in a character array should be
a `\0' because most programs that manipulate character arrays expect it. For example,
printf uses the `\0' to detect the end of a character array when printing it out with
a `%s'.
Array Initialization
• As with other declarations, array declarations can include an optional
initialization
• Scalar variables are initialized with a single value
• Arrays are initialized with a list of values
• The list is enclosed in curly braces
int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};
The number of initializers cannot be more than the number of elements in the array
but it can be less in which case, the remaining elements are initialized to 0.if you like,
the array size can be inferred from the number of initializers by leaving the square
brackets empty so these are identical declarations:
int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16};
int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};
An array of characters ie string can be initialized as follows:
char string[10] = "Hello";
To declare an array in C or C++, the programmer specifies the type of the elements
and the number of elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare
a 10-element array called balance of type double, use this statement:
double balance[10];
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5]={1000.0,2.0,3.4,17.0,50.0};
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization
is created. Therefore, if you write:
double balance[]={1000.0,2.0,3.4,17.0,50.0};
You will create exactly the same array as you did in the previous example. Following
is an example to assign a single element of the array:
balance[4]=50.0;
The above statement assigns element number 5th in the array with a value of 50.0.
All arrays have 0 as the index of their first element which is also called base index
and last index of an array will be total size of the array minus 1. Following is the
pictorial representation of the same array we discussed above:
0 1 2 3 4
balance 1000.0 2.0 3.4 7.0 50.0
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to
salary variable.
137
Dynamic Memory Allocation:
It enables us to create data types and structures of any size and length to suit our
programs need within the program. We use dynamic memory allocation concept when
we don't know how in advance about memory requirement.
There are following functions to use for dynamic memory manipulation:
• void *calloc(size_t num elems, size_t elem_size) - Allocate an array and
initialise all elements to zero .
• void free(void *mem address) - Free a block of memory.
• void *malloc(size_t num bytes) - Allocate a block of memory.
• void *realloc(void *mem address, size_t newsize) - Reallocate (adjust size)
a block of memory.
Command Line Arguments:
It is possible to pass arguments to C programs when they are executed. The brackets
which follow main are used for this purpose. argc refers to the number of arguments
passed, and argv[] is a pointer array which points to each argument which is passed
to main.
#include <stdio.>h
main( int argc, char *argv[] )
{
if( argc == 2 )
printf("The argument supplied is %s\n", argv[1]);
else if( argc > 2 )
printf("Too many arguments supplied.\n");
else
printf("One argument expected.\n");
}
Note that *argv[0] is the name of the program invoked, which means that *argv[1]
is a pointer to the first argument supplied, and *argv[n] is the last argument. If no
arguments are supplied, argc will be one. Thus for n arguments, argc will be equal
to n + 1. The program is called by the command line:
$myprog argument1
More clearly, Suppose a program is compiled to an executable program myecho and
that the program is executed with the following command.
$myeprog aaa bbb ccc
When this command is executed, the command interpreter calls the main() function
of the myprog program with 4 passed as the argc argument and an array of 4 strings
as the argv argument.
argv[0] - "myprog"
argv[1] - "aaa"
argv[2] - "bbb"
argv[3] - "ccc"
Multidimensional Arrays:
The array we used in the last example was a one dimensional array. Arrays can have
more than one dimension, these arrays-of-arrays are called multidimensional arrays.
They are very similar to standard arrays with the exception that they have multiple
sets of square brackets after the array identifier. The above array has two dimensions
and can be called a doubly subscripted array.
ip++;
On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++;
increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip
would be pointing at it.
Pointer arithmetic is very useful when dealing with arrays, because arrays and
pointers share a special relationship in C.
return total;
}
A return keyword is used to return a value and datatype of the returned value is
specified before the name of function. In this case function returns total which is
int type. If a function does not return a value then void keyword can be used as
return value.
Once you have defined your function you can use it within a program:
main()
{
Demo();
}
Functions and Variables:
Each function behaves the same way as C language standard function main(). So
a function will have its own local variables defined. In the above example total
variable is local to the function Demo.
A global variable can be accessed in any function in similar way it is accessed in
main() function.
140
Declaration and Definition
When a function is defined at any place in the program then it is called function
definition. At the time of definition of a function actual logic is implemented with-in
the function.
A function declaration does not have any body and they just have their interfaces.
A function declaration is usually declared at the top of a C source file, or in a separate
header file.
A function declaration is sometime called function prototype or function signature.
For the above Demo() function which returns an integer, and takes two parameters
a function declaration will be as follows:
int Demo( int par1, int par2);
Passing Parameters to a Function
There are two ways to pass parameters to a function:
• Pass by Value: mechanism is used when you don't want to change the
value of passed paramters. When parameters are passed by value then
functions in C create copies of the passed in variables and do required
processing on these copied variables.
• Pass by Reference : mechanism is used when you want a function to do
the changes in passed parameters and reflect those changes back to the
calling function. In this case only addresses of the variables are passed to
a function so that function can work directly over the addresses.
By default, C++ uses call by value to pass arguments.
While calling a function, there are two ways that arguments can be passed to a
function:
Call Type Description
Call by value This method copies the actual value of an
argument into the formal parameter of the function.
In this case, changes made to the parameter inside
the function have no effect on the argument.
Call by pointer This method copies the address of an argument
into the formal parameter. Inside the function, the
address is used to access the actual argument
used in the call. This means that changes made to
the parameter affect the argument.
Call by reference This method copies the reference of an argument
into the formal parameter. Inside the function, the
reference is used to access the actual argument
used in the call. This means that changes made to
the parameter affect the argument.
Here are two programs to understand the difference: First example is for Pass by
value:
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Here is the result produced by the above example. Here the values of a and b remain
unchanged before calling swap function and after calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20
Following is the example which demonstrate the concept of pass by reference
#include <stdio.h>
/* function declaration goes here.*/
void swap( int *p1, int *p2 );
int main()
{
int a = 10;
int b = 20;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
Here is the result produced by the above example. Here the values of a and b are
changes after calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10
Recursion
What is recursion? The simple answer is, it's when a function calls itself. But how
does this happen? Why would this happen, and what are its uses?
When we talk about recursion, we are really talking about creating a loop. Let's start
by looking at a basic loop.
1 for(int i=0; i<10; i++) {
2 cout << "The number is: " << i << endl;
3}
For those who don't yet know, this basic loop displays the sentence, "The number
is: " followed by the value of 'i'. Like this.
142
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
STRINGS
• In C language Strings are defined as an array of characters or a pointer to
a portion of memory containing ASCII characters. A string in C is a sequence of zero
or more characters followed by a NULL '\0' character:
• It is important to preserve the NULL terminating character as it is how C
defines and manages variable length strings. All the C standard library functions
require this for successful operation.
• All the string handling functions are prototyped in: string.h or stdio.h
standard header file. So while using any string related function, don't forget to include
either stdio.h or string.h. May be your compiler differes so please check before going
ahead.
• If you were to have an array of characters WITHOUT the null character
as the last element, you'd have an ordinary character array, rather than a string
constant.
• String constants have double quote marks around them, and can be
assigned to char pointers as shown below. Alternatively, you can assign a string
constant to a char array - either with no size specified, or you can specify a size, but
don't forget to leave a space for the null character!
char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "Hello";
int main() {
char array1[50];
char *array2;
return 0;
}
This will produce following result:
Now enter another string less than 50 characters with spaces:
hello world
C - Structured Datatypes
or an array of students as
struct student students[50];
Another way to declare the same thing is:
struct {
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
} student_a, student_b;
All the variables inside an structure will be accessed using these values as
student_a.firstName will give value of firstName variable. Similarly we can aqccess
other variables.
Pointers to Structs:
Sometimes it is useful to assign pointers to structures (this will be evident in the next
section with self-referential structures). Declaring pointers to structures is basically
the same as declaring a normal pointer:
struct student *student_a;
To dereference, you can use the infix operator: ->.
printf("%s\n", student_a->SSN);
typedef Keyword
There is an easier way to define structs or you could "alias" types you create. For
example:
typedef struct{
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
}student;
Now you can use student directly to define variables of student type without using
struct keyword. Following is the example:
student student_a;
You can use typedef for non-structs:
typedef long int *pint32;
pint32 x, y, z;
x, y and z are all pointers to long ints
Unions Datatype
Unions are declared in the same fashion as structs, but have a fundamental difference.
Only one item within the union can be used at any time, because the memory allocated
for each item inside the union is in a shared memory location.
Here is how we define a Union
145
union Shape {
int circle;
int triangle;
int ovel;
};
We use union in such case where only one condition will be applied and only one
variable will be used.
C - Working with Files
When accessing files through C, the first necessity is to have a way to access the
files. For C File I/O you need to use a FILE pointer, which will let the program keep
track of the file being accessed. For Example:
FILE *fp;
To open a file you need to use the fopen function, which returns a FILE pointer. Once
you've opened a file, you can use the FILE pointer to let the compiler perform input
and output functions on the file.
FILE *fopen(const char *filename, const char *mode);
Here filename is string literal which you will use to name your file and mode can have
one of the following values
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Note that it's possible for fopen to fail even if your program is perfectly correct: you
might try to open a file specified by the user, and that file might not exist (or it might
be write-protected). In those cases, fopen will return 0, the NULL pointer.
Here's a simple example of using fopen:
FILE *fp;
fp=fopen("/home/tutorialspoint/test.txt", "r");
This code will open test.txt for reading in text mode. To open a file in a binary mode
you must add a b to the end of the mode string; for example, "rb" (for the reading
and writing modes, you can add the b either after the plus sign - "r+b" - or before
- "rb+")
To close a function you can use the function:
int fclose(FILE *a_file);
fclose returns zero if the file is closed successfully.
An example of fclose is:
fclose(fp);
To work with text input and output, you use fprintf and fscanf, both of which are
similar to their friends printf and scanf except that you must pass the FILE pointer
as first argument.
Try out following example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w");
fprintf(fp, "This is testing...\n");
fclose(fp;);
}
This will create a file test.txt in /tmp directory and will write This is testing in that
file.
146
Here is an example which will be used to read lines from a file:
#include <stdio.h>
main()
{
FILE *fp;
char buffer[20];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buffer);
printf("Read Buffer: %s\n", %buffer );
fclose(fp;);
}
It is also possible to read (or write) a single character at a time--this can be useful
if you wish to perform character-by-character input. The fgetc function, which takes
a file pointer, and returns an int, will let you read a single character from a file:
int fgetc (FILE *fp);
The fgetc returns an int. What this actually means is that when it reads a normal
character in the file, it will return a value suitable for storing in an unsigned char
(basically, a number in the range 0 to 255). On the other hand, when you're at the very
end of the file, you can't get a character value--in this case, fgetc will return "EOF",
which is a constnat that indicates that you've reached the end of the file.
The fputc function allows you to write a character at a time--you might find this useful
if you wanted to copy a file character by character. It looks like this:
int fputc( int c, FILE *fp );
Note that the first argument should be in the range of an unsigned char so that it
is a valid character. The second argument is the file to write to. On success, fputc
will return the value c, and on failure, it will return EOF.
Binary I/O
There are following two functions which will be used for binary input and output:
size_t fread(void *ptr, size_t size_of_elements,
size_t number_of_elements, FILE *a_file);
Now, if we talk in terms of C++ Programming, C++ classes provides great level
of data abstraction. They provide sufficient public methods to the outside world to
play with the functionality of the object and to manipulate object data, i.e., state
without actually knowing how class has been implemented internally.
In C++, we use classes to define our own abstract data types (ADT). You can use
the cout object of class ostream to stream data to standard output like this:
#include<iostream>
usingnamespace std;
int main()
{
cout <<"Hello C++"<<endl;
return0;
}
Here, you don't need to understand how cout displays the text on the user's screen.
You need to only know the public interface and the underlying implementation of cout
is free to change.
Access Labels Enforce Abstraction:
In C++, we use access labels to define the abstract interface to the class. A class may
contain zero or more access labels:
• Members defined with a public label are accessible to all parts of the
program. The data-abstraction view of a type is defined by its public
members.
• Members defined with a private label are not accessible to code that uses
the class. The private sections hide the implementation from code that uses
the type.
There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right
brace of the class body is seen.
Benefits of Data Abstraction:
Data abstraction provides two important advantages:
• Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.
• The class implementation may evolve over time in response to changing
requirements or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author
is free to make changes in the data. If the implementation changes, only the class code
needs to be examined to see what affect the change may have. If data are public, then
any function that directly accesses the data members of the old representation might
be broken.
Designing Strategy:
Abstraction separates code into interface and implementation. So while designing
your component, you must keep interface independent of the implementation so that
if you change underlying implementation then interface would remain intact.
In this case whatever programs are using these interfaces, they would not be
impacted and would just need a recompilation with the latest implementation
148
OOPS
Introduction
The object-oriented programming (OOP) is a different approach to programming.
Object oriented technology supported by C++ is considered the latest technology
in software development. It is regarded as the ultimate paradigm for the modelling
of information, be that data or logic.
Objectives
After going through this lesson, you would be able to:
l learn the basic concepts used in OOP
l describe the various benefits provided by OOP
l explain the programming applications of OOP.
Object-Oriented Programming
The object-oriented programming is a different approach to programming. It has been
created with a view to increase programmer's productivity by overcoming the
weaknesses found in procedural programming approach. Over the years many object-
oriented programming languages such as C++ and smalltalk have come up and are
becoming quite popular in the market. The major need for developing such languages
was to manage the ever-increasing size and complexity of programs.
Basic Concepts
The following are the basic concepts used in object-oriented programming.
l Objects
l Classes
l Data abstraction
l Modularity
l Inheritance
l Polymorphism
Objects
It can represent a person, a bank account or any item that a program can handle.
When a program is executed, the objects interact by sending messages to one
another. For example, if 'customer' and 'account' are two objects in a program, then
the customer object may send message to account object requesting for a bank
balance. Each object contains data and code to manipulate data. Objects can interact
without having to know details of each other's data or code. It is sufficient to know
the type of massage accepted and the type of response returned by the objects.
Classes
We have just mentioned that objects contain data and function or code to manipulate
that data. The entire set of data and code of an object can be made a user-defined
data type with the help of a class. In fact objects are variables of type class. Once
a class has been defined, we can create any number of objects associated with that
class. For example, mango, apple and orange are members of class fruit. If fruit has
been defined as a class, then the statement fruit mango, will create an object mango
belonging to the class fruit.
Data Abstraction
Abstraction refers to the act of representing essential features without including the
background details. To understand this concept more clearly, take an example of
'switch board'. You only press particular switches as per your requirement. You need
not know the internal working of these switches. What is happening inside is hidden
from you. This is abstraction, where you only know the essential things to operate
on switch board without knowing the background details of switch board.
Data Encapsulation
Encapsulation is the most basic concept of OOP. It is the way of combining both
data and the functions that operate on that data under a single unit. The only way
to access the data is provided by the functions (that are combined along with the
data). These functions are considered as member functions in C++. It is not possible
149
to access the data directly. If you want to reach the data item in an object, you call
a member function in the object. It will read the data item and return the value to you.
The data is hidden, so it is considered as safe and far away from accidental
alternation. Data and its functions are said to be encapsulated into a single entity.
Modularity
The act of partitioning a program into individual components is called modularity. It
gives the following benefits.
l It reduces its complexity to some extent.
l It creates a number of well-defined, documented boundaries within the program.
Module is a separate unit in itself. It can be compiled independently though it has
links with other modules. Modules work quite closely in order to achieve the
program's goal.
Inheritance
It is the capability to define a new class in terms of an existing class. An existing
class is known as a base class and the new class is known as derived class. Number
of examples can be given on this aspect. For example, a motor cycle is a class in itself.
It is also a member of two wheelers class. Two wheelers class in turn is a member
of automotive class as shown in Fig. 8.1. The automotive is an example of base class
and two wheelers is its derived class. In simple words, we can say a motor cycle is
a two wheeler automotive.
C++ supports such hierarchical classification of classes. The main benefit from
inheritance is that we can build a generic base class, i.e., obtain a new class by adding
some new features to an existing class and so on. Every new class defined in that
way consists of features of both the classes. Inheritance allows existing classes to
be adapted to new application without the need for modification.
Polymorphism
Polymorphism is a key to the power of OOP. It is the concept that supports the
capability of data to be processed in more than one form. For example, an operation
may exhibit different behaviour in different instances. The behaviour depends upon
the types of data used in the operation. Let us consider the operation of addition.
For two numbers, the operation will generate a sum. If the operands are strings then
the operation would produce a third string by concatenation.
Fig.
150
Benefits of OOP
OOP provides lot of benefits to both the program designer and the user.
Objectoriented approach helps in solving many problems related to software
development and quality of software product. The new technology assures greater
programmer productivity, better quality of software and lesser maintenance cost. The
major benefits are :
l Software complexity can be easily managed
l Object-oriented systems can be easily upgraded
l It is quite easy to partition the work in a project based on objects.
Programming Applications of OOP
OOP has become one of the programming buzzwords today. There appears to be a
great deal of excitement and interest among software programmers in using OOP.
Applications of OOP are gaining importance in many areas. OOP has been extensively
used in the development of windows and word based systems such as MS-Windows,
x-Windows etc. The promising application areas of OOP are:
(i) Multiple data structure: This is an application where the same data structure is
used many times. For example a window data structure is used multiple-times in a
windowing system.
(ii) Data in multiple programs: This is an application where the same operations are
performed on a data structure in different programs. For example, record validation in
an accounting system.
The other application areas of OOP are parallel programming, simulation and
modelling, AI and Expert systems, Neural Networks and CAD systems.
Linked Lists
A linked list contains a list of data .The Data can be anything: number, character,
array,structure, etc.Each element of the list must also link with the next element
therefore, a structure containing data and link is created.
The link is a pointer to the same type of structure
struct Node
{
int data ;
struct Node *next ;
};
This is called a self-referential pointer
1 Insertion
2 Deletion
3 Searching
n = malloc(sizeof(node));
n->data = val;
n->next = NULL;
return n;
}
Insertion at the beginning of the list
Create a new node (say q)
Make q->next point to head
Make head equal to q
list is empty, i.e., head is NULL
Make head equal to q
Delete after p
Call the next node, i.e., p->next as q
Make p->next equal to q->next
Delete q
Linked List: element definition and creation
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data; // data of a node: list is made of these elements
struct Node *next; // link to the next node
} node;
node *create_node(int val)
{
node *n;
n = malloc(sizeof(node));
n->data = val;
n->next = NULL;
return n;
}
Displaying the data in the linked list
void print_list(node *h)
{ /*Display data in each element of the linked list*/
node *p;
p = h;
while (p != NULL)
{
printf("%d --> ", p->data);
p = p->next;
}
}
Inserting at end
int main()
{
153
node *head = NULL; // head maintains the entry to the list
node *p = NULL, *q = NULL;
int v = -1, a;
printf("Inserting at end: Enter the data value:\n");
scanf("%d", &v);
while (v != -1)
{
q = create node(v);
q->next = NULL;
free (P);
}
Print_list(head);/*Display the data in the list */
printf("Deleting after\n");
scanf("%d", &a);
p = head;
while ((p != NULL) && (p->data != a))
p = p->next;
if (p != NULL)
{
q = p->next;
if (q != NULL)
{
p->next = q->next;
free(q);
}
}
print_list(head); /*Display the data in the list*/
}
STACKS
A stack is simply a list of elements with insertions and deletions permitted at one
endcalled
the stack top. That means that it is possible to remove elements from a stack
in reverse order from the insertion of elements into the stack. Thus, a stack data
structure exhibits the LIFO (last in first out) property. Push and pop are the operations
that are provided for insertion of an element into the stack and the removal of an
element from the stack, respectively.
155
Operations on stack:
The insertion of elements into stack is called PUSH operation.
The deletion of elements from stack is called POP operation.
POP operation:
Following actions taken place in POP:
Check the stack empty or not.
Remove the top element from the stack.
Return this element to the calling function or program.
Stack Push
stack top/head has the address of the first element
Function needs the address to the stack top/head to make changes to head
void push(node **head_address, int top)
{
node *q;
q = create_node(top); /*New element storing the new data*/
q->next = *head address; /*New element pointing to head*/
q >head_/ head /
*head_address = q; /*head pointing to new element*/
return;
}
Stack Pop
A queue is a container of objects (a linear collection) that are inserted and removed
according to the first-in first-out (FIFO) principle. An excellent example of a queue is
a line of students in the food court of the UC. New additions to a line made to the
back of the queue, while removal (or serving) happens in the front. In the queue only
two operations are allowed enqueue and dequeue. Enqueue means to insert an item
into the back of the queue, dequeue means removing the front item. The picture
demonstrates the FIFO access.
The difference between stacks and queues is in removing. In a stack we remove the
item the most recently added; in a queue, we remove the itemthe least recently added.
156
Implementation
In the standard library of classes, the data type queue is an adapter class, meaning
that a queue is built on top of other data structures. The underlying structure for a
queue could be an array, a Vector, an ArrayList, a LinkedList, or any other collection.
Regardless of the type
of the underlying data structure, a queue must implement the same functionality. This
is achieved by providing a unique interface.
interface QueueInterface‹AnyType>
{
public boolean isEmpty();
public AnyType getFront();
public AnyType dequeue();
public void enqueue(AnyType e);
public void clear();
}
Each of the above basic operations must run at constant time O(1). The following
picture demonstrates the idea of implementation by composition.
Circular Queue
Given an array A of a default size (? 1) with two references back and front, originally
set to -1 and 0 respectively. Each time we insert (enqueue) a new item, we increase
the back index; when we remove (dequeue) an item - we increase the front index. Here
is a picture that illustrates the model after a few steps: 0 1 2 3 4 5
As you see from the picture, the queue logically moves in the array from left to right.
After several moves back reaches the end, leaving no space for adding new elements
However, there is a free space before the front index. We shall use that space for
enqueueing new items, i.e. the next entry will be stored at index 0, then 1, until front. front back
Such a model is called a wrap around queue or a circular queue 0 1 2 3 4 5
Finally, when back reaches front, the queue is full. There are two choices to handle
a full queue:a) throw an exception; b) double the array size.
The circular queue implementation is done by using the modulo operator (denoted
front back
%), which is computed by taking the remainder of division (for example, 8%5 is 3).
By using the modulo operator, we can view the queue as a circular array, where the
"wrapped around" can be simulated as "back % array_size". In addition to the back
and front indexes, we maintain another index: cur - for counting the number of
elements in a queue. Having this index simplifies a logic of implementation. back front
APPLICATIONS
The simplest two search techniques are known as Depth-First Search(DFS) and
Breadth-First Search (BFS). These two searches are described by looking at how the
search tree (representing all the possible paths from the start) will be traversed.
Deapth-First Search with a Stack
In depth-first search we go down a path until we get to a dead end; then we backtrack
or back up (by popping a stack) to get an alternative path.
Create a stack
Create a new choice point
Push the choice point onto the stack
• Pop the stack
• Find all possible choices after the last one tried
• Push these choices onto the stack
Return
Breadth-First Search with a Queue
In breadth-first search we explore all the nearest possibilities by finding all possible
successors and enqueue them to a queue.
Create a queue
Create a new choice point
Enqueue the choice point onto the queue
while (not found and queue is not empty)
157
• Dequeue the queue
• Find all possible choices after the last one tried
• Enqueue these choices onto the queue
Return
Queues
Queue operations are also called First-in first-out Operations
Enqueue: insert at the end of queue
Dequeue: delete from the beginning of queue
Code: similar to previous code on linked lists
Queue Application: Executing processes by operating system
Operating System puts new processes at the end of a queue.System executes
processes at the beginning of the queue
Circular Lists
The last element of a linked list points to the first element.
A reference pointer is required to access the list: head
Circular Lists
The list pointer can have the address of the last element.The tail/last element can be
accessed by the list pointer.The head/first element can be accessed from the tail/
lastelement (by list->next)
Provides flexibility in accessing first and last elements
Circular lists can be used for queues.
Useful in enqueue/dequeue operations without needing to
traverse the list.
Implementation
We implement a binary search tree using a private inner class BSTNode. In order to
support the binary search tree property, we require that data stored in each node is
Comparable:
public class BST <AnyType extends Comparable<AnyType>>
{
private Node<AnyType> root;
3
Insertion
9
The insertion procedure is quite similar to searching. We start at the root and
recursively go down the tree searching for a location in a BST to insert a new node.
1 5 12
If the element to be inserted is already in the tree, we are done (we do not insert
duplicates). The new node will always replace a NULL reference.
4 11 Example: Given a sequence of numbers:
before insertion 11, 6, 8, 19, 4, 10, 5, 17, 43, 49, 31
Draw a binary search tree by inserting the above numbers from left to right.
8
11
3 9
6 19
1 5 12
4 8 17 43
4 7 11
5 10 31 49
after insertion
162
Searching
Searching in a BST always starts at the root. We compare a data stored at the root
with the key we are searching for (let us call it as to Search). If the node does not
contain the key we proceed either to the left or right child depending upon
comparison. If the result of comparison is negative we go to the left child, otherwise
- to the right child. The recursive structure of a BST yields a recursive algorithm.
Deletion
Deletion is somewhat more tricky than insertion. There are several cases to consider.
A node to be deleted (let us call it as to Delete)
is not in a tree;
is a leaf;
has only one child;
has two children.
If to Delete is not in the tree, there is nothing to delete. If to Delete node has only
one child the procedure of deletion is identical to deleting a node from a linked list
- we just bypass that node being deleted
8 8
3 9 3 12
1 5 12 1 5 11
4 11 4
Deletion of an internal node with two children is less straightforward. If we delete such
a node, we split a tree into two subtrees and therefore, some children of the internal
node won’t be accessible after deletion. In the picture below we delete 8:
8 5
3 swap data 9 3 9
1 5 12 1 4 12
4 11 11
before deletion after deletion
Deletion starategy is the following: replace the node being deleted with the largest
node in the left subtree and then delete that largest node. By symmetry, the node
being deleted can be swapped with the smallest node is the right subtree.
Non-Recursive Traversals
Depth-first traversals can be easily implemented recursively.A non-recursive
implementation is a bit more difficult. In this section we implement a pre-order traversal
as a tree iterator
163
public Iterator<AnyType> iterator()
{
return new PreOrderIterator();
}
Example where the PreOrderIterator class is implemented as an inner private class of the BST
public AnyType next() class
{ private class PreOrderIterator implements Iterator<AnyType>
Node cur = stk.peek(); {
if(cur.left != null) ...
{ }
stk.push(cur.left); The main difficulty is with next() method, which requires the implicit recursive stack
} implemented explicitly. We will be using Java’s Stack. The algorithm starts with the root
else and push it on a stack. When a user calls for the next() method, we check if the top
{ element has a left child. If it has a left child, we push that child on a stack and return
Node tmp = stk.pop(); a parent node. If there is no a left child, we check for a right child. If it has a right child,
while(tmp.right == null) we push that child on a stack and return a parent node. If there is no right child, we
{ move back up the tree (by popping up elements from a stack) until we find a node with
if (stk.isEmpty()) return cur.data; a right child. Here is the next() implementation as shown in example
tmp = stk.pop(); This example showed the output and the state of the stack during each call to next().
} Note, the algorithm works on any binary trees, not necessarily binary search trees..
stk.push(tmp.right);
} Output 1 2 4 6 5 7 8 3
return cur.data;
6
} 4 7
2 4 5 8
Stack 1 2 5 3
1 2 1 1
1 1
1
1
S P
G R O N
A E C A I
This has violated the condition that the root must be greater than each of its children.
So interchange the M with the larger of its children.
M P
G R O N
A E C A I
165
The left subtree has now lost the heap property.
So again interchange the M with the larger of its children.
R P
G M O N
A E C A I
11
5 8
3 4 X
and we want to add the number 15 to the heap. We first place the 15 in the position
marked by the X. However, the heap property is violated since 15 is greater than 8,
so we need to swap the 15 and the 8. So, we have the heap looking as follows after
the first swap:
11
15
5 15
5 11
3 4 8
3 4 8 However the heap property is still violated since 15 is greater than 11, so we need
to swap again:
166
which is a valid max-heap. There is no need to check the children after this. Before
we placed 15 on X, the heap was valid, meaning 11 is greater than 5. If 15 is greater
than 11, and 11 is greater than 5, then 15 must be greater than 5, because of
the transitive relation.
Delete :
The procedure for deleting the root from the heap (effectively extracting the maximum
element in a max-heap or the minimum element in a min-heap) and restoring the
properties is called down-heap (also known as bubble-down, percolate-down, sift-
down, trickle down, heapify-down, cascade-down and extract-min/max).
1. Replace the root of the heap with the last element on the last level.
2. Compare the new root with its children; if they are in the correct order, stop.
3. If not, swap the element with one of its children and return to the previous step.
(Swap with its smaller child in a min-heap and its larger child in a max-heap.)
So, if we have the same max-heap as before
11
5 8
3 4
5 8
Now the heap property is violated since 8 is greater than 4. In this case, swapping
the two elements, 4 and 8, is enough to restore the heap property and we need not
swap elements further:
5 4
The downward-moving node is swapped with the larger of its children in a max-heap
(in a min-heap it would be swapped with its smaller child), until it satisfies the heap
property in its new position. This functionality is achieved by the Max-Heapify function
as defined below in pseudo code for an array-backed heap A of length heap_length[A].
Note that “A” is indexed starting at 1, not 0 as is common in many real programming
languages.
167
Max-Heapify (A, i):
left ¬ 2i
right ¬ 2i + 1
largest ¬ i
if left £ heap_length[A] and A[left] > A[largest] then:
largest ¬ left
if right £ heap_length[A] and A[right] > A[largest] then:
largest ¬ right
if largest ¹ i then:
swap A[i] « A[largest]
Max-Heapify(A, largest)
For the above algorithm to correctly re-heapify the array, the node at index i and its
two direct children must violate the heap property. If they do not, the algorithm will
fall through with no change to the array. The down-heap operation (without the
preceding swap) can also be used to modify the value of the root, even when an
element is not being deleted.
In the worst case, the new root has to be swapped with its child on each level until
it reaches the bottom level of the heap, meaning that the delete operation has a time
complexity relative to the height of the tree, or O(log n).
Building a heap :
A heap could be built by successive insertions. This approach requires O(n log n)
time because each insertion takes O(log n) time and there are n elements. However
this is not the optimal method. The optimal method starts by arbitrarily putting the
elements on a binary tree, respecting the shape property (the tree could be
represented by an array, see below). Then starting from the lowest level and moving
upwards, shift the root of each subtree downward as in the deletion algorithm until
the heap property is restored. More specifically if all the subtrees starting at some
height h (measured from the bottom) have already been “heapified”, the trees at
height h + 1 can be heapified by sending their root down along the path of maximum
valued children when building a max-heap, or minimum valued children when building
a min-heap. This process takes O(h) operations (swaps) per node. In this method
most of the heapification takes place in the lower levels. Since the height of the heap
is [lg(n)], the number of nodes at height is h.
é 2 lg n ù é n ù
£ [2(lg n - h) -1 ] = ê ú=ê ú
êë 2h +1 úû ë 2h +1 û
æ ¥ h ö
£ Oçnå ÷÷
ç h
è h=0 2 ø
= O(n)
This uses the fact that the given infinite series h / 2h converges to 2.
The exact value of the above (the worst-case number of comparisons during the heap
construction) is known to be equal to:
2n – 2s2(n) – e2(n),
where s2(n) is the sum of all digits of the binary representation of n and e2(n) is the
exponent of 2 in the prime factorization of n.
168
1. Assume that the operators +, –, ×, are left associative and ^ print f(“%s”, p);
is right associative. The order of precedence (from highest The output of the program is
to lowest) is ^, ×, +, –. The postfix expression corresponding (a) gnirts (b) string
to the infix expression a + b × c – d ^ e ^ f is [2005, 2 marks] (c) gnirt (d) no output is printed
(a) abc × + def ^^ – (b) abc × + de^f^– 5. Consider the following C function: [2005, 2 marks]
(c) ab + c × d – e^f^ (d) – + a × bc ^^ def int f (int n)
2. The elements 32, 15, 20, 30, 12, 25, 16, are inserted one by one
{ static int i = 1;
in the given order into a max-heap. The resultant max-heap is
if (n > = 5) return n;
[2005, 2 marks]
n = n + 1;
32 32 i ++;
return f(n);
(a) 30 25 (b) 25 30
}
12 15 20 The value returned by f(1) is
15 12 20 16 16
(a) 5 (b) 6
32 32 (c) 7 (d) 8
6. Postorder traversal of a given binary search tree, T produces
(c) 30 25 (d) 25 30 the following sequence of keys
10, 9, 23, 22, 27, 25, 15, 50, 95, 60, 40, 29
15 12 16 20 12 15 16 20 Which one of the following sequences of keys can be the
3. A circularly linked list is used to represent a queue. A single result of an in-order traversal of the tree T? [2005, 2 marks]
variable p is used to access the queue. To which node should (a) 9, 10, 15, 22, 23, 25, 27, 29, 40, 50, 60, 95
p point such that both the operations en-queue and de-queue (b) 9, 10, 15, 22, 40, 50, 60, 95, 23, 25, 27, 29
can be performed in constant time? [2005, 2 marks] (c) 29, 15, 9, 10, 25, 22, 23, 27, 40, 60, 50, 95
(d) 95, 50, 60, 40, 27, 23, 22, 25, 10, 9, 15, 29
7. Consider the following C-program [2005, 2 marks]
double foo (double); /* Line 1 */
(a) (b) 10 53. Consider the directed graph shown in the figure below. There
10 are multiple shortest paths between vertices S and T. Which
8 6 one will be reported by Dijkstra’s shortest path algorithm’?
8 6 Assume that in any iteration, the shortest path to a vertex v
5 4 5 1 2 is updated only when a strictly shorter path to v is discovered.
4 2 [2012, 2 marks]
1 2
E 2
(c) 10 (d) 5 G
C 1
1
A 4 3
5 6 2 8 3
4 D 3
7 O
4 8 2 1 4 6 10 S 5 T
1 3 4
5
50. Let G be a weighted graph with edge weights greater than 3
B F
one and G be the graph constructed by squaring the weights (a) SDT (b) SBDT
of edges in G. Let T and T’ be the minimum spanning trees of (c) SACDT (d) SACET
G and G’ respectively, with total weights t and t’. Which of
the following statements is true? [2012, 2 marks] (a) Main (b)
Main
(a) T’ = T with total weight t’ = t2
(b) T’ = T with total weight t’ = t2 A1 A1
(c) T’ ¹ T but total weight t’ = t2 A2 A2
(d) None of the above
51. Suppose a circular queue of capacity (n – 1) elements is A21 A21
implemented with an array of n elements. Assume that the Prame
insertion and deletion operations are carried out using REAR
A1 Prame A1
pointer Access pointer Access
and FRONT as array index variables, respectively. Initially links links
REAR = FRONT = 0. The conditions to detect queue full and
(c) (d) Main
queue empty are [2012, 2 marks] Main
(a) full (REAR + 1) mod n = = FRONT
Prame A1 A1
empty: REAR = = FRONT pointer
(b) full (REAR + 1) mod n = = FRONT A2 A2
empty: (FRONT + 1) mod n = = REAR Access
(c) full (REAR = = FRONT A21 links A21
empty: (REAR + 1) mod n = = REAR Prame A1
(d) full (FRONT + 1) mod n = = REAR pointer Access
empty: (REAR = = FRONT links
175
54. The height of a tree is defined as the number of edges on the 58. What is the return value of f(p,p), if the value of p is
longest path in the tree. The function shown in the below in initialized to 5 before the call? Note that the first
invoked as height (root) to compute the height of a binary parameter is passed by reference, whereas the second
tree rooted at the tree pointer root. [2012, 2 marks] parameter is passed by value. [2013, 2 Marks]
{ if (n = = NULL) return – 1; int f (int &x, int c) {
if (n ® left = = NULL) c = c – 1;
if (n ® right = = NULL) return 0; if (c==0) return 1;
else return B1 ; // Box 1 x = x + 1;
return f(x,c) * x;
else {h1 = height (n ® left); }
if (n ® right = NULL) return (1 + h1);
(a) 3024 (b) 6561
else {h2 = height (n ® right);
(c) 55440 (d) 161051
return B2 ; // Box 1
Common Data for Questions 59 and 60:
} The procedure given below is required to find and replace
} certain characters inside an input character string supplied in
} array A. The characters to be replaced are supplied in array
The appropriate expressions for the two boxes B1 and B2 are oldc, while their respective replacement characters are
(a) B1 : (1 + height (n ® right) supplied in array newc. Array A has a fixed length of five
B2 : (1 + max (h1, h2) characters, while arrays oldc and newc contain three
(b) B1 : (height (n ® right) characters each. However, the procedure is flawed.
B2 : (1 + max (h1, h2)
void find_and_replace (char *A, char *oldc,
(c) B1 : (height (n ® right)
char *newc)
B2 : max (h1, h2)
(d) B1 : (1 + height (n ® right) {
B2 : max (h1, h2) for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
55. The number of elements that can be sorted in Q(log n) if (A[i]==oldc[j])
time using heap sort is [2013, 2 Marks] A[i] = newc[j];
(a) Q(1) (b) Q ( log n ) }
The procedure is tested with the following four test cases.
1. oldc = “abc”, newc = “dab”
æ log n ö 2.
(c) Qç (d) Q(log n) oldc = “cde”, newc = “bcd”
è log log n ÷ø 3. oldc = “bca”, newc = “cda”
4. oldc = “abc”, newc = “bac”
56. Consider the following function:
int unknown (int n) { 59. The tester now tests the program on all input strings of
int i, j, k=0; length five consisting of characters ‘a’, ‘b’, ‘c’,
for (i=n/2; i<=n; i++) ‘d’ and ‘e’ with duplicates allowed. If the tester carries
for (j=2; j<=n; j=j*2) out this testing with the four test cases given above,
k = k + n/2; how many test cases will be able to capture the flaw?
return (k); [2013, 2 Marks]
} (a) Only 1 (b) Only 2
The return value of the function is (c) Only 3 (d) All four
[2013, 2 Marks] 60. If array A is made to hold the string “abcde”, which of
(a) Q(n ) 2
(b) Q(n log n)
2
the above four test cases will be successful in exposing
(c) Q(n3) (d) Q(n3 log n) the flaw in this procedure? [2013, 2 Marks]
57. The pre-order traversal sequence of a binary search tree (a) 2 only (b) 4 only
is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one of the (c) 3 and 4 only (d) None
following is the post-order traversal sequence of the
same tree? [2013, 2 Marks] 61. Consider the following program in C language :
(a) 10, 20, 15, 23, 25, 35, 42, 39, 30 #include <stdio.h>
(b) 15, 10, 25, 23, 20, 42, 35, 39, 30 main ()
(c) 15, 20, 10, 23, 25, 42, 35, 39, 30 {
(d) 15, 10, 23, 25, 20, 35, 42, 39, 30 int i;
int *pi = &i;
scanf ("%d", pi);
176
printf ("%d\n", i + 5); 65. Consider the function func shown below:
} int func(int num) {
Which one of the following statements is TRUE ? int count = 0;
[2014, Set-1, 1 Mark] while (num) {
(a) Compilation fails count++;
(b) Execution results in a run-time error. num>>= 1;
(c) On execution, the value printed is 5 more than the }
address of variable i. return (count);
(d) On execution, the value printed is 5 more than the }
integer value entered. The value returned by func (435) is __________.
62. There are 5 bags labeled 1 to 5. All the coins in a given bag [2014, Set-2, 1 Mark]
have the same weight. Some bags have coins of weight 10 66. Suppose n and p are unsigned int variables in a C program.
gm, others have coins of weight 11 gm. I pick 1, 2, 4, 8, 16 We wish to set p to nC3. If n is large, which one of the following
coins respectively from bags 1 to 5. Their total weight comes statements is most likely to set p correctly?
out to 323 gm. Then the product of the labels of the bags [2014, Set-2, 1 Mark]
having 11 gm coins is _____ . [2014, Set-1, 2 Marks] (a) p = n*(n–1)*(n–2) / 6;
63. Consider the following pseudo code. What is the total (b) p = n*(n–1) / 2*(n–2) / 3;
number of multiplications to be performed? (c) p = n*(n–1) / 3*(n–2) / 2;
[2014, Set-1, 2 Marks] (d) p = n * (n-1) * (n–2) / 6.0;
D=2 67. A priority queue is implemented as a Max-Heap. Initially, it
for i = 1 to n do has 5 elements. The level-order traversal of the heap is: 10,
for j = i to n do 8, 5, 3, 2. Two new elements 1 and 7 are inserted into the
for k = j + 1 to n do heap in that order. The level-order traversal of the heap after
D = D*3 the insertion of the elements is: [2014, Set-2, 1 Mark]
(a) Half of the product of the 3 consecutive integers. (a) 10, 8, 7, 3, 2, 1, 5 (b) 10, 8, 7, 2, 3, 1, 5
(b) One-third of the product of the 3 consecutive integers. (c) 10, 8, 7, 1, 2, 3, 5 (d) 10, 8, 7, 5, 3, 2, 1
(c) One-sixth of the product of the 3 consecutive integers. 68. Consider the expression tree shown. Each leaf represents a
(d) None of the above. numerical value, which can either be 0 or 1. Over all possible
64. Consider the following C function in which size is the choices of the values at the leaves, the maximum possible
number of elements in the array E: value of the expression represented by the tree is ___.
int MyX(int*E, unsigned int size)
{
int Y = 0;
int Z;
int i, j, k;
for (i = 0; i < size; i++)
Y = Y + E[i];
for (i = 0; i < size; i++)
for (j = i; j < size; j++)
{
Z = 0; 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1
for (k = i; k <= j; k++)
Z = Z + E[k]; [2014, Set-2, 2 Marks]
if (Z > Y) 69. Consider the following function
Y = Z; double f(double x){
} if( abs(x*x – 3) < 0.01) return x;
return Y; else return f(x/2 + 1.5/x);
} }
The value returned by the function MyX is the Give a value q (to 2 decimals) such that f(q) will return
[2014, Set-1, 2 Marks] q:_____. [2014, Set-2, 2 Marks]
(a) maximum possible sum of elements in any sub-array 70. Suppose a stack implementation supports an instruction
of array E. REVERSE, which reverses the order of elements on the stack,
(b) maximum element in any sub-array of array E. in addition to the PUSH and POP instructions. Which one
(c) sum of the maximum elements in all possible sub-arrays of the following statements is TRUE with respect to this
of array E. modified stack? [2014, Set-2, 2 Marks]
(d) the sum of all the elements in the array E.
177
(a) A queue cannot be implemented using this stack. A [j] [i] = Temp – C;
(b) A queue can be implemented where ENQUEUE takes }
a single instruction and DEQUEUE takes a sequence for i = 1 to n do
of two instructions. for j = 1 to n do
(c) A queue can be implemented where ENQUEUE takes output (A [i] [j]);
a sequence of three instructions and DEQUEUE takes (a) The matrix A itself
a single instruction. (b) Transpose of the matrix A
(d) A queue can be implemented where both ENQUEUE (c) Adding 100 to the upper diagonal elements and
and DEQUEUE take a single instruction each. subtracting 100 from lower diagonal elements of A
71. Consider the C function given below. (d) None of the above
int f(int j) 73. The minimum number of arithmetic operations required to
{ evaluate the polynomial P(X) = X5 + 4X3 + 6X + 5 for a given
static int i = 50; value of X, using only one temporary variable is _____.
int k; [2014, Set-3, 1 Mark]
if (i == j) 74. Consider the following rooted tree with the vertex labeled P
{ as the root :
printf(“something”);
k = f(i);
P
return 0;
}
else return 0;
}
Q R
Which one of thefollowing is TRUE?
[2014, Set-2, 2 Marks]
(a) The function returns 0 for all values of j.
(b) The function prints the string something for all values
of j. U V
(c) The function returns 0 when j = 50. T
S
(d) The function will exhaust the runtime stack or run into
an infinite loop when j = 50.
72. Let A be a square matrix of size n × n. Consider the following
pseudocode. What is the expected output ? W
[2014, Set-3, 1 Mark]
c = 100;
The order in which the nodes are visited during an in-order
for i = 1 to n do
traversal of the tree is [2014, Set-3, 1 Mark]
for j = 1 to n do
(a) SQPTRWUV (b) SQPTUWRV
{
(c) SQPTWUVR (d) SQPTRUWV
Temp = A [i] [j] + C;
A [i] [j] = A [j] [i];
178
1. Which of the following comments are not true? 8. int i = 5; is a statement in a C program. Which of the following
1. C provides no input-output features are true?
2. C provides no file access features (a) During execution, value of i may change but not its
3. C borrowed most of its ideas from BCPL address
4. C provides no features to manipulate composite objects (b) During execution both the address and value may
(a) 1 only (b) 1, 2 and 3 change
(c) 1, 2, 3 and 4 (d) None of these (c) Repeated execution may result in different addresses
2. Any C program
for i
(a) must contain at least one function
(d) i may not have an associated address
(b) need not contain any function
9. The declaration
(c) needs input data
enum cities {bethlethem, jericho, nazareth = 1, jerusalem}
(d) None of the above
3. Preprocessing is typically done assign the value 1 to
(a) either before or at the beginning of the compilation (a) bethlehem (b) nazareth
process (c) bethlehem and nazareth (d) jericho and nazareth
(b) after compilation but before execution 10. The value of an automatic variable that is declared but not
(c) after loading initialized will be
(d) None of these (a) 0 (b) – 1
4. The purpose of the following program fragment. (c) unpredictable (d) None of these
b = s + b; 11. The following program fragment
s = b – s; int a = 4, b = 6;
b = b – s; printf (“%d”, a = = b);
where s, be are two integers is to (a) outputs an error message (b) prints 0
(a) transfer the contents of s to b (c) prints 1 (d) none of the above
(b) transfer the contents of b to s 12. x – = y + 1; means
(c) exchange (swap) the contents of s and b (a) x = x – y + 1 (b) x = – x – y – 1
(d) negate the contents of s and b
(c) x = – x + y + 1 (d) x = x – y – 1
5. Which of the following about conditional compilation is
13. The following program fragment
not true?
int x[ 5 ] [ 5 ], i, j;
1. It is taken care of by the compiler
2. It is setting the compiler option conditionally. for (i = 0; i < 5; ++i)
3. It is compiling a program based on a condition. for (j = 0; j < 5, j++)
4. It is taken care of by the pre-processor. x[i][j] = x[j][i];
(a) 2 only (b) 3 and 4 only (a) transposes the given matrix x
(c) 1 and 2 (d) All of the above (b) makes the given matrix x, symmetric
6. Lengths of the string “correct” and “correct string” are (c) doesn’t alter the matrix x
(a) 7, 14 (d) None of these
(b) 8, 14 14. Consider the statement
(c) 6, 13 int val [2][4] = {1, 2, 3, 4, 5, 6, 7, 8};
(d) implementation dependant 4 will be the value of when array declaration in the row-
7. For C preprocessor, which of the following is/are true? major order.
1. Takes care of conditional compilation (a) val [1] [4] (b) val [0] [4]
2. Takes care of macros (c) val [1] [1] (d) None of the above
3. Takes care of includes files 15. The maximum number of dimension an array can have in C is
4. Acts before compilation
(a) 3 (b) 4
(a) 1 and 2 (b) 3 only
(c) 5 (d) None of the above
(c) 1, 2 and 3 (d) All of the above
179
16. Consider the array definition (a) max (max (a, b), max (a, c))
int num [10] = {3, 3, 3}; (b) max (a, max (a, c))
Pick the correct answers. (c) max (max (a, b), max (b, c))
(a) num [9] is the last element of the array num (d) max (b, max (a, c))
(b) the value of num [8] is 3 25. void can be used
(c) the value of num [3] is 3 (a) as data-type of a function that returns nothing to its
(d) None of the above calling environment
17. Consider the following type definition. (b) inside the brackets of a function that does not need
typedef char x [10]; any argument
x myArray [5]; (c) in an expression and in a printf statement
What will size of (myArray) be? (Assume one character (d) both (a) and (b)
occupies 1 byte) 26. The following program,
(a) 15 bytes (b) 10 bytes main ()
(c) 50 bytes (d) 30 bytes {
18. If n has the value 3, then the statement a[++n] = n++; int i = 2;
(a) assigns 3 to a [5] { int i = 4, j = 5;
(b) assigns 4 to a [5] printf (“%d%d”, i, j);
(c) assigns 4 to a [4] }
(d) what is assigned is compiler-dependent printf (“%d%d”, i, j);
19. If a global variable is of storage class static, then }
(a) the static declaration is unnecessary if the entire source (a) will not compile successfully
code is in a single file (b) prints 4525
(b) the variable is recognized only in the file in which it (c) prints 25 25
defined (d) None of the above
(c) it results in a syntax error 27. The following program,
(d) both (a) and (b) main ()
20. The default parameter passing mechanism is {
(a) call by value (b) call by reference inc (); inc (); inc ();
(c) call by value result (d) none of these }
21. The storage class static can be used to inc()
(a) restrict the scope of an external identifier {
(b) preserve the exit value of variables static int x;
(c) provide privacy to a set of functions printf (“%d”, ++x);
(d) All of the above }
22. The following program (a) prints 012
main () (b) prints 123
{printf (“tim”); (c) prints 3 consecutive, but unpredictable numbers
main ();} (d) prints 111
(a) is illegal (b) keeps on printing tim 28. main ()
(c) prints tim once (d) None of the above {int a = 5, b = 2;
23. Consider the following program print f (“%d”, a +++b);
main () }
{putchar (‘M’); (a) results in syntax error
first (); (b) prints 7
putchar (‘m’);} (c) prints 8
first () (d) None of these
{ _________ } 29. The program fragment
second () int a = 5, b = 2;
{putchar (‘d’);} printf (“%d”, a +++++b);
If Madam is the required output, then the body of first () (a) prints 7 (b) prints 8
must be (c) prints 9 (d) none of these
(a) empty
30. If arr is a two dimensional array of 10 rows and 12 columns,
(b) second (); putchar (‘a’);
then arr [5] logically points to the
(c) putchar (‘a’); second (); printf(“%C”, ‘a’);
(a) sixth row (b) fifth row
(d) none of the above
(c) fifth column (d) sixth column
24. Max is a function that returns the larger of the two integers,
given as arguments. Which of the following statements does
not finds the largest of three given numbers?
180
31. The statements 39. a ® b is syntactically correct if
int**a; (a) a and b are structures
(a) is illegal (b) a is a structure and b is a pointer to a structure
(b) is legal but meaningless (c) a is a pointer to a structure and b is a structure
(c) is syntactically and semantically correct (d) a is a pointer to a structure is which b is a field
(d) none of these 40. If a file is opened in r+ mode then
32. Consider the following declaration, 1. reading is possible
int a, * b = &a, **c = & b; 2. writing is possible
the following program fragment 3. it will be created if it does not exist
a = 4; (a) 1 is true (b) 1 and 3 are true
**c = 5 ; (c) 1 and 2 are true (d) 1, 2 and 3 are true
(a) does not change the value of a 41. The contents of a file will be lost if it is opened in
(b) assigns address of c to a (a) a mode (b) w mode and w + mode
(c) assigns the value of b to a (c) r + mode (d) a + mode
(d) assigns 5 to a 42. Bit field
33. Let x be an array. Which of the following operations are (a) is a field having many sub-fields
illegal? (b) is a structure declaring the sizes of the members in
1. + + x 2. x + 1 terms of bits
3. x + + 4. x * 2 (c) is a member of a structure whose size is specified in
(a) 1 only (b) 3 and 4 terms of bits
(c) 2, 3 and 4 (d) 1, 3 and 4 (d) none of these
34. Pick the correct answers. 43. The statement printf (“%d”, size of (“”)); prints
If x is an one dimensional array, then (a) an error message (b) 0
(a) &x[i] is same as x + i – 1 (c) garbage (d) 1
(b) * (x + i) is same as * (&x [i]) 44. The statement printf (“%d”, (a++)); prints
(c) *(x + i) is same as x[i] (a) the current value of a (b) the value of a + 1
(d) both (b) and (c) (c) an error message (d) garbage
35. Choose the correct statements 45. Consider the function
(a) An entire array can be passed as argument to a function. find (int x, int y)
(b) A part of an array can be passed as argument to a {return ((x < y) ? 0 : (x – y)); }
function. Let a, b be two non-negative integers. The call find (a, find
(c) Any change done to an array that is passed as an (a, b)) can be used to find the
argument to a function will be local to the function. (a) maximum of a, b
(d) Both (a) and (b) (b) positive difference of a, b
36. A pointer variable can not be (c) sum of a, b
(a) passed to a function as argument (d) minimum of a, b
(b) changed within a function 46. If abc is the input, then the following program fragment
(c) returned by a function char x, y, z;
(d) assigned an integer value printf (“%d”, scanf (“%c%c%c, &x, &y, &z)); results in
37. If func is a function needing three arguments a1, a2, a3, then (a) a syntax error (b) a fatal error
func can be invoked by (c) segmentation violation (d) printing of 3
(a) func (a1, a2, a3); (b) (*func) (a1, a2, a3); 47. Consider the statements
(c) *func (a1, a2, a3); (d) Both (a) and (b) putchar (getchar ());
38. The following program putchar (getchar ());
main () If
{ a
float a = .5, b = .7; b
if (b < = 7) is the input, the output will be
if (a < .5) (a) an error message (b) a/nb
printf (“IES”); (c) ab (d) a b
else 48. If y is of integer type then the expressions
printf (“PSU”); 3 * (y – 8)/9 and (y – 8) / 9*3
else yield the same value if
printf (“GATE”); (a) y must yield the same value
} (b) y must yield different values
(c) y may or may not yield the same value
output is
(d) None of these
(a) PSU (b) IES
(c) GATE (d) None of these
181
49. The program fragment 57. Consider the following flow chart.
int i = 263; T
F
putchar (i); a>b b>c a=1
(a) prints 263
(b) prints the ASCII equivalent of 263
(c) rings the bell F
(d) prints garbage
50. The following statement F
printf (“%f”, 9/5); b=2 c>d
prints
(a) 1.8 (b) 1.0 Which of the following does not correctly implements the
(c) 2.0 (d) none of these above flow chart?
51. The following loop (a) if (a > b) (b) if (a < = b)
for (putchar (‘c’); putchar (‘a’); putchar (‘r’)) putchar (‘t’); if (b > c) if (b > c)
outputs a = 1; a = 1;
else if (c > d) else if (c < = d)
(a) a syntax error (b) cartrt
b = 2; b = 2;
(c) catrat (d) catratratratrat...
(c) if (a > b) (d) if (a < = b)
52. The following program ; ;
main () else if (b > c) else if (b > c)
{ a = 1; a = 1;
int i = 5; else if (c < = d) else if (c > d)
if (i = = 5) return; b = 2; ;
else printf “i is not five”); else b = 2;
printf (“over”); 58. The following statement
} if (a > b)
results in if (c > b)
(a) a syntax error print f (“one”);
(b) an execution error else
(c) printing of over if (c = = a) printf (“two”);
(d) execution termination, without printing anything else print f (“three”);
53. The following program fragment else print f (“four”);
int i = 5; (a) results in a syntax error
do {putchar (i + 100); printf (“%d”, i – –):} (b) prints four if c < = b, can here print four
while (i); (c) prints two if c < = b, can never print two
results in the printing of (d) prints four if a < = b, can never print four
(a) i5h4g3f 2e1 (b) i4h3g2 fle0 59. The following program fragment
(c) an error message (d) none of these int x = 4, y = x, i;
for (i = 1; i < 4; ++ i)
54. The following statements
x + = x;
for (i = 3; i < 15; i + = 3) outputs an integer that is same as
{ printf (“%d”, i); (a) 8 * y (b) y * (1 + 2 + 3 + 4)
++i; (c) y * 4 (d) y * y
} 60. Consider the declaration
will result in the printing of static char hello {} = “hello” ;
(a) 3 6 9 12 (b) 3 6 9 12 15 The output of print f (“% s \ n”, hello);
(c) 3 7 11 (d) 3 7 11 15 will not be the same as that of
55. If a = 9, b = 5 and c = 3, then the expression (a – a/b * b % c) (a) puts (“hello”);
> a % b % c evaluates to (b) puts (hello);
(a) true (b) false (c) printf (“%s \ n”, “hello”);
(c) invalid (d) 0 (d) puts (“hello \ n”);
56. Consider the following program fragment 61. The following program
if (a > b) main ()
printf (“a > b”) {
else static int a[ ] = {7, 8, 9};
printf (“else part”); print f (“%d”, 2 [a] + a[2]);
printf (“a < = b”); }
then a < = b (a) results in bus error
will be printed if (b) results in segmentation violation error
(a) a > b (b) a < b (c) will not compile successfully
(c) a = = b (d) All of the above (d) None of these
182
62. The following program (a) storage needed will be proportional to the size of the
main () data
{ (b) execution will be faster
static char a[3] [4] = {“abcd”, “mnop”, “fghi”}, (c) swapping process becomes easier and faster
putchar (**a); (d) All of the above
} 70. Consider the two declarations
(a) will not compile successfully void * voidPtr;
(b) results in run-time error char *charPtr;
(c) prints garbage Which of the following assignments are syntactically
(d) None of these correct?
63. The output of the following program is (a) voidPtr = charPtr (b) charPtr = voidPtr
main () (c) * voidPtr = * charPtr (d) * charPtr = voidPtr
{ static int x[ ] = {1, 2, 3, 4, 5, 6, 7, 8}, 71. Consider the declaration
int i; char x[ ] = “SUCCESS”;
for (i = 2; i < 6; ++i) char *y = “SUCCESS”;
x [x[i]] = x[i]; Pick the correct answers.
for (i = 0; i < 8; ++i) (a) The output of puts (x) and puts (y) will be the same.
print f (“%d”, x[i]); (b) The output of puts (x) and puts (y) will be different.
} (c) The output of puts (y) is implementation dependent.
(a) 1 2 3 3 5 5 7 8 (b) 1 2 3 4 5 6 7 8 (d) None of the above comments are true.
(c) 8 7 6 5 4 3 2 1 (d) 1 2 3 5 4 6 7 8 72. Consider three pegs A, B, C and four disks of different sizes.
64. Consider the following program Initially, the four disks are stacked on peg A, in orderof
main () decreasing size. The task is to move all the disks from peg A
{ int x = 2, y = 2; to peg C with the help of peg B. themoves are to be made
if (x < y) return (x = x + y); under the following constraints:
else printf (“z1”); [i] In each step, exactly one disk is moved from one peg to
printf (“z2”); another.
} [ii] A disk cannot be placed on another disk of smaller size.
Choose the correct statements If we denote the movement of a disk from onepeg to another
(a) The output is z2 by y ® y, where y, y are A, B or C, then represent the
(b) The output is z1z2 sequence of the minimum numberof moves to accomplish
(c) This will result in compilation error this as a binary tree with node labels of the form (y ® y)
(d) None of the above such that the in-ordertraversal of the tree gives the correct
65. A possible output of the following program fragment sequence of the moves.If there are n disks, what is the total
static char wer [ ] [5] = {“harmot”, “merli”, “axari”); number of moves required in terms of n. Answer can be an
printf ({“%d %d”, wer, wer [0], &wer [0] [0]); is expression in terms of n.
(a) 262164 262164 262164 (b) 262164 262165 262166 (a) 2n – 1 (b) 2n + 1
(c) 262164 262165 262165 (d) 262164 262164 262165 (c) 2 n – 1 (d) 2n – 3
66. The following program 73. The following sequence of operations is performed on a
main () stack :
{ int abc (); PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP,
abc (); POP, POP, PUSH (20), POP.
(*abc) (); (a) 10 20 10 20 20 (b) 20 10 10 20 20
} (c) 20 20 10 10 20 (d) None of these
int abc () 74. Choose the false statements.
{printf (“come”);} (a) The scope of a macro definition need not be the entire
(a) results in a compilation error program.
(b) prints come come (b) The scope of a macro definition extends from the point
(c) results in a run time error of definition to the end of the file.
(d) prints come
(c) A macro definition may go beyond a line
67. The possible output of printf (“%d %d, wer [1], wer [1] + 1); is
(d) None of the above
(a) 162 163 (b) 162 166
75. Calloc (m, n); is equivalent to
(c) 162 166 (b) 162 165
68. The possible output of printf (“%d %d, wer, wer + 1); is (a) malloc (m*n, 0);
(a) 262 262 (b) 262 266 (b) memset (0, m*n);
(c) 262 263 (b) 262 265 (c) ptr = malloc (m*n); memset (p, 0, m*n)
69. While sorting a set of names, representing the names as an (d) ptr = malloc (m*n); strcpy (p, 0)
array of pointers is preferable to representing the name as a
two dimensional array of characters, because
183
76. The for loop 84. For loop in a C program, if the condition is missing
for (i = 0, i < 10; ++i) (a) it is assumed to be present and taken to be false
printf (“%d”, i &1); (b) it is assumed to be present and taken to the true
prints (c) it result in a syntax error
(a) 0101010101 (b) 0111111111 (d) execution will be terminated abruptly
(c) 0000000000 (d) 1111111111 85. Which of the following statements about for loop is/are
77. The output of the following program correct?
main () (a) Index value is retained outside the loop
{ int a = 1, b = 2, c = 3; (b) Index value can be changed from within the loop
printf (“%d”, a + = (a + = 3, 5, a)); (c) Goto can be used to jump, out of the loop
} (d) All of these
will be 86. If c is a variable initialised to 1, how many times will the
(a) 8 (b) 12 following loop be executed?
while ((c > 0). && (c < 60)) {
(c) 9 (d) 6
loop body
78. Consider the following program segment.
c + + ;}
char *a, *b, c [10], d[10];
(a) 60 (b) 59
a = b;
(c) 61 (d) 1
b = c;
87. The program fragment
c = d; int i = 263;
d = a; putchar (i);
Choose the statements having errors. prints
(a) No error (b) a = b; and b = c; (a) 263 (b) ASCII equivalent of 263
(c) c = d; and d = a; (d) a = b; and d = a; (c) rings the bell (d) garbage
79. Consider the following statements 88. If statement
# define hypotenuse (a, b) sqrt (a * a + b * b); b = (int *) **c;
The macro-call hypotenuse (a + 2, b + 3); is appended to the above program fragment, then
(a) Finds the hypotenuse of a triangle with sides a + 2 and (a) value of b is unaffected
b+ 3 (b) value of b will be the address of c
(b) Finds the square root of (a + 2)2 + (b + 3)2 (c) value of b becomes 5
(c) is invalid (d) None of these
(d) Finds the square root of 3*a + 4*b + 5 89. Consider the declarations:
80. Which of the following comments about arrays and pointers char first (int (*) (char, float));
is/are not true? int second (char, float);
1. Both are exactly same Which of the following function invocation is valid?
2. Array is a constant pointer (a) first (*second) (b) first (& second);
3. Pointer is an one-dimensional array (c) first (second); (d) None of these
4. Pointer is a dynamic array 90. Consider the declaration:
(a) 1, 3 and 4 (b) 1, 2, and 3 static struct {unsigned a : 5;
(c) 2, 3 and 4 (d) 1, 2, 3 and 4 unsigned b : 5;
81. Use of macro instead of function is recommended unsigned c : 5;
(a) when one wants to reduce the execution time unsigned d : }v = (1, 2, 3, 4);
(b) when there is a loop with a function call inside v occupies
(a) 4 words (b) 2 words
(c) when a function is called in many places in a program
(c) 1 word (d) None of these
(d) In (a) and (b) above
91. The value of ab if ab & 0 × 3f equals 0 × 27 is
82. Which of the following statements is (are) correct?
(a) 047 (b) 0 × 0f
(a) Enum variables can be assigned new values
(c) 0 × f 3 (d) 0 × 27
(b) Enum variables can be compared
92. A function can make
(c) Enumeration feature does not increase the power of C
(a) one throw
(d) All of these
(b) one throw of each scale type
83. For ‘C’ programming language,
(c) one throw of each programmer defined type
(a) constant expressions are evaluated at compile time
(d) as many throws of as many types as necessary.
(b) string constants can be concatenated at compile time
93. In the statement template << class T>>,
(c) size of array should be known at compile time
(a) T is a class (b) T is a scalar variable
(d) All of these
(c) either (a) or (b) (d) None of these
184
94. In C programming language, which of the following type of 105. Following is a recursive function for computing the sum of
operators have the highest precedence integers from 0 to N.
(a) relational operators function sum (N : integer): integer
(b) equality operators begin
(c) logical operators if N = 0 then Sum = 0
(d) arithmetic operators else
95. In C programming language, which of the following end;
operators has the highest precedence? The missing line in the else part is
(a) unary + (b) * (a) Sum : = N + Sum (N)
(c) ³ (d) = = (b) Sum : = N + Sum (N – 1)
96. What will be the value of x and y after execution of the (c) Sum : = (N – 1) + Sum (N)
following statement (C language) n = = 5; x = n++; y = – x? (d) Sum : = (N – 1) + Sum (N – 1)
106. What is the value of F(4) using the following procedure?
(a) 5, 4 (b) 6, 5
function F(k : integer) : integer;
(c) 6, 6 (d) 5, 5
begin
97. C programming language provides operations which deal if (k < 3)
directly with objects such as then F: = k
(a) strings and sets else F : = F(k – 1) * F(k – 2) + F(k – 3)
(b) lists and arrays end;
(c) characters, integers, and floating point numbers (a) 5 (b) 6
(d) All of these (c) 7 (d) 8
98. C programming language by itself provides 107. Which of the following types of expressions does not require
(a) input facility precedence rule for evaluated?
(b) output facility (a) Full parenthesized infix expression
(c) both input and output facilities (b) Prefix expression
(d) no input and output facilities (c) Partially parenthesized infix expression
99. In what kind of storage structure for strings, one can easily (d) More than one of these
insert, delete, concatenate and rearrange substrings? 108. If space occupied by null terminated string “S1” and “S2” in
(a) Fixed length storage structure “c” are respectively “m” and “n”, the space occupied by
(b) Variable length storage with fixed maximum the string obtained by concatenating “S1” and “S2” is
(c) Linked list storage always
(d) Array type storage (a) less than m + n (b) equal to m + n
100. The time required to search an element in a linked list of (c) greater than m + n (d) None of these
length n is 109. Output of the following ‘C’ program is
(a) O (log2n) (b) O(n) main ()
(c) O(1) (d) O(n2) {
101. Consider a linked list of n element which is pointed by an printf (“\n%x”, – 1 >>4);
external pointer. What is the time taken to delete the element }
which is successor of the element pointed to by a given (a) ffff (b) 0fff
pointer? (c) 0000 (d) fff0
(a) O (1) (b) O (log2n) 110. If abc is the input, then following program fragment
(c) O (n) (d) O (n log2 n) char x, y, z;
102. Which of the following is a tabular listing of contents of printf (“%d”, scanf (“%c%c%c”, &x, &y, &z));
certain registers and memory locations at different times results in
(a) a syntax error (b) a fatal error
during the execution of a program?
(c) segmentation violation (d) printing of 3
(a) Loop program (b) Program trace
111. The rule for implicit type conversion in ‘C’ is
(c) Subroutine program (d) Byte sorting program
(a) int < unsigned < float < double
103. For a linear search in an array of n elements the time
(b) unsigned < int < float < double
complexity for best, worst and average case are......, ..... and
(c) int < unsigned < double < float
.... respectively
(d) unsigned < int < double < float
(a) O(n), O(1) and O(n/2) (b) O(1), O(n) and O(n/2)
112. Result of the execution of the following ‘C’ statements is
æ n -1 ö int i = 5;
(c) O/1, O(n) and O(n) (d) O(1), O(n) and ç ÷ do {putchar (i + 100); printf (“%d”, i– –);}
è 2 ø
104. Using the standard algorithm, what is the time required to while (i);
determine that a number n is prime? (a) i5hug3f 2e1 (b) 14h3g2f1e0
(a) Linear time (b) Logarithmic time (c) an error message (d) None of these
(c) Constant time (d) Quadratic time
185
113. A “switch” statement is used to 121. The expression 5 – 2 – 3 * 5 – 2 will evaluate to 18, if – is left
(a) switch between functions in a program associative and
(b) switch from one variable to another variable (a) * has precedence over *
(c) to choose from multiple possibilities which may arise (b) * has precedence over –
due to different values of a single variable (c) – has precedence over *
(d) to use switching variable (d) – has precedence over –
114. When a function is recursively called, all automatic variables 122. What is the output of this program?
(a) are initialized during each execution of the function 1. #include <iostream>
(b) are retained from the last execution 2. #include <functional>
(c) are maintained in a stack 3. #include <numeric>
(d) None of these
4. using namespace std;
115. For x and y are variables as declared below
double x = 0.005, y = – 0.01; 5. int myop (int x, int y)
what is the value of ceil (x + y), where ceil is a function to 6. {
compute ceiling of a number? 7. return x + y;
(a) 1 (b) 0 8. }
(c) 0.005 (d) 0.5
9. int main ()
116. The declarations
typedef float height [100]; 10. {
height men, women; 11. int val[] = {1, 2, 3, 5};
(a) define men and women as 100 element floating point 12. int result[7];
arrays 13. adjacent_difference (val, val + 7, result);
(b) define men and women as floating point variables
(c) define height, men and women as floating point 14. for (int i = 0; i < 4; i++)
variables 15. cout << result[i] <<’ ‘;
(d) are illegal 16. return 0;
117. A short integer occupies 2 bytes, an ordinary integer 4 bytes 17. }
and a long integer occupies 8 bytes of memory. (a) 1112 (b) 2111
If a structure is defined as (c) 1212 (d) None of these
struct TAB { 123. The C declaration
short a; int b [100];
int b; reserves ________ successive memory locations, each large
long c; enough to contain single integer.
}TABLE [10]; (a) 200 (b) 10,000
then total memory requirement for TABLE is (c) 100 (d) 10
(a) 14 (b) 140 124. Match List I with List II and select the correct answer from
(c) 40 (d) 24 the codes given below the lists:
118. If i, j, k are integer variable with values 1, 2, 3 respectively, List I List I
then what is the value of the expression A. m = malloc (5); m = NULL 1. Using doing long
((j + k) > (i + 5)) pointers
(a) 6 (b) 5 B. Free (n); n ® value = 5; 2. Using uninitialized
(c) 1 (d) 0 pointers
C. char* P, *P = ‘a’; 3. Lost memory
119. The expression a << 6 shifts all bits of a six places to the left.
Codes:
If a 0x6db7, then what is the value of a << 6?
A B C
(a) 0xa72b (b) 0xa2b (a) 1 2 3
(c) 0x6dc0 (d) 0x1111 (b) 3 1 2
120. The declaration (c) 3 2 1
union id { (d) 2 3 1
char colour [12]; 125. The average search time of hashing, with linear probing will
int size; } shirt, pant; be less if the load factor
denotes shirt and pant are variable of type id and (a) is for less than one (b) equals one
(a) each can have a value of colour and size (c) is for greater than one (d) None of these
(b) each can represent either a 12-character colour or a 126. argv is a/an
integer size at a time (a) array of character pointers
(c) shirt and pant are same as struct variables (b) pointer to an array of character pointers
(d) variable shirt and pant cannot be used simultaneously (c) array of strings
in a statement. (d) None of these
186
127. In the following declarations: Which stacks are possible:
typedef struct { (a) All possible stacks with A, B, C, D, E and F
char name [20]; (b) No possible stacks with A, B, C, D, E and F
char middlename [5]; (c) Exactly and only those stacks which can be produced
char surname [20]; with SI alone
} NAME (d) Twice as many stacks can be produced with SI alone
NAME class [20]; 134. Consider the following tree
class is 1
(a) an array of 20 characters only
(b) an array of 20 names where each name consists of a
name, middlename and surname 3
2
(c) a new type
(d) none of these
128. What would be the values of i, x and c if
scanf (“%3d, %5f, %c”, &i, &x, &c) 4 5 6 7
is executed with input data 10b 256, 875bT?
If the post order traversal gives ab – cd* + then the label of
(a) i = 10, b = 56.875, C = T
the nodes 1, 2, 3, .... will be
(b) i = 100, b = 256.87, C = T
(a) +, –, *, a, b, c, d (b) a, –, b, +, *, d
(c) i = 010, b = 256.87, C = ‘5’
(d) i = 10, b = 256.8, C = ‘7’ (c) a, b, c, d, d, –, *, + (d) –, a, b, +, *, c, d
129. The five items : A, B, C, D and E are pushed in a stack, one 135. Consider the following tree
after the other starting from A. The stack is popped four
times and each element is inserted in a queue. Then two 6
elements are deleted from the queue and pushed back on
the stack. Now one item is popped from the stack. The
popped item is 4 12
(a) A (b) B
30
(c) C (d) D
130. Which of the following is an illegal array definition?
(a) type COLOGNE: (LIME, PINE, MUSK, MENTHOL); 1 5 10
var a : array [COLOGNE] of REAL; 11
(b) var a : array [REAL] of REAL;
(c) var a : array [‘A’.. ‘Z’] of REAL; If this tree is used for sorting, then a new number 8 should
(d) var a : array [BOOLEAN] of REAL; be places as the
131. Which of the following assertions is most strongly satisfied (a) left child of the node labeled 30
at the point marked [1]? (b) right child of the node labeled 5
(a) list [j] < list [j + 1] for all j such that item £ j < n (c) right child of the node labeled 30
(b) list [j] < list [j + 1] for all j such that item < j £ n (d) left child of the node labeled 10
(c) list [j] £ list [j + 1] for all j such that item £ j < n 136. The number of possible binary search trees with 3 nodes is
(d) list [j] < list [j – 1] for all j such that 1 < j £ item
(a) 12 (b) 13
132. Using Pop (SI, Item), Push (SI, Item), Read (Item), Print (Item),
(c) 5 (d) 15
the variables SI (stack) and Item, and given the input file:
A, B, C, D, E, F, < EOF > 137. You want to check whether a given set of items is sorted.
Which stacks are possible? Which of the following sorting methods will be the most
(a) 5 A (b) 5 efficient if it is already is sorted order?
4 B 4 (a) Bubble sort (b) Selection sort
3 C 3 D (c) Insertion sort (d) Merge sort
2 D 2 A 138. As part of the maintenance work, you are entrusted with the
1 E 1 F work of rearranging the library books in a shelf in proper
(c) 5 (d) 5 order, at the end of each day. The ideal choice will be
4 4 (a) bubble sort (b) insertion sort
3 F 3 C (c) selection sort (d) heap sort
2 D 2 E 139. Which of the following algorithms solves the all-pair shortest
1 B 1 B path problem?
133. Using Pop (SI, Item), Push (SI, Item), Getlist (Item), Pop (S2, (a) Dijkstra’s algorithm (b) Floyd’s algorithm
Item), Push (S2, Item), and the variables S1, S2 (stacks with (c) Prim’s algorithm (d) Warshall’s algorithm
Top 1 and Top 2) and Item and given the input file: 140. Which of the following expressions accesses the (i, j)th entry
A, B, C, D, E, F, < EOF > of a (m × n) matrix stored in column major form?
(a) n × (i – 1) + j (b) m × (j – 1) + i
(c) m × (n – j) + j (d) n × (m – i) + j
187
141. Sparse matrices have
(a) many zero entries (b) many non-zero entries +
(c) higher dimension (d) none of the above – !
142. Consider the graph in figure –
– e
A C b
1. a = – b and e = 0
B D
2. a = – b and e = 1
3. a = b and e = 0
Which of the following is a valid topological sorting?
4. a = b and e = 1
(a) A B C D (b) B A C D
(a) 2 only (b) 3 and 4
(c) B A D C (d) A B D C
(c) 1 and 2 (d) 1 and 4
143. For merging two sorted lists of sizes m and n into a sorted
list of size m + n. Find out the time complexity of this merging 150. Unrestricted use of goto is harmful, because it
process. (a) makes debugging difficult
(a) O(m) (b) O(n) (b) increases the running time of programs
(c) O(m + n) (d) O(log(m) + log (n)) (c) increases memory requirement of programs
144. A binary tree has n leaf nodes. The maximum numbers of (d) results in the compiler generating longer machine code
nodes of degree 2 in this tree is 151. The maximum degree of any vertex in a simple graph with n
(a) log2 n (b) n – 1 vertices is
(c) n (d) 2n (a) n (b) n – 1
145. The postfix expression for the infix expression (c) n + 1 (d) 2n – 1
A + B* (C + D)/F + D*E is: 152. The recurrence relation that arises in relation with the
(a) AB + CD + *F/D + E* (b) ABCD + *F / + DE* + complexity of binary search is
(c) A*B + CD? F*DE ++ (d) F*DE++ (a) T(n) = T(n/2) + k, where k is a constant
146. Stack is useful for implementing (b) T(n) = 2T(n/2) + k, where k is a constant
(a) recursion (b) breadth first search (c) T(n) = T(n/2) + log(n)
(c) depth first search (d) both (a) and (c) (d) T(n) = T(n/2) + n
147. A machine took 200 sec to sort 200 names, using bubble NUMERICAL TYPE QUESTIONS
sort. In 800 sec, it can approximately sort 153. The expression 4 + 6 / 3 * 2 – 2 + 7% 3 evaluates to
(a) 400 names (b) 700 names 154. Consider the following program segment.
(c) 750 names (d) 800 names i = 6720; j =4 ;
148. Which of the following is useful in implementing heap sort? while (i%j) = = 0)
(a) Stack (b) Set {i = i/j;
(c) List (d) Queue j = j + 1;
149. The expression tree given in Fig. evaluates to 1, if }
On termination j will have the value
155. If 7 bits are used to store a character, the percentage
reduction of needed storage will be
156. Consider the following program fragment.
d = 0;
for (i = 1; i < 31; ++i)
188
for (j = 1; j < 31; ++k) while ((c = getchar( )) != EOF)
for (k = 1; k < 31; ++k) { if (isdigit(c))
if (((i + j + k) % 3) = = 0) push (c)
d = d + 1;
else if (c = = ‘+’) || (c = = ‘*’))
printf (“%d”, d);
{ m = pop( );
the output will be
n = pop( );
157. Suppose one character at a time comes as an input from a
are = (c = = ‘+’) ? n + m : n*m;
string of letters. There is an option either to (i) print the
incoming letter or to (ii) put the incoming letter on to a stack. push(r);
Also a letter from top of the stack can be popped out at any }
time and printed. The total number of total distinct words else if (c != ‘ ‘)
that can be formed out of a string of three letters in this flagError( );
fashion, is. Enter a value. }
158. #include<stdio.h> printf(“%c”, pop( ));
#define EOF -1 }
What is the output of the program for the following
void push(int); /* Push the argument on the stack */
input?
int pop(void); /* pop the top of the stack */ 52*332+*+
void flagError();
int main( )
{ int c, m, n, r;
189
PAST GATE QUESTIONS EXERCISE function and when the function foo (a, sum) is called
1. (a) a + b × c – d ^ e ^ f where a = 2048 and sum = 0 as per given conditions.
a+b×c–d^e f^ Then, the execution of the function takes in the following
a+b×c–def^ ^ manner.
a+bc×–d e f ^ ^ i) k= n % 10 => modulus operator will return the remainder.
abc× –d e f ^ ^ for example, if n=2048, then 2048 %10 will store the value
abc× +d e f ^ ^ 8 in k.
a b c × + d e f ^ ^– ii) j is declared as integer datatype in foo function.
the result is obtained. Therefore after division if the result contains decimal part,
2. (a) it will be truncated and only the integer part will be stored
3. (c) As given p is a single variable that is used to access the in j. For example if j=2048/10, (actual result = 204.8) then
queue and with the single variable it is not possible to 204 will be stored in j.
perform both the functions of enqueue and dequeue with iii) The sum variable declared in the main function will
a constant time since, insertion and deletion are not be used by the foo function.
operations that needs to be done from the opposite end 9. (a) We have to store frequencies of scores above 50. That is
of the queue rear and front respectively.
number of students having score 51, number of students
4. (b) The program undergoes normal execution upto line
having score 52 and so on. For that an array of size 50 is
number 7 since, no error is present til there but as soon
the best option.
as the execution goes to line 8 an error occurs as in this
the pointer s is assigned a character variable, i.e., p and 10. (b) Object Oriented Programming (OPP) is a programming
this assignment is not permissible in C language thus, paradigm. The language is object oriented as it use
the program produces a garbage value as an output or objects. Objects are the data structures that contain data
no output is returned. fields and methods together with their interactions.
5. (c) The iterations that the given code will undergo are: The main features of the Programming techniques are
From the given conditions we does not take into account 1. data abstraction
when n = 1 2. encapsulation
Iteration 1
N = 1 + 1 = 2 therefore, i = 2 3. modularity
Iteration 2 4. polymorphism
N = 2 + 2 = 4 therefore, i = 3 5. inheritance
Iteration 3 Therefore, the essential features are given by statements
N = 4 + 3 = 2 = 4 therefore, i = 4 (i) and (iv).
Hence, the value returned after three iterations is 7
11. (c) Languages needs declaration of any statement that we
When, i = 4 and it also fulfill the condition of n>=5
write before its use thus, the common property of both
6. (a) Inorder traversal of a BST always gives elements in
the languages is that both are declarative.
increasing order. Among all four options, (a) is the only
increasing order sequence. 12. (c) An abstract data type is a mathematical model for a certain
7. (c) Whenever the a function’s data type is not declared in class of data structures that have similar behaviour. An
the program, the default declaration is taken into abstract data type is indirectly defined by the operations
consideration. By default, the function foo in this is and mathematical constraints thus, is a user defined data
assumed to be of int type, then also it returns a double type, not a system defined, that can perform operations
type of value. This situation will generate compiler defined by it on that data.
warning due to this mismatch leading to unintended 13. (c) Syntax to declare pointer to a function =>datatype
results. (*pointer_variable)(list of arguments)
8. (d) sum has no use in foo(), it is there just to confuse. Function To make a pointer to a function =>pointer_variable =
foo() just prints all digits of a number. In main, there is function_name
one more printf statement after foo(), so one more 0 is
Note: don't use parenthesis of the function.
printed after all digits of n.
From the given code it is found that foo is a recursive To call (invoke) the function =>pointer_variable(list of
arguments)
190
14. (b) For the given code only the statements S2 and S3 are
a
valid and thus, are true. Since, the code may generate a
segmentation fault at runtime depending on the
arguments passed as the arguments are passed by c
b
reference and also the swap procedure is correctly
implemented. g
d e f
15. (d) Both functions work1 &work2 performs the same task,
therefore S1 is true. In the postorder traversal, the sequence is debfgca.
In S2 it is asking about improvement in performance i.e. 20. (d) We follow, the following steps to obtain the value of f(5)
reduction in CPU time. When compared work2 will reduce
f(5)
the CPU time, because in work1 a[i+2] is computed twice
but in work2 a[i+2] is computed once and stored in t2, r=5
and then t2 is used. When we consider the performance f(3) + 2 = 18
in terms of reduction in CPU time, S2 is correct.
16. (c) The condition (i) is true if the last inserted element in c[] f(2) + 5 = 16
is from a[] and condition (ii) is true if the last inserted
element is from b[]. f(1) + 5 = 11
17. (a) The order in which insert and delete operations are
performed matters here.
f(0) + 5 = 6
The best case: Insert and delete operations are performed
alternatively. In every delete operation, 2 pop and 1 push
operations are performed. So, total m+ n push (n push for 1
insert() and m push for delete()) operations and 2m pop 21. (a) The algorithm for evaluating any postfix expression is
operations are performed. fairly straightforward:
The worst case: First n elements are inserted and then m 1. While there are input tokens left
elements are deleted. In first delete operation, n + 1 pop o Read the next token from input.
operations and n push operation are performed. Other o If the token is a value
+ Push it onto the stack.
than first, in all delete operations, 1 pop operation is o Otherwise, the token is an operator
performed. So, total m + n pop operations and 2n push (operator here includes both operators, and functions).
operations are performed (n push for insert() and m push * It is known a priori that the operator takes n arguments.
for delete()) * If there are fewer than n values on the stack
18. (c) A node is a leaf node if both left and right child nodes of (Error) The user has not input sufficient values in the
expression.
it are NULL.
* Else, Pop the top n values from the stack.
1) If node is NULL then return 0. * Evaluate the operator, with the values as arguments.
2) Else If left and right child nodes are NULL return 1. * Push the returned results, if any, back onto the stack.
3) Else recursively calculate leaf count of the tree using 2. If there is only one value in the stack
below formula. o That value is the result of the calculation.
Leaf count of a tree = Leaf count of left subtree + 3. If there are more values in the stack
o (Error) The user input has too many values.
Leaf count of right subtree Let us run the above algorithm for the given expression.
First three tokens are values, so they are simply pushed.
After pushing 8, 2 and 3, the stack is as follows
8, 2, 3
When ^ is read, top two are popped and power(2^3) is
calculated
8, 8
When / is read, top two are popped and division(8/8) is
performed
1
Example Tree Next two tokens are values, so they are simply pushed.
Leaf count for the above tree is 3. After pushing 2 and 3, the stack is as follows
19. (a) The inorder traversal sequence is dbeafcg and the 1, 2, 3
preorder traversal sequence is abdecfg so, the tree is When * comes, top two are popped and multiplication is
performed.
1, 6
191
22. (d) From the statement j = j*2 in the code we get to know that binary max-heap.
j increases in power of 2’s. Let us say that this statement Thus, under given cases the tree obtained is.
execute x times then, according to the question for while
25
loop
2^x < = n
Therefore, x < = log2n 14 16
And also for termination of while loop there will be an
extra comparison required. Thus, total number of
13 10
comparisons = x + 1 8 12
= [log2n] + 2
23. (b) The function rearrange() exchanges data of every node 28. (d) Always a greater element is deleted from the binary heap
with its next node. It starts exchanging data from the first first. The answer of previous question gave the array as
node itself. [25, 14, 16, 13, 10, 12, 8]
24. (d) The option chosen is So, when the greatest element, i.e., 25 is deleted the array
?1 is ((c = getchar ( ))! = ‘\n’) becomes [14, 16, 13, 10, 12, 8]
?2 is putchar (c); And next after second deletion the array becomes [14,
Because the operator ‘1=’ has higher priority than ‘=’ 13, 10, 12, 8]
operator so according to this C = getchar () should be Thus, the procedure for the obtaining the final tree is as
contained in brackets and when the string is reversed follows.
then the function putchar (c) is used so that the characters Replacing 25 with After heapifying
can be printed.
25. (b) The program gets executed in the following manner 12 16
Graphical Representation
c a 2000 14 14 12
4 b 1000 16
1000 2000 3000
13 10 8 13 10 8