DXC Interview Questions
DXC Interview Questions
Note: Round2: This is a mix of Technical Interview and HR Round. Candidates were asked
general questions like “Tell me about yourself” ,” What are your strengths and weaknesses?” ,
“Why do you think you are fit for this role ?” etc.
The rest were technical questions mostly based on OOPS, Ds and Algo, and technologies and
projects mentioned in resume. They might ask you to write a code in the editor
available.Prepare well on skills in resume and contents mentioned below are most asked
interview questions and it is just for your reference.have look at section-9 for sample
interview of DXC
Contents:
Section 1:OOPS based questions
Section 2: Data Structures interview questions
1
• Even very big software can be easily written and managed easily using OOPs.
1. Imperative Programming Paradigm: Imperative programming focuses on HOW to execute program logic and
defines control flow as statements that change a program state. This can be further classified as:
a) Procedural Programming Paradigm: Procedural programming specifies the steps a program must take to reach
the desired state, usually read in order from top to bottom.
b) Object-Oriented Programming or OOP: Object-oriented programming (OOP) organizes programs as objects, that
contain some data and have some behavior.
c) Parallel Programming: Parallel programming paradigm breaks a task into subtasks and focuses on executing them
simultaneously at the same time.
2. Declarative Programming Paradigm: Declarative programming focuses on WHAT to execute and defines
program logic, but not a detailed control flow. Declarative paradigm can be further classified into:
a) Logical Programming Paradigm: Logical programming paradigm is based on formal logic, which refers to a set of
sentences expressing facts and rules about how to solve a problem
b) Functional Programming Paradigm: Functional programming is a programming paradigm where programs are
constructed by applying and composing functions.
c) Database Programming Paradigm: Database programming model is used to manage data and information
structured as fields, records, and files.
2
• Polymorphism
• Data Abstraction
One can visualize Encapsulation as the method of putting everything that is required to do the job, inside a capsule
and presenting that capsule to the user. What it means is that by Encapsulation, all the necessary data and methods
are bind together and all the unnecessary details are hidden to the normal user. So Encapsulation is the process of
binding data members and methods of a program together to do a specific job, without revealing unnecessary
details.
1) Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting access to any
member of an object.
3
2) Data binding: Encapsulation is the process of binding the data members and the methods together as a whole,
as a class.
In OOPs, Polymorphism refers to the process by which some code, data, method, or object behaves differently
under different circumstances or contexts. Compile-time polymorphism and Run time polymorphism are the two
types of polymorphisms in OOPs languages.
Compile Time Polymorphism: Compile time polymorphism, also known as Static Polymorphism, refers to the type of
Polymorphism that happens at compile time. What it means is that the compiler decides what shape or value has to
be taken by the entity in the picture.
Example:
// In this program, we will see how multiple functions are created with t
he same name, // but the compiler decides which function to call easily a
t the compile time itself.class CompileTimePolymorphism{
// 1st method with name add
public int add(int x, int y){
return x+y;
}
// 2nd method with name add
public int add(int x, int y, int z){
return x+y+z;
}
// 3rd method with name add
public int add(double x, int y){
return (int)x+y;
}
// 4th method with name add
public int add(int x, double y){
return x+(int)y;
}
}class Test{
public static void main(String[] args){
CompileTimePolymorphism demo= new CompileTimePolymorphism();
4
// In the below statement, the Compiler looks at the argument types and
decides to call method 1
System.out.println(demo.add( 2,3));
Runtime Polymorphism: Runtime polymorphism, also known as Dynamic Polymorphism, refers to the type of
Polymorphism that happens at the run time. What it means is it can't be decided by the compiler. Therefore what
shape or value has to be taken depends upon the execution. Hence the name Runtime Polymorphism.
Example:
class AnyVehicle{
public void move(){
System.out.println(“Any vehicle should move!!”);
}
}class Bike extends AnyVehicle{
public void move(){
System.out.println(“Bike can move too!!”);
}
}class Test{
public static void main(String[] args){
AnyVehicle vehicle = new Bike();
// In the above statement, as you can see, the object vehicle is of typ
e AnyVehicle
// But the output of the below statement will be “Bike can move to
o!!”,
// because the actual implementation of object ‘vehicle’ is decided dur
ing runtime vehicle.move();
vehicle = new AnyVehicle();
// Now, the output of the below statement will be “Any vehicle should m
ove!!”,
vehicle.move();
5
}
}
As the method to call is determined at runtime, as shown in the above code, this is called runtime polymorphism.
6
{
int x;
ABC()
{
x = 0;
}
}
Parameterized constructor: The constructors that take some arguments are known as parameterized constructors.
class ABC
{
int x;
ABC(int y)
{
x = y;
}
}
Copy constructor: A copy constructor is a member function that initializes an object using another object of the
same class.
class ABC
{
int x;
ABC(int y)
{
x = y;
}
// Copy constructor
ABC(ABC abc)
{
x = abc.x;
}
}
7
22. What is a destructor?
Contrary to constructors, which initialize objects and specify space for them, Destructors are also special methods.
But destructors free up the resources and memory occupied by an object. Destructors are automatically called when
an object is being destroyed.
23. Are class and structure the same? If not, what's the difference between a
class and a structure?
No, class and structure are not the same. Though they appear to be similar, they have differences that make them
apart. For example, the structure is saved in the stack memory, whereas the class is saved in the heap memory. Also,
Data Abstraction cannot be achieved with the help of structure, but with class, Abstraction is majorly used.
8
29. What is an interface?
An interface refers to a special type of class, which contains methods, but not their definition. Only the declaration
of methods is allowed inside an interface. To use an interface, you cannot create objects. Instead, you need to
implement that interface and define the methods for their implementation.
9
An exception can be considered as a special event, which is raised during the execution of a program at runtime,
that brings the execution to a halt. The reason for the exception is mainly due to a position in the program, where
the user wants to do something for which the program is not specified, like undesirable input.
40. Can we run a Java application without implementing the OOPs concept?
No. Java applications are based on Object-oriented programming models or OOPs concept, and hence they cannot
be implemented without it.
However, on the other hand, C++ can be implemented without OOPs, as it also supports the C-like structural
programming model.
The data structure is a way that specifies how to organize and manipulate the data. It also defines the relationship
between them. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data Structures are the
central part of many computer science algorithms as they enable the programmers to handle the data in an efficient
way
Linear Data Structure: A data structure is called linear if all of its elements are arranged in the sequential order. In
linear data structures, the elements are stored in a non-hierarchical way where each item has the successors and
predecessors except the first and last element.
2.6M
Prime Ministers of India | List of Prime Minister of India (1947-2020)
Non-Linear Data Structure: The Non-linear data structure does not form a sequence i.e. each item or element is
connected with two or more other items in a non-linear arrangement. The data elements are not arranged in the
sequential structure.
10
3) List the area of applications of Data Structure.
Data structures are applied extensively in the following areas of computer science:
o Compiler Design,
o Operating System,
o Database Management System,
o Statistical analysis package,
o Numerical Analysis,
o Graphics,
o Artificial Intelligence,
o Simulation
The main difference between file structure and storage structure is based on memory area that is being accessed.
Storage structure: It is the representation of the data structure in the computer memory.
File structure: It is the representation of the storage structure in the auxiliary memory.
5) List the data structures which are used in RDBMS, Network Data Modal, and
Hierarchical Data Model.
Stack data structure is used in recursion due to its last in first out nature. Operating system maintains the stack in
order to save the iteration variables at each function call
7) What is a Stack?
11
Stack is an ordered list in which, insertion and deletion can be performed only at one end that is called the top. It is
a recursive data structure having pointer to its top element. The stack is sometimes called as Last-In-First-Out (LIFO)
list i.e. the element which is inserted first in the stack will be deleted last from the stack.
8) List the area of applications where stack data structure can be used?
o Expression evaluation
o Backtracking
o Memory Management
o Function calling and return
o Push Operations
o Pop Operations
o Peek Operations
PUSH and POP operations specify how data is stored and retrieved in a stack.
PUSH: PUSH specifies that data is being "inserted" into the stack.
POP: POP specifies data retrieval. It means that data is being deleted from the stack.
12) Write the steps involved in the insertion and deletion of an element in the
stack.
Push:
o Increment the variable top so that it can refer to the next memory allocation
o Copy the item to the at the array index value equal to the top
o Repeat step 1 and 2 until stack overflows
Pop:
12
o Store the topmost element into the an another variable
o Decrement the value of the top
o Return the topmost element
An expression in which operators follow the operands is known as postfix expression. The main benefit of this form
is that there is no need to group sub-expressions in parentheses or to consider operator precedence.
AB+CD-*
16)What is an array?
Arrays are defined as the collection of similar types of data items stored at contiguous memory locations. It is the
simplest data structure in which each data element can be randomly accessed by using its index number.
It can be done by using an indexed loop such that the counter runs from 0 to the array size minus one. In this
manner, you can reference all the elements in sequence by using the loop counter as the array subscript.
The multidimensional array can be defined as the array of arrays in which, the data is stored in tabular form consists
of rows and columns. 2D arrays are created to implement a relational database lookalike data structure. It provides
ease of holding the bulk of data at once which can be passed to any number of functions wherever required.
13
19) How are the elements of a 2D array are stored in the memory?
There are two techniques by using which, the elements of a 2D array can be stored in the memory.
o Row-Major Order: In row-major ordering, all the rows of the 2D array are stored into the memory
contiguously. First, the 1st row of the array is stored into the memory completely, then the 2nd row of the
array is stored into the memory completely and so on till the last row.
o Column-Major Order: In column-major ordering, all the columns of the 2D array are stored into the
memory contiguously. first, the 1st column of the array is stored into the memory completely, then the 2nd
row of the array is stored into the memory completely and so on till the last column of the array.
20) Calculate the address of a random element present in a 2D array, given base
address as BA.
Row-Major Order: If array is declared as a[m][n] where m is the number of rows while n is the number of columns,
then address of an element a[i][j] of the array stored in row major order is calculated as,
Address(a[i][j]) = B. A. + (i * n + j) * size
Column-Major Order: If array is declared as a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in column major order is calculated as
Linked List is the collection of randomly stored data objects called nodes. In Linked List, each node is linked to its
adjacent node through a pointer. A node contains two fields, i.e. Data Field and Link Field.
A linked list is considered both linear and non-linear data structure depending upon the situation.
o The size of a linked list can be incremented at runtime which is impossible in the case of the array.
14
o The List is not required to be contiguously present in the main memory, if the contiguous space is not
available, the nodes can be stored anywhere in the memory connected through the links.
o The List is dynamically stored in the main memory and grows as per the program demand while the array is
statically stored in the main memory, size of which must be declared at compile time.
o The number of elements in the linked list are limited to the available memory space while the number of
elements in the array is limited to the size of an array.
24) Write the syntax in C to create a node in the singly linked list.
1. struct node
2. {
3. int data;
4. struct node *next;
5. };
6. struct node *head, *ptr;
7. ptr = (struct node *)malloc(sizeof(struct node));
25) If you are using C language to implement the heterogeneous linked list, what
pointer type should be used?
The heterogeneous linked list contains different data types, so it is not possible to use ordinary pointers for this. For
this purpose, you have to use a generic pointer type like void pointer because the void pointer is capable of storing
a pointer to any type.
The doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as
the next node in the sequence. In a doubly linked list, a node consists of three parts:
o node data
o pointer to the next node in sequence (next pointer)
o pointer to the previous node (previous pointer).
27) Write the C program to insert a node in circular singly list at the beginning.
1. #include<stdio.h>
2. #include<stdlib.h>
15
3. void beg_insert(int);
4. struct node
5. {
6. int data;
7. struct node *next;
8. };
9. struct node *head;
10. void main ()
11. {
12. int choice,item;
13. do
14. {
15. printf("\nEnter the item which you want to insert?\n");
16. scanf("%d",&item);
17. beg_insert(item);
18. printf("\nPress 0 to insert more ?\n");
19. scanf("%d",&choice);
20. }while(choice == 0);
21. }
22. void beg_insert(int item)
23. {
24.
25. struct node *ptr = (struct node *)malloc(sizeof(struct node));
26. struct node *temp;
27. if(ptr == NULL)
28. {
29. printf("\nOVERFLOW");
30. }
31. else
32. {
33. ptr -> data = item;
34. if(head == NULL)
35. {
36. head = ptr;
37. ptr -> next = head;
38. }
39. else
40. {
41. temp = head;
42. while(temp->next != head)
16
43. temp = temp->next;
44. ptr->next = head;
45. temp -> next = ptr;
46. head = ptr;
47. }
48. printf("\nNode Inserted\n");
49. }
50.
51. }
52.
A queue can be defined as an ordered list which enables insert operations to be performed at one end called REAR
and delete operations to be performed at another end called FRONT.
o Queues are widely used as waiting lists for a single shared resource like a printer, disk, CPU.
o Queues are used in the asynchronous transfer of data (where data is not being transferred at the same rate
between two processes) for eg. pipes, file IO, sockets.
o Queues are used as buffers in most of the applications like MP3 media player, CD player, etc.
o Queues are used to maintain the playlist in media players to add and remove the songs from the play-list.
o Queues are used in operating systems for handling interrupts.
o Memory Wastage: The space of the array, which is used to store queue elements, can never be reused to
store the elements of that queue because the elements can only be inserted at front end and the value of
front might be so high so that, all the space before that, can never be filled.
o Array Size: There might be situations in which, we may need to extend the queue to insert more elements
if we use an array to implement queue, It will almost be impossible to extend the array size, therefore
deciding the correct array size is always a problem in array implementation of queue.
31) What are the scenarios in which an element can be inserted into the circular
queue?
17
o If (rear + 1)%maxsize = front, the queue is full. In that case, overflow occurs and therefore, insertion can not
be performed in the queue.
o If rear != max - 1, the rear will be incremented to the mod(maxsize) and the new value will be inserted at
the rear end of the queue.
o If front != 0 and rear = max - 1, it means that queue is not full therefore, set the value of rear to 0 and insert
the new element there.
Dequeue (also known as double-ended queue) can be defined as an ordered set of elements in which the insertion
and deletion can be performed at both the ends, i.e. front and rear.
33) What is the minimum number of queues that can be used to implement a
priority queue?
Two queues are needed. One queue is used to store the data elements, and another is used for storing priorities.
The Tree is a recursive data structure containing the set of one or more data nodes where one node is designated as
the root of the tree while the remaining nodes are called as the children of the root. The nodes other than the root
node are partitioned into the nonempty sets where each one of them is to be called sub-tree.
o General Tree
o Forests
o Binary Tree
o Binary Search Tree
o Expression Tree
o Tournament Tree
A binary Tree is a special type of generic tree in which, each node can have at most two children. Binary tree is
generally partitioned into three disjoint subsets, i.e. the root of the node, left sub-tree and Right binary sub-tree.
18
37) Write the C code to perform in-order traversal on a binary tree.
39) Which data structure suits the most in the tree construction?
40) Which data structure suits the most in the tree construction?
41) Write the recursive C function to count the number of nodes present in a
binary tree.
19
8. return (1+l+r);
9. }
10. else
11. {
12. return 0;
13. }
14. }
43) How can AVL Tree be useful in all the operations as compared to Binary
search tree?
AVL tree controls the height of the binary search tree by not letting it be skewed. The time taken for all operations in
a binary search tree of height h is O(h). However, it can be extended to O(n) if the BST becomes skewed (i.e. worst
case). By limiting this height to log n, AVL tree imposes an upper bound on each operation to be O(log n) where n is
the number of nodes.
A B tree of order m contains all the properties of an M way tree. In addition, it contains the following properties.
20
45) What are the differences between B tree and B+ tree?
SN B Tree B+ Tree
1 Search keys cannot repeatedly be stored. Redundant search keys can be present.
2 Data can be stored in leaf nodes as well as internal nodes Data can only be stored on the leaf nodes.
3 Searching for some data is a slower process since data Searching is comparatively faster as data can only
can be found on internal nodes as well as on the leaf be found on the leaf nodes.
nodes.
4 Deletion of internal nodes is so complicated and time- Deletion will never be a complexed process since
consuming. element will always be deleted from the leaf nodes.
5 Leaf nodes cannot be linked together. Leaf nodes are linked together to make the search
operations more efficient.
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G) represents the
set of edges which are used to connect these vertices. A graph can be seen as a cyclic tree, where the vertices
(Nodes) maintain any complex relationship among them instead of having parent-child relations.
o Path: A Path is the sequence of adjacent vertices connected by the edges with no restrictions.
o Cycle: A Cycle can be defined as the closed path where the initial vertex is identical to the end vertex. Any
vertex in the path can not be visited twice
o Circuit: A Circuit can be defined as the closed path where the intial vertex is identical to the end vertex. Any
vertex may be repeated.
49) Mention the data structures which are used in graph implementation.
21
o In sequential representation, Adjacency matrix is used.
o In Linked representation, Adjacency list is used.
50) Which data structures are used in BFS and DFS algorithm?
o Graphs are used in circuit networks where points of connection are drawn as vertices and component wires
become the edges of the graph.
o Graphs are used in transport networks where stations are drawn as vertices and routes become the edges
of the graph.
o Graphs are used in maps that draw cities/states/regions as vertices and adjacency relations as edges.
o Graphs are used in program flow analysis where procedures or modules are treated as vertices and calls to
these procedures are drawn as edges of the graph.
Binary Search algorithm is used to search an already sorted list. The algorithm follows divide and conqer approach
52) What are the advantages of Binary search over linear search?
There are relatively less number of comparisons in binary search than that in linear search. In average case, linear
search takes O(n) time to search a list of n elements while Binary search takes O(log n) time to search a list of n
elements.
22
55) List Some Applications of Multilinked Structures?
o Sparse matrix,
o Index generation.
C is a mid-level and procedural programming language. The Procedural programming language is also known as
the structured programming language is a technique in which large programs are broken down into smaller
modules, and each module uses structured code. This technique minimizes error and misinterpretation. More details.
C is known as a mother language because most of the compilers and JVMs are written in C language. Most of the
languages which are developed after C language has borrowed heavily from it like C++, Python, Rust, javascript, etc.
It introduces new core concepts like arrays, functions, file handling which are used in these languages. More details.
C is called a mid-level programming language because it binds the low level and high -level programming language.
We can use C language as a System programming to develop the operating system as well as an Application
programming to generate menu driven customer driven billing system. More details.
23
4) Who is the founder of C language?
o Simple: C is a simple language because it follows the structured approach, i.e., a program is broken into
parts
o Portable: C is highly portable means that once the program is written can be run on any machine with little
or no modifications.
o Mid Level: C is a mid-level programming language as it combines the low- level language with the features
of the high-level language.
o Structured: C is a structured language as the C program is broken into parts.
o Fast Speed: C language is very fast as it uses a powerful set of data types and operators.
o Memory Management: C provides an inbuilt memory function that saves the memory and improves the
efficiency of our program.
o Extensible: C is an extensible language as it can adopt new features in the future.
More details.
printf(): The printf() function is used to print the integer, character, float and string values on to the screen.
scanf(): The scanf() function is used to take input from the user.
More details.
24
8) What is the difference between the local variable and global variable in C?
Following are the differences between a local variable and global variable:
Declaration A variable which is declared inside function or A variable which is declared outside function
block is known as a local variable. or block is known as a global variable.
Scope The scope of a variable is available within a The scope of a variable is available
function in which they are declared. throughout the program.
Access Variables can be accessed only by those Any statement in the entire program can
statements inside a function in which they are access variables.
declared.
Life Life of a variable is created when the function block Life of a variable exists until the program is
is entered and destroyed on its exit. executing.
Storage Variables are stored in a stack unless specified. The compiler decides the storage location of
a variable.
More details.
o A variable which is declared as static is known as a static variable. The static variable retains its value
between multiple function calls.
o Static variables are used because the scope of the static variable is available in the entire program. So, we
can access a static variable anywhere in the program.
o The static variable is initially initialized to zero. If we update the value of a variable, then the updated value
is assigned.
o The static variable is used as a common value which is shared by all the methods.
o The static variable is initialized only once in the memory heap to reduce the memory usage.
More details.
o C functions are used to avoid the rewriting the same code again and again in our program.
o C functions can be called any number of times from any place of our program.
o When a program is divided into functions, then any part of our program can easily be tracked.
o C functions provide the reusability concept, i.e., it breaks the big task into smaller tasks so that it makes the
C program more understandable.
25
More details.
11) What is the difference between call by value and call by reference in C?
Following are the differences between a call by value and call by reference are:
Description When a copy of the value is passed to the function, When a copy of the value is passed to the
then the original value is not modified. function, then the original value is modified.
Memory Actual arguments and formal arguments are Actual arguments and formal arguments are
location created in separate memory locations. created in the same memory location.
Safety In this case, actual arguments remain safe as they In this case, actual arguments are not reliable, as
cannot be modified. they are modified.
Arguments The copies of the actual arguments are passed to The addresses of actual arguments are passed to
the formal arguments. their respective formal arguments.
1. #include <stdio.h>
2. void change(int,int);
3. int main()
4. {
5. int a=10,b=20;
6. change(a,b); //calling a function by passing the values of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int x,int y)
13. {
14. x=13;
15. y=17;
16. }
Output:
Value of a is: 10
Value of b is: 20
26
Example of call by reference:
1. #include <stdio.h>
2. void change(int*,int*);
3. int main()
4. {
5. int a=10,b=20;
6. change(&a,&b); // calling a function by passing references of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int *x,int *y)
13. {
14. *x=13;
15. *y=17;
16. }
Output:
Value of a is: 13
Value of b is: 17
More details.
When a function calls itself, and this process is known as recursion. The function that calls itself is known as a
recursive function.
1. Winding phase
2. Unwinding phase
Winding phase: When the recursive function calls itself, and this phase ends when the condition is reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to the original
call.
Example of recursion
27
1. #include <stdio.h>
2. int calculate_fact(int);
3. int main()
4. {
5. int n=5,f;
6. f=calculate_fact(n); // calling a function
7. printf("factorial of a number is %d",f);
8. return 0;
9. }
10. int calculate_fact(int a)
11. {
12. if(a==1)
13. {
14. return 1;
15. }
16. else
17. return a*calculate_fact(a-1); //calling a function recursively.
18. }
Output:
More details.
An Array is a group of similar types of elements. It has a contiguous memory location. It makes the code optimized,
easy to traverse and easy to sort. The size and type of arrays cannot be changed after its declaration.
o One-dimensional array: One-dimensional array is an array that stores the elements one after the another.
Syntax:
1. data_type array_name[size];
o Multidimensional array: Multidimensional array is an array that contains more than one array.
Syntax:
28
1. data_type array_name[size];
Example of an array:
1. #include <stdio.h>
2. int main()
3. {
4. int arr[5]={1,2,3,4,5}; //an array consists of five integer values.
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ",arr[i]);
8. }
9. return 0;
10. }
Output:
1 2 3 4 5
More details.
A pointer is a variable that refers to the address of a value. It makes the code optimized and makes the performance
fast. Whenever a variable is declared inside a program, then the system allocates some memory to a variable. The
memory contains some address number. The variables that hold this address number is known as the pointer
variable.
For example:
1. Data_type *p;
The above syntax tells that p is a pointer variable that holds the address number of a given data type value.
Example of pointer
1. #include <stdio.h>
2. int main()
3. {
4. int *p; //pointer of type integer.
29
5. int a=5;
6. p=&a;
7. printf("Address value of 'a' variable is %u",p);
8. return 0;
9. }
Output:
More details.
o Accessing array elements: Pointers are used in traversing through an array of integers and strings. The
string is an array of characters which is terminated by a null character '\0'.
o Dynamic memory allocation: Pointers are used in allocation and deallocation of memory during the
execution of a program.
o Call by Reference: The pointers are used to pass a reference of a variable to other function.
o Data Structures like a tree, graph, linked list, etc.: The pointers are used to construct different data
structures like tree, graph, linked list, etc.
A pointer that doesn't refer to any address of value but NULL is known as a NULL pointer. When we assign a '0'
value to a pointer of any type, then it becomes a Null pointer.
More details.
A pointer which can access all the 16 segments (whole residence memory) of RAM is known as far pointer. A far
pointer is a 32-bit pointer that obtains information outside the memory in a given section.
o If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory occupied
by the first pointer while the first pointer still points to that memory location, the first pointer will be known
as a dangling pointer. This problem is known as a dangling pointer problem.
30
o Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer
points to the deallocated memory.
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. }
In the above example, initially memory is allocated to the pointer variable ptr, and then the memory is deallocated
from the pointer variable. Now, pointer variable, i.e., ptr becomes a dangling pointer.
The problem of a dangling pointer can be overcome by assigning a NULL value to the dangling pointer. Let's
understand this through an example:
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. ptr=NULL; //Now, ptr is no longer a dangling pointer.
7. }
In the above example, after deallocating the memory from a pointer variable, ptr is assigned to a NULL value. This
means that ptr does not point to any memory location. Therefore, it is no longer a dangling pointer.
In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The pointer to pointer
is a chain of pointers. Generally, the pointer contains the address of a variable. The pointer to pointer contains the
address of a first pointer. Let's understand this concept through an example:
1. #include <stdio.h>
2. int main()
3. {
31
4. int a=10;
5. int *ptr,**pptr; // *ptr is a pointer and **pptr is a double pointer.
6. ptr=&a;
7. pptr=&ptr;
8. printf("value of a is:%d",a);
9. printf("\n");
10. printf("value of *ptr is : %d",*ptr);
11. printf("\n");
12. printf("value of **pptr is : %d",**pptr);
13. return 0;
14. }
In the above example, pptr is a double pointer pointing to the address of the ptr variable and ptr points to the
address of 'a' variable.
More details.
o In case of static memory allocation, memory is allocated at compile time, and memory can't be increased
while executing the program. It is used in the array.
o The lifetime of a variable in static memory is the lifetime of a program.
o The static memory is allocated using static keyword.
o The static memory is implemented using stacks or heap.
o The pointer is required to access the variable present in the static memory.
o The static memory is faster than dynamic memory.
o In static memory, more memory space is required to store the variable.
1. For example:
2. int a[10];
The above example creates an array of integer type, and the size of an array is fixed, i.e., 10.
More details.
o In case of dynamic memory allocation, memory is allocated at runtime and memory can be increased while
executing the program. It is used in the linked list.
o The malloc() or calloc() function is required to allocate the memory at the runtime.
32
o An allocation or deallocation of memory is done at the execution time of a program.
o No dynamic pointers are required to access the memory.
o The dynamic memory is implemented using data segments.
o Less memory space is required to store the variable.
1. For example
2. int *p= malloc(sizeof(int)*10);
More details.
22) What functions are used for dynamic memory allocation in C language?
1. malloc()
o The malloc() function is used to allocate the memory during the execution of the program.
o It does not initialize the memory but carries the garbage value.
o It returns a null pointer if it could not be able to allocate the requested space.
Syntax
o The calloc() is same as malloc() function, but the difference only is that it initializes the memory
with zero value.
Syntax
o The realloc() function is used to reallocate the memory to the new size.
o If sufficient space is not available in the memory, then the new block is allocated to accommodate
the existing data.
Syntax
33
1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.
4. free():The free() function releases the memory allocated by either calloc() or malloc() function.
Syntax
The above syntax releases the memory from a pointer variable ptr.
More details.
calloc() malloc()
Description The malloc() function allocates a single block The calloc() function allocates multiple blocks of
of requested memory. requested memory.
Initialization It initializes the content of the memory to It does not initialize the content of memory, so it
zero. carries the garbage value.
Return value It returns a pointer pointing to the allocated It returns a pointer pointing to the allocated
memory. memory.
More details.
o The structure is a user-defined data type that allows storing multiple types of data in a single unit. It
occupies the sum of the memory of all members.
o The structure members can be accessed only through structure variables.
o Structure variables accessing the same structure but the memory allocated for each variable will be different.
Syntax of structure
1. struct structure_name
2. {
34
3. Member_variable1;
4. Member_variable2
5. .
6. .
7. }[structure variables];
1. #include <stdio.h>
2. struct student
3. {
4. char name[10]; // structure members declaration.
5. int age;
6. }s1; //structure variable
7. int main()
8. {
9. printf("Enter the name");
10. scanf("%s",s1.name);
11. printf("\n");
12. printf("Enter the age");
13. scanf("%d",&s1.age);
14. printf("\n");
15. printf("Name and age of a student: %s,%d",s1.name,s1.age);
16. return 0;
17. }
Output:
More details.
o The union is a user-defined data type that allows storing multiple types of data in a single unit. However, it
doesn't occupy the sum of the memory of all members. It holds the memory of the largest member only.
o In union, we can access only one variable at a time as it allocates one common space for all the members of
a union.
35
Syntax of union
1. union union_name
2. {
3. Member_variable1;
4. Member_variable2;
5. .
6. .
7. Member_variable n;
8. }[union variables];
1. #include<stdio.h>
2. union data
3. {
4. int a; //union members declaration.
5. float b;
6. char ch;
7. };
8. int main()
9. {
10. union data d; //union variable.
11. d.a=3;
12. d.b=5.6;
13. d.ch='a';
14. printf("value of a is %d",d.a);
15. printf("\n");
16. printf("value of b is %f",d.b);
17. printf("\n");
18. printf("value of ch is %c",d.ch);
19. return 0;
20. }
Output:
value of a is 1085485921
value of b is 5.600022
value of ch is a
36
In the above example, the value of a and b gets corrupted, and only variable ch shows the actual output. This is
because all the members of a union share the common memory space. Hence, the variable ch whose value is
currently updated.
More details.
In C, every local variable of a function is known as an automatic (auto) variable. Variables which are declared inside
the function block are known as a local variable. The local variables are also known as an auto variable. It is optional
to use an auto keyword before the data type of a variable. If no value is stored in the local variable, then it consists
of a garbage value.
The sprintf() stands for "string print." The sprintf() function does not print the output on the console screen. It
transfers the data to the buffer. It returns the total number of characters present in the string.
Syntax
1. #include<stdio.h>
2. int main()
3. {
4. char a[20];
5. int n=sprintf(a,"javaToint");
6. printf("value of n is %d",n);
7. return 0;}
Output:
value of n is 9
But, if we use #define, we can compile and run a C program without using the main() function. For example:
37
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
More details.
The Token is an identifier. It can be constant, keyword, string literal, etc. A token is the smallest individual unit in a
program. C has the following tokens:
The argument passed to the main() function while executing the program is known as command line argument. For
example:
The ANSI stands for " American National Standard Institute." It is an organization that maintains the broad range of
disciplines including photographic film, computer languages, data encoding, mechanical parts, safety and more.
The getch() function reads a single character from the keyboard. It doesn't use any buffer, so entered data will not
be displayed on the output screen.
38
The getche() function reads a single character from the keyword, but data is displayed on the output screen. Press
Alt+f5 to see the entered character.
1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5.
6. char ch;
7. printf("Enter a character ");
8. ch=getch(); // taking an user input without printing the value.
9. printf("\nvalue of ch is %c",ch);
10. printf("\nEnter a character again ");
11. ch=getche(); // taking an user input and then displaying it on the screen.
12. printf("\nvalue of ch is %c",ch);
13. return 0;
14. }
Output:
Enter a character
value of ch is a
Enter a character again a
value of ch is a
In the above example, the value entered through a getch() function is not displayed on the screen while the value
entered through a getche() function is displayed on the screen.
The new line escape sequence is represented by "\n". It inserts a new line on the output screen.
More details.
34) Who is the main contributor in designing the C language after Dennis Ritchie?
Brain Kernighan.
39
35) What is the difference between near, far and huge pointers?
A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit selector. When you
perform pointer arithmetic on the far pointer, the selector is not modified, but in case of a huge pointer, it can be
modified.
These are the non-standard keywords and implementation specific. These are irrelevant in a modern platform.
The typecasting is a process of converting one data type into another is known as typecasting. If we want to store
the floating type value to an int type, then we will convert the data type into another data type explicitly.
Syntax
1. (type_name) expression;
38) What are the functions to open and close the file in C language?
The fopen() function is used to open file whereas fclose() is used to close file.
Yes, by holding the base address of array into a pointer, we can access the array using a pointer.
A loop running continuously for an indefinite number of times is called the infinite loop.
1. for(;;){
40
2. //code to be executed
3. }
1. while(1){
2. //code to be executed
3. }
1. do{
2. //code to be executed
3. }while(1);
1. #include<stdio.h>
2. void main(){
3. if(printf("hello world")){} // It prints the ?hello world? on the screen.
4. }
More details.
42) Write a program to swap two numbers without using the third variable?
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int a=10, b=20; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Before swap a=%d b=%d",a,b);
8.
9. a=a+b;//a=30 (10+20)
10. b=a-b;//b=10 (30-20)
11. a=a-b;//a=20 (30-10)
41
12.
13. printf("\nAfter swap a=%d b=%d",a,b);
14. getch();
15. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n1=0,n2=1,n3,i,number;
6. clrscr();
7. printf("Enter the number of elements:");
8. scanf("%d",&number);
9. printf("\n%d %d",n1,n2);//printing 0 and 1
10.
11. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
12. {
13. n3=n1+n2;
14. printf(" %d",n3);
15. n1=n2;
16. n2=n3;
17. }
18. getch();
19. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void printFibonacci(int n) // function to calculate the fibonacci series of a given number.
4. {
5. static int n1=0,n2=1,n3; // declaration of static variables.
6. if(n>0){
7. n3 = n1 + n2;
42
8. n1 = n2;
9. n2 = n3;
10. printf("%d ",n3);
11. printFibonacci(n-1); //calling the function recursively.
12. }
13. }
14. void main(){
15. int n;
16. clrscr();
17. printf("Enter the number of elements: ");
18. scanf("%d",&n);
19. printf("Fibonacci Series: ");
20. printf("%d %d ",0,1);
21. printFibonacci(n-2);//n-2 because 2 numbers are already printed
22. getch();
23. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. int n,i,m=0,flag=0; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("Enter the number to check prime:");
8. scanf("%d",&n);
9. m=n/2;
10. for(i=2;i<=m;i++)
11. {
12. if(n%i==0)
13. {
14. printf("Number is not prime");
15. flag=1;
16. break; //break keyword used to terminate from the loop.
17. }
18. }
19. if(flag==0)
43
20. printf("Number is prime");
21. getch(); //It reads a character from the keyword.
22. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n,r,sum=0,temp;
6. clrscr();
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=(sum*10)+r;
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("palindrome number ");
18. else
19. printf("not palindrome");
20. getch();
21. }
More details.
47) Write a program to print factorial of given number without using recursion?
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int i,fact=1,number;
5. clrscr();
6. printf("Enter a number: ");
44
7. scanf("%d",&number);
8.
9. for(i=1;i<=number;i++){
10. fact=fact*i;
11. }
12. printf("Factorial of %d is: %d",number,fact);
13. getch();
14. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. long factorial(int n) // function to calculate the factorial of a given number.
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1)); //calling the function recursively.
9. }
10. void main()
11. {
12. int number; //declaration of variables.
13. long fact;
14. clrscr();
15. printf("Enter a number: ");
16. scanf("%d", &number);
17. fact = factorial(number); //calling a function.
18. printf("Factorial of %d is %ld\n", number, fact);
19. getch(); //It reads a character from the keyword.
20. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
45
3. main()
4. {
5. int n,r,sum=0,temp; //declaration of variables.
6. clrscr(); //It clears the screen.
7. printf("enter the number=");
8. scanf("%d",&n);
9. temp=n;
10. while(n>0)
11. {
12. r=n%10;
13. sum=sum+(r*r*r);
14. n=n/10;
15. }
16. if(temp==sum)
17. printf("armstrong number ");
18. else
19. printf("not armstrong number");
20. getch(); //It reads a character from the keyword.
21. }
More details.
1. #include<stdio.h>
2. #include<conio.h>
3. main()
4. {
5. int n, reverse=0, rem; //declaration of variables.
6. clrscr(); // It clears the screen.
7. printf("Enter a number: ");
8. scanf("%d", &n);
9. while(n!=0)
10. {
11. rem=n%10;
12. reverse=reverse*10+rem;
13. n/=10;
14. }
15. printf("Reversed Number: %d",reverse);
16. getch(); // It reads a character from the keyword.
46
}
An algorithm is a well-defined computational procedure that takes some values or the set of values, as an input and
produces a set of values or some values, as an output.
4.9M
116
Exception Handling in Java - Javatpoint
Next
Stay
The algorithm provides the basic idea of the problem and an approach to solve it. Some reasons to use an algorithm
are as follows.
47
o The algorithm measures the performance of the methods in different cases (Best cases, worst cases,
average cases).
o The algorithm identifies the resources (input/output, memory) cycles required by the algorithm.
o With the help of an algorithm, we can measure and analyze the complexity time and space of the problems.
o The algorithm also reduces the cost of design.
The complexity of the algorithm is a way to classify how efficient an algorithm is compared to alternative ones. Its
focus is on how execution time increases with the data set to be processed. The computational complexity of the
algorithm is important in computing.
It is very suitable to classify algorithm based on the relative amount of time or relative amount of space they
required and specify the growth of time/ space requirement as a function of input size.
Time complexity
Time complexity is a Running time of a program as a function of the size of the input.
Space complexity
Space complexity analyzes the algorithms, based on how much space an algorithm needs to complete its task.
Space complexity analysis was critical in the early days of computing (when storage space on the computer was
limited).
Nowadays, the problem of space rarely occurs because space on the computer is broadly enough.
Worst-case: f(n)
Best-case: f(n)
Average-case: f(n)
Step1: start
48
Step2: Take two variable i and j
Step6: Increment i by 1
Step7: Increment j by 1
Step9: Stop
Case1:
Check if the linked list is empty then set the node as head and return it.
Case2:
Case3:
49
1. While (P->next!= null)
2. {
3. P= P->Next;
4. }
5. P->Next = New_Node;
6. New_Node->Next = null;
Asymptotic analysis is used to measure the efficiency of an algorithm that doesn't depend on machine-specific
constants and prevents the algorithm from comparing the time taking algorithm. Asymptotic notation is a
mathematical tool that is used to represent the time complexity of algorithms for asymptotic analysis.
θ Notation
θ Notation defines the exact asymptotic behavior. To define a behavior, it bounds functions from above and below.
A convenient way to get Theta notation of an expression is to drop low order terms and ignore leading constants.
Big O Notation
The Big O notation bounds a function from above, it defines an upper bound of an algorithm. Let's consider the
case of insertion sort; it takes linear time in the best case and quadratic time in the worst case. The time complexity
of insertion sort is O(n2). It is useful when we only have upper bound on time complexity of an algorithm.
50
Ω Notation
Just like Big O notation provides an asymptotic upper bound, the Ω Notation provides an asymptotic lower bound
on a function. It is useful when we have lower bound on time complexity of an algorithm.
51
6) Explain the Bubble sort algorithm?
Bubble sort is the simplest sorting algorithm among all sorting algorithm. It repeatedly works by swapping the
adjacent elements if they are in the wrong order.
e.g.
Pass1:
Pass2:
(25378) -> (25378) algorithm does not swap 2 and 5 because 2<5.
(25378) -> (23578) swap 3 and 5.
(23578) -> (23578) algorithm does not swap 5 and 7 because 5<7.
(23578) -> (23578) algorithm does not swap 7 and 8 because 7<8.
7) How to swap two integers without swapping the temporary variable in Java?
It's a very commonly asked trick question. There are many ways to solve this problem.
But the necessary condition is we have to solve it without swapping the temporary variable.
If we think about integer overflow and consider its solution, then it creates an excellent impression in the eye of
interviewers.
Suppose we have two integers I and j, the value of i=7 and j=8 then how will you swap them without using a third
variable. This is a journal problem.
We need to do this using Java programming constructs. We can swap numbers by performing some mathematical
operations like addition, subtraction, multiplication, and division. But maybe it will create the problem of integer
overflow.
1. a= a + b;
2. b=a - b; // this will act like (a+b)-b, now b is equal to a.
3. a=a - b; // (a+b)-a, now, a is equal to b.
52
It is a nice trick. But in this trick, the integer will overflow if the addition is more than the maximum value of int
primitive as defined by Integer.MAX_VALUE and if subtraction is less than minimum value i.e., Integer.MIN_VALUE.
Another solution to swap two integers without using a third variable (temp variable) is widely recognized as the best
solution, as it will also work in a language which doesn't handle integer overflow like Java example C, C++. Java
supports several bitwise operators. One of them is XOR (denoted by ^).
1. x=x^y;
2. y=x^y;
3. x=x^y;
8) What is a Hash Table? How can we use this structure to find all anagrams in a
dictionary?
A Hash table is a data structure for storing values to keys of arbitrary type. The Hash table consists of an index into
an array by using a Hash function. Indexes are used to store the elements. We assign each possible element to a
bucket by using a hash function. Multiple keys can be assigned to the same bucket, so all the key and value pairs are
stored in lists within their respective buckets. Right hashing function has a great impact on performance.
To find all anagrams in a dictionary, we have to group all words that contain the same set of letters in them. So, if
we map words to strings representing their sorted letters, then we could group words into lists by using their sorted
letters as a key.
1. FUNCTION find_anagrams(words)
2. word_groups = HashTable<String, List>
3. FOR word IN words
4. word_groups.get_or_default(sort(word), []).push(word)
5. END FOR
6. anagrams = List
7. FOR key, value IN word_groups
8. anagrams.push(value)
9. END FOR
10. RETURN anagrams
The hash table contains lists mapped to strings. For each word, we add it to the list at the suitable key, or create a
new list and add it to it.
53
Divide and Conquer is not an algorithm; it's a pattern for the algorithm. It is designed in a way as to take dispute on
a huge input, break the input into minor pieces, and decide the problem for each of the small pieces. Now merge all
of the piecewise solutions into a global solution. This strategy is called divide and conquer.
Divide and conquer uses the following steps to make a dispute on an algorithm.
Divide: In this section, the algorithm divides the original problem into a set of subproblems.
Combine: In this section, the algorithm puts together the solutions of the
subproblems to get the solution to the whole problem.
BFS (Breadth First Search) is a graph traversal algorithm. It starts traversing the graph from the root node and
explores all the neighboring nodes. It selects the nearest node and visits all the unexplored nodes. The algorithm
follows the same procedure for each of the closest nodes until it reaches the goal state.
Algorithm
Step2: Queue the starting node A and set its status=2, i.e. (waiting state)
Step4: Dequeue a node N and process it and set its status=3, i.e. (processed state)
Step5: Queue all the neighbors of N that are in the ready state (status=1) and set their status =2 (waiting state)
[Stop Loop]
Step6: Exit
Dijkstra's algorithm is an algorithm for finding the shortest path from a starting node to the target node in a
weighted graph. The algorithm makes a tree of shortest paths from the starting vertex and source vertex to all other
nodes in the graph.
Suppose you want to go from home to office in the shortest possible way. You know some roads are heavily
congested and challenging to use this, means these edges have a large weight. In Dijkstra's algorithm, the shortest
path tree found by the algorithm will try to avoid edges with larger weights.
Some problems that use Divide and conquer algorithm to find their solution are listed below.
54
o Merge Sort
o Quick Sort
o Binary Search
o Strassen's Matrix Multiplication
o Closest pair (points)
A greedy algorithm is an algorithmic strategy which is made for the best optimal choice at each sub stage with the
goal of this, eventually leading to a globally optimum solution. This means that the algorithm chooses the best
solution at the moment without regard for consequences.
In other words, an algorithm that always takes the best immediate, or local, solution while finding an answer.
Greedy algorithms find the overall, ideal solution for some idealistic problems, but may discover less-than-ideal
solutions for some instances of other problems.
Below is a list of algorithms that finds their solution with the use of the Greedy algorithm.
Linear search is used on a group of items. It relies on the technique of traversing a list from start to end by visiting
properties of all the elements that are found on the way.
For example, suppose an array of with some integer elements. You should find and print the position of all the
elements with their value. Here, the linear search acts in a flow like matching each element from the beginning of
the list to the end of the list with the integer, and if the condition is `True then printing the position of the element.'
Step2: In every iteration, compare the target value with the current value of the array
55
Step3: If the values match, return the current index of the array
Step4: If the values do not match, shift on to the next array element.
The binary search tree is a special type of data structure which has the following properties.
o Nodes which are less than root will be in the left subtree.
o Nodes which are greater than root (i.e., contains more value) will be right subtree.
o A binary search tree should not have duplicate nodes.
o Both sides subtree (i.e., left and right) also should be a binary search tree.
Insert node operation is a smooth operation. You need to compare it with the root node and traverse left (if smaller)
or right (if greater) according to the value of the node to be inserted.
Algorithm:
Algorithm-
56
No. of leaf nodes= no of leaf nodes in left subtree + number of leaf nodes in the right subtree.
18) How to find all possible words in a board of characters (Boggle game)?
In the given dictionary, a process to do a lookup in the dictionary and an M x N board where every cell has a single
character. Identify all possible words that can be formed by order of adjacent characters. Consider that we can move
to any of the available 8 adjacent characters, but a word should not have multiple instances of the same cell.
Example:
Output:
Algorithm
o Check If the Linked list does not have any value then make the node as head and return it
o Check if the value of the node to be inserted is less than the value of the head node, then insert the node at
the start and make it head.
o In a loop, find the appropriate node after which the input node is to be inserted. To find the just node start
from the head, keep forwarding until you reach a node whose value is greater than the input node. The
node just before is the appropriate node.
o Insert the node after the proper node found in step 3.
20) How to delete a node in a given link list? Write an algorithm and a program?
Write a function to delete a given node from a Singly Linked List. The function must follow the following constraints:
o The function must accept a pointer to the start node as the first argument and node to be deleted as the
second argument, i.e., a pointer to head node is not global.
57
o The function should not return a pointer to the head node.
o The function should not accept pointer to pointer to head node.
Suppose the function name is delNode(). In a direct implementation, the function needs to adjust the head pointer
when the node to be deleted the first node.
We will handle the case when the first node to be deleted then we copy the data of the next node to head and
delete the next node. In other cases when a deleted node is not the head node can be handled generally by finding
the previous node.
1. #include <stdio.h>
2. #include <stdlib.h>
3. struct Node
4. {
5. int data;
6. struct Node *next;
7. };
8.
9. void delNode(struct Node *head, struct Node *n)
10. {
11. if(head == n)
12. {
13. if(head->next == NULL)
14. {
15. printf("list can't be made empty because there is only one node. ");
16. return;
17. }
18. head->data = head->next->data;
19. n = head->next;
20. head->next = head->next->next;
21. free(n);
22. return;
23. }
24. struct Node *prev = head;
25. while(prev->next != NULL && prev->next != n)
26. prev = prev->next;
27. if(prev->next == NULL)
58
28. {
29. printf("\n This node is not present in List");
30. return;
31. }
32. prev->next = prev->next->next;
33. free(n);
34. return;
35. }
36. void push(struct Node **head_ref, int new_data)
37. {
38. struct Node *new_node =
39. (struct Node *)malloc(sizeof(struct Node));
40. new_node->data = new_data;
41. new_node->next = *head_ref;
42. *head_ref = new_node;
43. }
44. void printList(struct Node *head)
45. {
46. while(head!=NULL)
47. {
48. printf("%d ",head->data);
49. head=head->next;
50. }
51. printf("\n");
52. }
53. int main()
54. {
55. struct Node *head = NULL;
56. push(&head,3);
57. push(&head,2);
58. push(&head,6);
59. push(&head,5);
60. push(&head,11);
61. push(&head,10);
62. push(&head,15);
63. push(&head,12);
64. printf("Available Link list: ");
65. printList(head);
66. printf("\nDelete node %d: ", head->next->next->data);
67. delNode(head, head->next->next);
59
68.
69. printf("\nUpdated Linked List: ");
70. printList(head);
71.
72. /* Let us delete the the first node */
73. printf("\nDelete first node ");
74. delNode(head, head);
75.
76. printf("\nUpdated Linked List: ");
77. printList(head);
78.
79. getchar();
80. return 0;
81. }
Output:
21) Write a c program to merge a link list into another at an alternate position?
We have two linked lists, insert nodes of the second list into the first list at substitute positions of the first list.
Example
if first list is 1->2->3 and second is 12->10->2->4->6, the first list should become 1->12->2->10->17->3->2->4-
>6 and second list should become empty. The nodes of the second list should only be inserted when there are
positions available.
Use of extra space is not allowed i.e., insertion must be done in a place. Predictable time complexity is O(n) where n
is number of nodes in first list.
1. #include <stdio.h>
2. #include <stdlib.h>
3. struct Node
4. {
60
5. int data;
6. struct Node *next;
7. };
8. void push(struct Node ** head_ref, int new_data)
9. {
10. struct Node* new_node =
11. (struct Node*) malloc(sizeof(struct Node));
12. new_node->data = new_data;
13. new_node->next = (*head_ref);
14. (*head_ref) = new_node;
15. }
16. void printList(struct Node *head)
17. {
18. struct Node *temp = head;
19. while (temp != NULL)
20. {
21. printf("%d ", temp->data);
22. temp = temp->next;
23. }
24. printf("\n");
25. }
26. void merge(struct Node *p, struct Node **q)
27. {
28. struct Node *p_curr = p, *q_curr = *q;
29. struct Node *p_next, *q_next;
30. while (p_curr != NULL && q_curr != NULL)
31. {
32. p_next = p_curr->next;
33. q_next = q_curr->next;
34. q_curr->next = p_next;
35. p_curr->next = q_curr;
36. p_curr = p_next;
37. q_curr = q_next;
38. }
39.
40. *q = q_curr;
41. }
42. int main()
43. {
44. struct Node *p = NULL, *q = NULL;
61
45. push(&p, 3);
46. push(&p, 2);
47. push(&p, 1);
48. printf("I Linked List:\n");
49. printList(p);
50.
51. push(&q, 8);
52. push(&q, 7);
53. push(&q, 6);
54. push(&q, 5);
55. push(&q, 4);
56. printf("II Linked List:\n");
57. printList(q);
58.
59. merge(p, &q);
60.
61. printf("Updated I Linked List:\n");
62. printList(p);
63.
64. printf("Updated II Linked List:\n");
65. printList(q);
66. getchar();
67. return 0;
68. }
Output:
I Linked List:
1 2 3
II Linked List:
4 5 6 7 8
Updated I Linked List:
1 4 2 5 3 6
Updated II Linked List:
7 8
62
Encryption is the technique of converting plaintext into a secret code format it is also called as "Ciphertext." To
convert the text, the algorithm uses a string of bits called as "keys" for calculations. The larger the key, the higher
the number of potential patterns for Encryption. Most of the algorithm use codes fixed blocks of input that have a
length of about 64 to 128 bits, while some uses stream method for encryption.
o Time complexity
o Space complexity
Time complexity deals with the quantification of the amount of time taken by a set of code or algorithm to process
or run as a function of the amount of input. In other words, the time complexity is efficiency or how long a program
function takes to process a given input.
Space complexity is the amount of memory used by the algorithm to execute and produce the result.
Stack and Queue both are non-primitive data structure used for storing data elements and are based on some real-
world equivalent.
Working principle
The significant difference between stack and queue is that stack uses LIFO (Last in First Out) method to access and
add data elements whereas Queue uses FIFO (First in first out) method to obtain data member.
Structure
In Stack, the same end is used to store and delete elements, but in Queue, one end is used for insertion, i.e., rear
end and another end is used for deletion of elements.
Stack uses one pointer whereas Queue uses two pointers (in the simple case).
Operations performed
Stack operates as Push and pop while Queue operates as Enqueue and dequeuer.
Variants
Stack does not have variants while Queue has variants like a circular queue, Priority queue, doubly ended Queue.
Implementation
63
The stack is simpler while Queue is comparatively complex.
25) What is the difference between the Singly Linked List and Doubly Linked List
data structure?
This is a traditional interview question on the data structure. The major difference between the singly linked list and
the doubly linked list is the ability to traverse.
You cannot traverse back in a singly linked list because in it a node only points towards the next node and there is
no pointer to the previous node.
On the other hand, the doubly linked list allows you to navigate in both directions in any linked list because it
maintains two pointers towards the next and previous node.
It is a general-purpose computer programming language. It is a high-level, object-oriented language which can run
equally on different platforms such as Windows, Linux, UNIX, and Macintosh. Its high-level built-in data structures,
combined with dynamic typing and dynamic binding. It is widely used in data science, machine learning and artificial
intelligence domain.
55.1K
Snake bites man sitting on toilet
64
o System scripting.
2) Why Python?
Python is used in various software domains some application areas are given below.
Python provides various web frameworks to develop web applications. The popular python web frameworks
are Django, Pyramid, Flask.
Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.
Python's SciPy and NumPy helps in scientific and computational application development.
65
o Python is Interpreted language
Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes
instructions directly.
Free and open source: It is an open-source project which is publicly available to reuse. It can be downloaded free of
cost.
o It is Extensible
o Object-oriented
Object-oriented: Python allows to implement the Object-Oriented concepts to build application solution.
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.
o Readability
o High-Level Language
o Cross-platform
Portable: Python programs can run on cross platforms without affecting its performance.
66
5) What is PEP 8?
PEP 8 stands for Python Enhancement Proposal, it can be defined as a document that helps us to provide the
guidelines on how to write the Python code. It is basically a set of rules that specify how to format Python code for
maximum readability. It was written by Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001.
Literals can be defined as a data which is given in a variable or constant. Python supports the following literals:
String Literals
String literals are formed by enclosing text in the single or double quotes. For example, string literals are string
values.
Numeric Literals
Python supports three types of numeric literals integer, float and complex.
Boolean Literals
Boolean literals are used to denote Boolean values. It contains either True or False.
67
Special literals
Python contains one special literal, that is, 'None'. This special literal is used for defining a null variable. If 'None' is
compared with anything else other than a 'None', it will return false.
A function is a section of the program or a block of code that is written once and can be executed whenever
required in the program. A function is a block of self-contained statements which has a valid name, parameters list,
and body. Functions make programming more functional and modular to perform modular tasks. Python provides
several built-in functions to complete tasks and also allows a user to create new functions as well.
o Built-In Functions: copy(), len(), count() are the some built-in functions.
o User-defined Functions: Functions which are defined by a user known as user-defined functions.
o Anonymous functions: These functions are also known as lambda functions because they are not declared
with the standard def keyword.
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable,
convert into iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples.
Signature
Parameters
iterator1, iterator2, iterator3: These are iterator objects that are joined together.
Return
68
Note: If the given lists are of different lengths, zip stops generating tuples when the first list ends. It
means two lists are having 3, and 5 lengths will create a 3-tuple.
o Pass by references
o Pass by value
By default, all the parameters (arguments) are passed "by reference" to the functions. Thus, if you change the value
of the parameter within a function, the change is reflected in the calling function as well. It indicates the original
variable. For example, if a variable is declared as a = 10, and passed to a function where it's value is modified to a =
20. Both the variables denote to the same value.
The pass by value is that whenever we pass the arguments to the function only values pass to the function, no
reference passes to the function. It makes it immutable that means not changeable. Both variables hold the different
values, and original value persists even after modifying in the function.
Python has a default argument concept which helps to call a method using an arbitrary number of arguments.
Python's constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is
automatically invoked by python to initialize members of an object. We can't overload constructors or methods in
Python. It shows an error if we try to overload.
Example:
69
1. class student:
2. def __init__(self, name):
3. self.name = name
4. def __init__(self, name, email):
5. self.name = name
6. self.email = email
7.
8. # This line will generate an error
9. #st = student("rahul")
10.
11. # This line will call the second constructor
12. st = student("rahul", "rahul@gmail.com")
13. print("Name: ", st.name)
14. print("Email id: ", st.email)
Output:
Name: rahul
Email id: rahul@gmail.com
11) What is the difference between remove() function and del statement?
The user can use the remove() function to delete a specific object in the list.
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
2. print(list_1)
3. list_1.remove(3)
4. print("After removal: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After removal: [5, 7, 3, 9, 3]
If you want to delete an object at a specific location (index) in the list, you can either use del or pop.
Example:
1. list_1 = [ 3, 5, 7, 3, 9, 3 ]
70
2. print(list_1)
3. del list_1[2]
4. print("After deleting: ", list_1)
Output:
[3, 5, 7, 3, 9, 3]
After deleting: [3, 5, 3, 9, 3]
Note: You don't need to import any extra module to use these functions for removing an element from
the list.
We cannot use these methods with a tuple because the tuple is different from the list.
It is a string's function which converts all uppercase characters into lowercase and vice versa. It is used to alter the
existing case of the string. This method creates a copy of the string which contains all the characters in the swap
case. If the string is in lowercase, it generates a small case string and vice versa. It automatically ignores all the non-
alphabetic characters. See an example below.
Example:
Output:
it is in lowercase.
IT IS IN UPPERCASE.
To remove the whitespaces and trailing spaces from the string, Python providies strip([str]) built-in function. This
function returns a copy of the string after removing whitespaces if present. Otherwise returns original string.
Example:
71
1. string = " javatpoint "
2. string2 = " javatpoint "
3. string3 = " javatpoint"
4. print(string)
5. print(string2)
6. print(string3)
7. print("After stripping all have placed in a sequence:")
8. print(string.strip())
9. print(string2.strip())
10. print(string3.strip())
Output:
javatpoint
javatpoint
javatpoint
After stripping all have placed in a sequence:
Javatpoint
javatpoint
javatpoint
To remove leading characters from a string, we can use lstrip() function. It is Python string function which takes an
optional char type parameter. If a parameter is provided, it removes the character. Otherwise, it removes all the
leading spaces from the string.
Example:
Output:
javatpoint
72
javatpoint
After stripping all leading whitespaces:
javatpoint
javatpoint
After stripping, all the whitespaces are removed, and now the string looks like the below:
Example:
1. str = "Rohan"
2. str2 = "ab"
3. # Calling function
4. str2 = str.join(str2)
5. # Displaying result
6. print(str2)
Output:
aRohanb
This method shuffles the given string or an array. It randomizes the items in the array. This method is present in the
random module. So, we need to import it and then we can call the function. It shuffles elements each time when the
function calls and produces different output.
Example:
73
2. import random
3. # declare a list
4. sample_list1 = ['Z', 'Y', 'X', 'W', 'V', 'U']
5. print("Original LIST1: ")
6. print(sample_list1)
7. # first shuffle
8. random.shuffle(sample_list1)
9. print("\nAfter the first shuffle of LIST1: ")
10. print(sample_list1)
11. # second shuffle
12. random.shuffle(sample_list1)
13. print("\nAfter the second shuffle of LIST1: ")
14. print(sample_list1)
Output:
Original LIST1:
['Z', 'Y', 'X', 'W', 'V', 'U']
The break statement is used to terminate the execution of the current loop. Break always breaks the current
execution and transfer control to outside the current block. If the block is in a loop, it exits from the loop, and if the
break is in a nested loop, it exits from the innermost loop.
Example:
74
8. break
9. else:
10. continue
11. break
Output:
2
X 11
X 22
X 33
Y 11
Y 22
Y 33
BREAK
75
18) What is tuple in Python?
A tuple is a built-in data collection type. It allows us to store values in a sequence. It is immutable, so no change is
reflected in the original data. It uses () brackets rather than [] square brackets to create a tuple. We cannot remove
any element but can find in the tuple. We can use indexing to get elements. It also allows traversing elements in
reverse order by using negative indexing. Tuple supports various methods like max(), sum(), sorted(), Len() etc.
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
6. # Displaying Single value
7. print(tup[2])
Output:
(2, 4, 6, 8)
6
Example:
1. # Declaring tuple
2. tup = (2,4,6,8)
3. # Displaying value
4. print(tup)
5.
76
6. # Displaying Single value
7. print(tup[2])
8.
9. # Updating by assigning new value
10. tup[2]=22
11. # Displaying Single value
12. print(tup[2])
Output:
tup[2]=22
TypeError: 'tuple' object does not support item assignment
(2, 4, 6, 8)
The Python provides libraries/modules that enable you to manipulate text files and binary files on the file system. It
helps to create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.
Here, os and os.path - modules include a function for accessing the filesystem
while shutil - module enables you to copy and delete the files.
20) What are the different file processing modes supported by Python?
Python provides four modes to open files. The read-only (r), write-only (w), read-write (rw) and append mode (a). 'r'
is used to open a file in read-only mode, 'w' is used to open a file in write-only mode, 'rw' is used to open in reading
and write mode, 'a' is used to open a file in append mode. If the mode is not specified, by default file opens in read-
only mode.
o Read-only mode (r): Open a file for reading. It is the default mode.
o Write-only mode (w): Open a file for writing. If the file contains data, data would be lost. Other a new file is
created.
o Read-Write mode (rw): Open a file for reading, write mode. It means updating mode.
o Append mode (a): Open for writing, append to the end of the file, if the file exists.
An operator is a particular symbol which is used on some values and produces an output as a result. An operator
works on operands. Operands are numeric literals or variables which hold some values. Operators can be unary,
77
binary or ternary. An operator which requires a single operand known as a unary operator, which require two
operands known as a binary operator and which require three operands is called ternary operator.
Example:
1. # Unary Operator
2. A = 12
3. B = -(A)
4. print (B)
5. # Binary Operator
6. A = 12
7. B = 13
8. print (A + B)
9. print (B * A)
10. #Ternary Operator
11. A = 12
12. B = 13
13. min = A if A < B else B
14.
15. print(min)
Output:
# Unary Operator
-12
# Binary Operator
25
156
# Ternary Operator
78
12
Python uses a rich set of operators to perform a variety of operations. Some individual operators like membership
and identity operators are not so familiar but allow to perform operations.
Arithmetic operators perform basic arithmetic operations. For example "+" is used to add and "?" is used for
subtraction.
Example:
Output:
35
-11
276
0.5217391304347826
Relational Operators are used to comparing the values. These operators test the conditions and then returns a
boolean value either True or False.
Example:
79
1. a, b = 10, 12
2. print(a==b) # False
3. print(a<b) # True
4. print(a<=b) # True
5. print(a!=b) # True
Output:
False
True
True
True
Assignment operators are used to assigning values to the variables. See the examples below.
Example:
Output:
12
14
12
24
576
Logical operators are used to performing logical operations like And, Or, and Not. See the example below.
Example:
80
1. # Logical operator examples
2. a = True
3. b = False
4. print(a and b) # False
5. print(a or b) # True
6. print(not b) # True
Output:
False
True
True
Membership operators are used to checking whether an element is a member of the sequence (list, dictionary,
tuples) or not. Python uses two membership operators in and not in operators to check element presence. See an
example.
Example:
Output:
False
True
Identity Operators (is and is not) both are used to check two values or variable which are located on the same part
of the memory. Two variables that are equal does not imply that they are identical. See the following examples.
Example:
81
Output:
False
True
Bitwise Operators are used to performing operations over the bits. The binary operators (&, |, OR) work on bits. See
the example below.
Example:
Output:
8
14
6
-11
In Python 3, the old Unicode type has replaced by "str" type, and the string is treated as Unicode by default. We can
make a string in Unicode by using art.title.encode("utf-8") function.
Example:
Output:
82
Python is an interpreted language. The Python language program runs directly from the source code. It converts the
source code into an intermediate language code, which is again translated into machine language that has to be
executed.
o Memory management in python is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have access to this private heap. The
python interpreter takes care of this instead.
o The allocation of heap space for Python objects is done by Python's memory manager. The core API gives
access to some tools for the programmer to code.
o Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be
made available to the heap space.
Decorators are very powerful and a useful tool in Python that allows the programmers to add functionality to an
existing code. This is also called metaprogramming because a part of the program tries to modify another part of
the program at compile time. It allows the user to wrap another function to extend the behaviour of the wrapped
function, without permanently modifying it.
Example:
1. def function_is_called():
2. def function_is_returned():
3. print("JavaTpoint")
4. return function_is_returned
83
5. new_1 = function_is_called()
6. # Outputs "JavaTpoint"
7. new_1()
Output:
JavaTpoint
A function is a block of code that performs a specific task whereas a decorator is a function that modifies other
functions.
27) What are the rules for a local and global variable in Python?
Global Variables:
o Variables declared outside a function or in global space are called global variables.
o If a variable is ever assigned a new value inside the function, the variable is implicitly local, and we need to
declare it as 'global' explicitly. To make a variable globally, we need to declare it by using global keyword.
o Global variables are accessible anywhere in the program, and any function can access and modify its value.
Example:
1. A = "JavaTpoint"
2. def my_function():
3. print(A)
4. my_function()
Output:
JavaTpoint
Local Variables:
o Any variable declared inside a function is known as a local variable. This variable is present in the local
space and not in the global space.
o If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local.
o Local variables are accessible within local body only.
Example:
84
1. def my_function2():
2. K = "JavaTpoint Local"
3. print(K)
4. my_function2()
Output:
JavaTpoint Local
The namespace is a fundamental idea to structure and organize the code that is more useful in large projects.
However, it could be a bit difficult concept to grasp if you're new to programming. Hence, we tried to make
namespaces just a little easier to understand.
A namespace is defined as a simple system to control the names in a program. It ensures that names are unique and
won't lead to any conflict.
Also, Python implements namespaces in the form of dictionaries and maintains name-to-object mapping where
names act as keys and the objects as values.
In Python, iterators are used to iterate a group of elements, containers like a list. Iterators are the collection of items,
and it can be a list, tuple, or a dictionary. Python iterator implements __itr__ and next() method to iterate the stored
elements. In Python, we generally use loops to iterate over the collections (list, tuple).
In simple words: Iterators are objects which can be traversed though or iterated upon.
In Python, the generator is a way that specifies how to implement iterators. It is a normal function except that it
yields expression in the function. It does not implements __itr__ and next() method and reduce other overheads as
well.
If a function contains at least a yield statement, it becomes a generator. The yield keyword pauses the current
execution by saving its states and then resume from the same when required.
Slicing is a mechanism used to select a range of items from sequence type like list, tuple, and string. It is beneficial
and easy to get elements from a range by using slice way. It requires a : (colon) which separates the start and end
index of the field. All the data collection types List or tuple allows us to use slicing to fetch elements. Although we
85
can get elements by specifying an index, we get only single element whereas using slicing we can get a group of
elements.
Example:
Output:
The Python dictionary is a built-in data type. It defines a one-to-one relationship between keys and values.
Dictionaries contain a pair of keys and their corresponding values. It stores elements in key and value pairs. The keys
are unique whereas values can be duplicate. The key accesses the dictionary elements.
Example:
The following example contains some keys Country Hero & Cartoon. Their corresponding values are India, Modi,
and Rahul respectively.
Output:
Country: India
86
Hero: Modi
Cartoon: Rahul
Pass specifies a Python statement without operations. It is a placeholder in a compound statement. If we want to
create an empty class or functions, the pass keyword helps to pass the control without error.
Example:
1. class Student:
2. pass # Passing class
3. class Student:
4. def info():
5. pass # Passing function
The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method
definition. It provides a convenient way to associate the documentation.
String literals occurring immediately after a simple assignment at the top are called "attribute docstrings".
String literals occurring immediately after another docstring are called "additional docstrings".
Python uses triple quotes to create docstrings even though the string fits on one line.
Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special chars.
Example:
1. # One-line docstrings
2. def hello():
3. """A function to greet."""
4. return "hello"
35) What is a negative index in Python and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that
are positive uses '0' that is uses as first index and '1' as the second index and the process go on like that.
87
The index for the negative number starts from '-1' that represents the last index in the sequence and '-2' as the
penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last
character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct
order.
SQL stands for the Structured Query Language. It is the standard language used to maintain the relational database
and perform many different data manipulation operations on the data. SQL was initially invented in 1970. It is a
database language used for database creation, deletion, fetching and modifying rows, etc. sometimes, it is
pronounced as 'sequel.' We can also use it to handle organized data comprised of entities (variables) and relations
between different entities of the data.
88
SQL first appeared in 1974. It is one of the most used languages for maintaining the relational database. In 1986,
SQL became the standard of the American National Standards Institute (ANSI) and ISO (International Organization
for Standardization) in 1987.
SQL is responsible for maintaining the relational data and the data structures present in the database. Some of the
common usages are given below:
Skip Ad
SQL refers to the Standard Query Language. Therefore, it is true that SQL is a language but does not actually
support the programming language. It is a common language that doesn't have a loop, conditional statements, and
logical operations. It cannot be used for anything other than data manipulation. It is a command language to
perform database operations. The primary purpose of SQL is to retrieve, manipulate, update, delete, and perform
complex operations like joins on the data present in the database.
o Data definition language (DDL): It defines the data structure that consists of commands like CREATE,
ALTER, DROP, etc.
o Data manipulation language (DML): It is used to manipulate existing data in the database. The
commands in this category are SELECT, UPDATE, INSERT, etc.
o Data control language (DCL): It controls access to the data stored in the database. The commands in this
category include GRANT and REVOKE.
o Transaction Control Language (TCL): It is used to deal with the transaction operations in the database.
The commands in this category are COMMIT, ROLLBACK, SET TRANSACTION, SAVEPOINT, etc.
89
6) What is the purpose of DDL Language?
DDL stands for Data definition language. It is the subset of a database that defines the data structure of the
database when the database is created. For example, we can use the DDL commands to add, remove, or modify
tables. It consists of the following commands: CREATE, ALTER and DELETE database objects such as schema, tables,
indexes, view, sequence, etc.
Example
Data manipulation language makes the user able to retrieve and manipulate data in a relational database. The DML
commands can only perform read-only operations on data. We can perform the following operations using DDL
language:
Example
Data control language allows users to control access and permission management to the database. It is the subset
of a database, which decides that what part of the database should be accessed by which user at what point of time.
It includes two commands, GRANT and REVOKE.
GRANT: It enables system administrators to assign privileges and roles to the specific user accounts to perform
specific tasks on the database.
REVOKE: It enables system administrators to revoke privileges and roles from the user accounts so that they cannot
use the previously assigned permission on the database.
Example
90
1. GRANT * ON mydb.Student TO javatpoint@localhsot;
A table is a set of organized data in the form of rows and columns. It enables users to store and display records in
the structure format. It is similar to worksheets in the spreadsheet application. Here rows refer to the tuples,
representing the simple data item, and columns are the attribute of the data items present in a particular row.
Columns can categorize as vertical, and Rows are horizontal.
Fields are the components to provide the structure for the table. It stores the same category of data in the same
data type. A table contains a fixed number of columns but can have any number of rows known as the record. It is
also called a column in the table of the database. It represents the attribute or characteristics of the entity in the
record.
Example
Table: Student
A primary key is a field or the combination of fields that uniquely identify each record in the table. It is one of a
special kind of unique key. If the column contains a primary key, it cannot be null or empty. A table can have
duplicate columns, but it cannot have more than one primary key. It always stores unique values into a column. For
example, the ROLL Number can be treated as the primary key for a student in the university or college.
91
11) What is a foreign key?
The foreign key is used to link one or more tables together. It is also known as the referencing key. A foreign key is
specified as a key that is related to the primary key of another table. It means a foreign key field in one table refers
to the primary key field of the other table. It identifies each row of another table uniquely that maintains the
referential integrity. The primary key-foreign key relationship is a very crucial relationship as it maintains the ACID
properties of the database sometimes. It also prevents actions that would destroy links between the child and
parent tables.
1. CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)
A unique key is a single or combination of fields that ensure all values stores in the column will be unique. It means
a column cannot stores duplicate values. This key provides uniqueness for the column or set of columns. For
example, the email addresses and roll numbers of student's tables should be unique. It can accept a null value but
only one null value per column. It ensures the integrity of the column or group of columns to store different values
into a table.
13) What is the difference between a primary key and a unique key?
The primary key and unique key both are essential constraints of the SQL. The main difference among them is that
the primary key identifies each record in the table. In contrast, the unique key prevents duplicate entries in a column
except for a NULL value. The following comparison chart explains it more clearly:
92
Primary Key Unique Key
The primary key act as a unique identifier for The unique key is also a unique identifier for records when the
each record in the table. primary key is not present in the table.
We cannot store NULL values in the primary key We can store NULL value in the unique key column, but only one
column. NULL is allowed.
We cannot change or delete the primary key We can modify the unique key column values.
column values.
A database is an organized collection of data that is structured into tables, rows, columns, and indexes. It helps the
user to find the relevant information frequently. It is an electronic system that makes data access, data manipulation,
data retrieval, data storing, and data management very easy. Almost every organization uses the database for
storing the data due to its easily accessible and high operational ease. The database provides perfect access to data
and lets us perform required tasks.
DBMS stands for Database Management System. It is a software program that primarily functions as an interface
between the database and the end-user. It provides us the power such as managing the data, the database engine,
and the database schema to facilitate the organization and manipulation of data using a simple query in almost no
time. It is like a File Manager that manages data in a database rather than saving it in file systems. Without the
database management system, it would be far more difficult for the user to access the database's data.
o Software
o Data
o Procedures
o Database Languages
o Query Processor
93
o Database Manager
o Database Engine
o Reporting
The database management systems can be categorized into several types. Some of the important lists are given
below:
RDBMS stands for Relational Database Management System. It is a database management system based on a
relational model. It facilitates you to manipulate the data stored in the tables by using relational operators. RDBMS
stores the data into the collection of tables and links those tables using the relational operators easily whenever
required. Examples of relational database management systems are Microsoft Access, MySQL, SQL Server, Oracle
database, etc.
Normalization is used to minimize redundancy and dependency by organizing fields and table of a database.
There are some rules of database normalization, which is commonly known as Normal From, and they are:
Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be removed.
94
19) What is the primary use of Normalization?
Normalization is mainly used to add, delete or modify a field that can be made in a single table. The primary use of
Normalization is to remove redundancy and remove the insert, delete and update distractions. Normalization breaks
the table into small partitions and then links them using different relationships to avoid the chances of redundancy.
The occurrence of redundant terms in the database causes the waste of space in the disk.
Due to redundant terms, inconsistency may also occur. If any change is made in the data of one table but not made
in the same data of another table, then inconsistency will occur. This inconsistency will lead to the maintenance
problem and effects the ACID properties as well.
An Inconsistent dependency refers to the difficulty of getting relevant data due to a missing or broken path to the
data. It leads users to search the data in the wrong table, resulting in an error as an output.
Denormalization is a technique used by database administrators to optimize the efficiency of their database
infrastructure. The denormalization concept is based on Normalization, which is defined as arranging a database
into tables correctly for a particular purpose. This method allows us to add redundant data into a normalized
database to alleviate issues with database queries that merge data from several tables into a single table. It adds
redundant terms into the tables to avoid complex joins and many other complex operations.
Denormalization doesn't mean that normalization will not be done. It is an optimization strategy that takes place
after the normalization process.
Operators are the special keywords or special characters reserved for performing particular operations. They are also
used in SQL queries. We can primarily use these operators within the WHERE clause of SQL commands. It's a part of
the command to filters data based on the specified condition. The SQL operators can be categorized into the
following types:
o Arithmetic operators: These operators are used to perform mathematical operations on numerical data.
The categories of this operators are addition (+), subtraction (-), multiplication (*), division (/),
remainder/modulus (%), etc.
95
o Logical operators: These operators evaluate the expressions and return their results in True or False. This
operator includes ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR, UNIQUE.
o Comparison operators: These operators are used to perform comparisons of two values and check
whether they are the same or not. It includes equal to (=), not equal to (!= or <>), less than (<), greater
than (>), less than or equal to (<=), greater than or equal to (>=), not less than (!<), not greater than (!>),
etc.
o Bitwise operators: It is used to do bit manipulations between two expressions of integer type. It first
performs conversion of integers into binary bits and then applied operators such as AND (& symbol), OR (|,
^), NOT (~), etc.
o Compound operators: These operators perform operations on a variable before setting the variable's
result to the operation's result. It includes Add equals (+=), subtract equals (-=), multiply equals (*=), divide
equals (/=), modulo equals (%=), etc.
o String operators: These operators are primarily used to perform concatenation and pattern matching of
strings. It includes + (String concatenation), += (String concatenation assignment), % (Wildcard), []
(Character(s) matches), [^] (Character(s) not to match), _ (Wildcard match one character), etc.
A view is a database object that has no values. It is a virtual table that contains a subset of data within a table. It
looks like an actual table containing rows and columns, but it takes less space because it is not present physically. It
is operated similarly to the base table but does not contain any data of its own. Its name is always unique. A view
can have data from one or more tables. If any changes occur in the underlying table, the same changes reflected in
the views also.
The primary use of a view is to implement the security mechanism. It is the searchable object where we can use a
query to search the view as we use for the table. It only shows the data returned by the query that was declared
when the view was created.
An index is a disc structure associated with a table or view that speeds up row retrieval. It reduces the cost of the
query because the query's high cost will lead to a fall in its performance. It is used to increase the performance and
allow faster retrieval of records from the table. Indexing reduces the number of data pages we need to visit to find a
particular data page. It also has a unique value meaning that the index cannot be duplicated. An index creates an
entry for each value which makes it faster to retrieve data.
96
For example: Suppose we have a book which carries the details of the countries. If you want to find out information
about India, why will you go through every page of that book? You could directly go to the index. Then from the
index, you can go to that particular page where all the information about India is given.
26) What are the differences between SQL, MySQL, and SQL Server?
SQL or Structured Query Language MySQL is the popular database SQL Server is an RDBMS database
is useful for managing our relational management system used for system mainly developed for the
databases. It is used to query and managing the relational database. It is Windows system to store, retrieve,
operate the database. a fast, scalable, and easy-to-use and access data requested by the
database. developer.
SQL first appeared in 1974. MySQL first appeared on May 23, 1995. SQL Server first appeared on April 24,
1989.
SQL was developed by IBM MySQL was developed by Oracle SQL Server was developed by
Corporation. Corporation. Microsoft Company.
SQL is a query language for MySQL is database software that uses SQL Server is also a software that uses
managing databases. SQL language to conduct with the SQL language to conduct with the
database. database.
SQL has no variables. MySQL can use variables constraints SQL Server can use variables
and data types. constraints and data types.
SQL is a programming language, so MySQL is software, so it gets frequent SQL Server is also software, so it gets
that it does not get any updates. Its updation. frequent updation.
commands are always fixed and
remain the same.
97
Section7: HR Interview Questions
1) Tell me about yourself?
This is the most famous question for an interviewer and also most difficult to answer this question for the candidate.
This question puts all the pressure on the candidate, and the interviewer relax.
You should alert enough to answer this question. You should start with an easy and confident tone and answer in a
proper manner. It should not be scripted. Always remember, you are not giving the interview to a robot so your
articulation, your pronunciation of each word should be clear and confident.
A good way:
1.2M
OOPs Concepts in Java
Next
Stay
Possible Answer 1
First of all, thank you for giving me this opportunity to introduce myself.
As far as my education qualification is concerned, I have done MBA with finance stream from
Srivenkateswara university in Emerald's P. G. College, Tirupathi, in the year of 2014.
98
I am good in programming languages C, C++, and Java and very much interested in HTML, CSS, ASP.
Net and SQL.
Possible Answer 2
While coming to my family members, there are 4 members including me. My father is a doctor, and
any mother is a teacher. My younger sister will appear her 12th CBSE board exam this year.
Now coming to me, I am sweet smart, confident, and hardworking person. I am a cool hearted person,
so usually see every difficulty with a positive side and keep myself always smiling which makes me
stronger even more.
My hobbies are dancing, Internet surfing, playing Chess, listening to music, watching the news channel.
In my spare time, I like to read news on my phone and traveling to my hometown.
Possible Answer 3
I am carrying 5 years of experience at top Wall Street Companies. In my recent company, I led the
development of an award-winning new trading platform. I can survive in a fast-paced environment.
Now I am looking for a chance to apply my technical expertize and my creative problem-solving skills
at an innovative software company like yours.
99
By this question, the interviewer wants to know that:
Before answering this question, take your own time an answer in the way that convinces the interviewer. Explain
your qualities according to the above-stated points.
Possible Answer 1
I have applied for this vacancy because it is an excellent match for my skills and experience. This
role is exactly the sort of role I am currently targeting, and I am confident I will be able to make a
major contribution.
Possible Answer 2
Sir, it's a great privilege to work in a reputed company like yours. When I read about your
requirement, I found that my skills are matching with them. Through this role, I can show my
technical skills to contribute to the company growth.
You should become very honest to answer this question. Don't tell a lie or compromise to get the job only. If you
don't have any problem, you can answer like this:
I know that in the company being asked to work for an extended number of hours comes with a
good reason, so I am ok with it. It an extra effort means I am doing something for the company, I'll
be happy to do it.
This is a very tricky question. The work should always be more important than the money. This frame of mind is
good for you(at least at the time of interview).
Possible Answer 1
"Money is always important, but the work is most important for me."
Possible Answer 2
100
"I would say that work is more important. If we work and achieve Company goals then obviously
money would follow. I believe work to be prior."
Possible Answer 3
"Work is more important for me. Working just for money may not be fulfilled if I don't feel
satisfied with my job. My work makes me stay productive, and money would naturally come along
well."
Possible Answer 4
"I think money probably matters to me about as much as it does to anyone. It's vital and necessary
for us to live and prosper but, at the same time, it's not my single most important driving force. I
believe that money is rewarded for work."
You should fully aware of that organization where you are going for an interview, so check the history, present
structure and working style of that organization. Check the company's website, Facebook, Twitter, Google+,
LinkedIn pages to gather the information.
Possible Answer 1
We all know that it is one of the fastest growing infrastructure company in India. The facilities
provided to the employee is best. People feel proud to be the part of your company as the
company provides full support to their employees in professional front. The working
environment of this company is decent. It has crossed the branches in the world also. And I was in
search of this type of company.
Possible Answer 2
We all know that this company is India's no.1 company for development. I was delighted to see on
your company website that your employees are talking about how great it is to work for your
company. Now these days, so many people seem to hate the company where they work for one
reason or another. It's great to see that your employees are proud to talk about how much they
love their company and jobs.
101
You should be very careful with this question. Avoid trashing other employers and making a statement like "I need
more money". Instead of this, you can say that:
Sir, it's a career move. I have learned a lot from my last job, but now I am looking for new
challenges to broaden my horizons and to gain a new skill-set.
Tell your qualifications and highlight that points which makes you unique.
Possible Answer 1
"I believe that everyone starts with a beginning, I need a platform to prove my abilities and skills.
I think your company is the right place to explore my abilities. I need to be a part of your growth. I
will do my level best."
Possible Answer 2
"As a fresher, I need a platform to prove my ability. If I will be a part of your company, I'll put my
effort and strength to uplift your company. None is born with experience, and if you hire me, I will
get professional experience through your company."
Possible Answer 3
"Sir, as I am a fresher, I have theoretical knowledge, but I need a platform where I can implement
my knowledge in the practical field. I am ensuring you that I will put all my efforts for the good
progress of the organization. As a fresher, I have no preset mind regarding work culture in an
organization, and this will help me to adapt the working culture of your company very easily.
Being punctual and regular, I can finish the work giving to me on time and try my best to fulfill all
the needs of the company."
Possible Answer 4
"I have a good experience in that particular field (field of your specialization), and I think my
talents will be a big contribution to the continuing pursuit of excellence of your company."
Don't ask your salary in exact numbers, instead of this show your commitment to the job itself.
Possible Answer 1
102
I am more interested in the role than the pay, and I expect to be paid appropriate money for this
role based on my experience. As you also know that the high cost of living here in Delhi.
Possible Answer 2
As I am fresher, Salary is not an issue for me. Learning and gaining experience is my major
priority. As your company is one of the most reputed company, I just accept the salary offered by
you is the best in the industry.
Possible Answer 3
As of now, I haven't thought much about it. I am more focused on learning the requirements for
this position that I am applying for.
9) Assume you are hired, then how long would you expect to work for us?
Possible Answer 1
"I will do my best for the growth of your company as long as I have the career growth, job
satisfaction, respect and a healthy environment, then I don't need to change my company."
Possible Answer 2
"I will work with the company as long as my presence benefits the company and I get ample
opportunity to grow and develop both professionally and monetarily."
Possible Answer 3
"Everyone looks for a bright future, healthy work environment, good salary, job satisfaction and I
am pretty sure that your company gives such things, so I don't need to change the company."
Possible Answer 4
"I will work with the company as long as my presence benefits both the company and mine in
parallel. So your company gains good results, and I can be in a good position to improve my
skills."
Possible Answer 1
103
I will rate myself 8 out of 10 because I would never like to think that there should be a room left
for putting in more efforts. That thought will create an interest in learning the things. Thank you
very much for giving me this wonderful opportunity.
Possible Answer 2
I will answer this question based on some parameters. As far as hard work is concerned, I will
rate myself as 8 because there should always be a scope to increase our skills which will create an
interest in learning the things. When it comes to creativity, I would like to rate myself as 9. In the
past, I have designed banners and brochures which were appreciated by the clients. To talk about
patience, I will tag myself with 6 because I am an entry-level professional. Same as personal life,
even professional life needs more experience for more patience. That is probably why in most
companies, senior management looks more patient than entry level or even middle level. Overall, I
would rate myself as 8 on a scale of 1 to 10.
This question may also be asked that what are your biggest achievements? Or what are you most proud of?
You should discuss only work-related achievements. Try to pick a recent achievement.
Possible Answer 1
"My greatest achievement so far in my career would probably be winning the Manager of the Year
award last year."
Possible Answer 2
Possible Answer 3
Possible Answer 1
104
"My short-term goal is to work in a reputed organization like yours where I can enhance my technical
skills and knowledge.
My long-term goal is to see the company at a topmost position where I am one of the people
responsible for that."
Possible Answer 2
"My goal is to become a successful person and make my family proud of me."
You should always remember that even if your strength is not business related, find a way to relate it to work. Tell
your positive points related to the job.
Possible Answer 1
My main strengths are the ability to use my initiative to take on challenges. I am always proactive
at what I do, and that keeps my mind stimulated and focused.
Possible Answer 2
Possible Answer 3
My time management skills are excellent, and I'm organized, efficient, and take pride in excelling
at my work.
Possible Answer 4
I always understand the value of time, and I am always able to innovate. I listen to advice from
others.
Possible Answer 5
My greatest strength is my ability to focus on my work. I'm not easily distracted, and this means
that my performance is very high.
Possible Answer 6
105
My biggest strength is my Confidence . Apart from that, I am Hardworking, self-motivated with
a positive attitude towards my career and my life. If I have a problem, then I think its an
opportunity for me to express my ability.
Everyone has weaknesses so while answering this question don't spend so much time on this. This question is
generally asked to know how honest you are with yourself. State one or two minor weaknesses and try to relate it
works. (avoid saying "I work too hard" it is a very common answer). Don't pretend you don't have weaknesses and
don't avoid answering the question.
Possible Answer 1
You can say, "I used to be very disorganized, always forgetting assignments and birthdays. But I
managed to work out a computerized system of to-do lists and reminders that keep me on top of
everything."
Possible Answer 2
"I am a straightforward person, and I cannot say no when someone asks me for help."
It totally depends on you what you like and what hobbies do you have but always justify your answer.
For Example:
My hobbies are dancing, Internet surfing, playing Chess, listening to music, watching the news
channel. In my spare time, I like to read news on my phone and traveling to my hometown. Thank
you for giving this opportunity to introduce myself.
While answering this question, don't merely say that you are hard working, dedicated, punctual, etc. because these
are not assets, these are the responsibility that management wants. Off course these are positive words and has a
lot of meaning for you as well as for the company. Actually, these qualities make you an asset for the company after
getting experience.
Possible Answer 1
106
"To become an asset for an organization, we have to punctual, dedicated, quickly adapt of the
environment and positive working attitude I have all of these qualities so I will prove an asset for
this company."
Possible Answer 2
"As I'm a fresher, I'll be passionate about my work, and if given a chance I'll be ready to expose
myself into different sectors of work into the industry, and would be faithful to the company
always."
Possible Answer 3
"My skill in XYZ company is outstanding. I have earned a lot of certificates and awards from my
past employers. As an employee, I can handle pressure with ease and can work with minimal
supervision."
Possible Answer 1
"It depends on the situation if my lie creates a positive impact on the company and It was useful
for many people, then I will lie."
Possible Answer 2
"Probably I would say no for a lie. But if condition persists that my lie will help thousands of
persons and it is not giving any impact to other persons, then I will agree with the lie. My one lie
results lot of success and happiness without hurting others rights then I expect to do this."
This question has a very specific purpose. The interviewer wants to know that if the candidate admits that he has
applied to other places or gives a canned answer. Or what the candidate think about their company.
You should never claim that you did not apply to other company. Despite this, you can say that -
As you know, I would like to work as a software developer. Beyond your company, I have also
applied to XYZ company and ABC company. This answer is more specific.
107
19) How do you get to know about our company?
The interviewer should not lie while answering such questions. Because an interviewer is a brilliant person and they
can detect it if you are lying.
For Example
Possible Answer 1
If I feel I am making a difference working with a team of people to make a more profitable
company. It is a success for me.
Possible Answer 2
If I put a smile on someone face and make him happy, it is a success for me.
This question is asked to the candidate to judge how spontaneous and explaining he is. If he uses a word, he must
be able to explain that word and also represent himself according to that word.
These are some positive words. You can use it but be sure that you are judging with the word.
Original, genuine, logical, incredible, focused, curious, active, quick, balanced, achiever, etc.
Confidence is based on facts and knowledge, and overconfidence is based on speculation. There is a small
difference between confidence and overconfidence. Yes, I can do this work is self-confidence. But only I can do this
work is overconfidence.
Or you can say that: confidence is an internal belief that I am a right person for this job and overconfidence is
thought that I am only the right person for this job.
108
23) What is the difference between smart work and hard work?
The difference between smart work and hard work are as follows:
Smart work and hard work are related to each other. Without being a hard worker, we can't be a
smart worker. Smart work comes from the hard work. That means everyone has to specialize in his
work to become a smart worker. So, all of us have to do hard work to achieve smart work.
So hard work increases your accuracy, and smart work increases accuracy as well as efficiency.
24) Just imagine that you have enough money to retire right now. Would you?
"No sir, I don't think so. I am a professional, and I love my work, so there is no question to leave
my work. Yes, it may be that I would take a break to spend quality time with my family."
25) Don't you think that you are overqualified for this position?
This is trick of the interviewer to trap you and judge how boasting you are?
So, be alert to answer this question and don't even hint to the interviewer that you are overqualified although you
are.
"I think I am qualified for this post because I am just a beginner and have lots more to learn. I
think qualification is not only a matter of theoretical knowledge or results; it also depends on
practical knowledge and learning. When I get practical knowledge, I will consider myself just a
well-qualified not overqualified. Because learning never ends."
It is a trick question. So don't specify your actual weaknesses. Instead of this try to show you are very team oriented
For example:
109
"I would say everyone has blind spots and I would too that's why I believe in teamwork because
when you are a team, you can point out the blind spots of other people, and they will also do the
same for you."
Note: "don't admit failure as a blind spot. Failure is not a blind spot."
It is a typical interview question asked to judge how you handle the job stress and pressure.
Possible Answer 1
I believe in working in a planned way and finishing my work regularly. I always react to situations,
rather than to stress. In this way, I handle the situation and don't take the stress.
Possible Answer 2
I go to the gym regularly and do work out. In this way, I remove my stress. I believe that physical
exercise is a great stress reducer.
This question is asked to judge, what type of situations make you uncomfortable and disappointed. While answering
this question, don't just say your disappointment. Instead of this, you should include what you learn from that
incident.
Possible Answer 1:
"The greatest disappointment in my life so far as when my laptop had stolen, and I had lost all my
important data. I remember that I had to work hard for the next 10 days to redo all my work to
make sure to submit on time."
Possible Answer 2: If you did not face any disappointment in your life
You should always answer this question in a manner that suits both your personality and management too.
110
"Sir, I am not a short-tempered person, but I feel a bit of annoyance when someone disturbs me in
my work without a genuine reason. Although I am an even-tempered person, when I get angry, I
try to channel my negative feeling in my work."
30) What was the most difficult decision you have made in your past life?
This question is asked to judge your decision-making capabilities. The interviewer wants to know, how you take a
decision in tough times.
Possible Answer 1
After completing my graduation, the toughest decision is whether to go for higher studies or do a
job. Then I chose the job because getting trained is better than educated and it was also the
demand of that time.
Possible Answer 2
My toughest decision was to take admission in B.tech. I belong to a middle-class family, and my
father was not in favor of taking admission, but I convinced him, and today he is very happy.
Possible Answer 3
Before some time when I had to choose between joining a group of employees protesting some
issue, and staying away from the issue. I ended up being a mediator between our immediate
supervisor and employees, and I am glad I made that decision because it all ended well and
without further conflicts in the company.
Just tell the source from where you got the information about this post. If the interviewer asks, what you know
about this position or what appeals you most in this position?
I have carefully studied both the job description and the person specification, so I am fully aware
of the duties and responsibilities of this role.
111
It is my promise that gets up me in the morning. My promise is to learn something new and someone in need. It
provides me the satisfaction that I am making a difference in someone life.
This question is asked to judge your taste about reading books. The interviewer wants to know what types of book
you like. Would you fit for the company culture?
Answer this question according to your sense, your knowledge about the book. Only named the books you have
really read. You should choose something from a reputable author that your interviewer has probably heard of.
34) As you said, internet surfing is your hobby. Which site do you surf mostly?
This is your choice that which sites you surf most, but while answering this question always refers to sites which are
relevant to your field of job. Don't take the name of social networking sites or other irrelevant sites.
At the time of answering this question, you should choose a story containing not too many mistakes. It should be
real.
Talk about the mistake, but it is also important to convince the interviewer that you never make the same mistake
again.
For example:
I think the worst mistake I ever made at work was in my first ever job - five years ago now. A more
senior member of the team seemed to take an instant dislike to me from the start, and one day she was
particularly unpleasant to me in front of several colleagues.
Later on, I was talking to one of those colleagues who was, I thought, attempting to console me. Angry
and hurt, I foolishly vented my feelings and told her what I thought of the lady in question. I was
naturally shocked to find out that she went on to tell everyone what I had said and this certainly didn't
help my relationship with the team member who was causing me problems.
Rather than let the situation carry on, I chose to have a quiet word with this lady to find out what her
problem was with me and to see if we could put it behind us. It turned out it was nothing personal; she
just resented the fact that a friend of hers had also been interviewed for my position and had been
turned down. Once we had got matters out into the air, her behavior changed, and we got on quite well
after that. However, I certainly learned a lot from experience. I learned that careful communication is
112
vital in managing interpersonal relationships and that if I have a problem with someone, it's always
best to talk it over with them rather than with someone else.
This question has just two answers, YES or NO. If you know anyone from that company, say YES, otherwise NO.
Possible Answer 1
I would try to find out exactly what the problem was, and evaluate if there was something I could
do to make it right.
Possible Answer 2
I would ask the customer to explain his problem and carefully listen to him. After that, I do my
best to solve his problem. If that problem is not regarding my work area, I spoke to someone who
could help him immediately.
Possible Answer 1
I would try to find out exactly what the problem was, and evaluate if there was something I could
do to make it right.
Possible Answer 2
I would ask the customer to explain his problem and carefully listen to him. After that, I do my
best to solve his problem. If that problem is not regarding my work area, I spoke to someone who
could help him immediately.
Possible Answer 1
113
Before some time, public speaking has been a challenge for me. I was very nervous and hesitate
while giving any presentation, so I started taking public speaking seminars to improve it. Now, I
still get nervous before pitches, but I have learned how to remain calm and get the job done right.
Possible Answer 2
As you know that I have never worked in my life and this is my first job, my inexperience is my
weakness. But I beg to differ. I am confident and a fast learner. I assure you that I will perform my
job without carrying any pre-conceived notions regarding how I feel.
There is only one difference between the group and the team. That is unity. Any set of people who
stand together without any purpose or goal can be called as Group. Whereas, when more than 2
people work towards a common goal, can be called as a Team. For example: If you assign work to
a group, then the work will be divided between the members and each member will work out
their part, without any coordination with the other members of the group. On the other hand, if
you assign a project to a team, they will collectively take the responsibility and work together
with the goal to achieve the desired result. In a team, the members will cooperate and coordinate
with each other at all times.
Machine learning is a branch of computer science which deals with system programming in order to
automatically learn and improve with experience. For example: Robots are programed so that they can
perform the task based on data they gather from sensors. It automatically learns programs from data.
Machine learning relates with the study, design and development of the algorithms that give computers
the capability to learn without being explicitly programmed. While, data mining can be defined as the
process in which the unstructured data tries to extract knowledge or unknown interesting
patterns. During this process machine, learning algorithms are used.
In machine learning, when a statistical model describes random error or noise instead of underlying
relationship ‘overfitting’ occurs. When a model is excessively complex, overfitting is normally observed,
because of having too many parameters with respect to the number of training data types. The model
exhibits poor performance which has been overfit.
114
4) Why overfitting happens?
The possibility of overfitting exists as the criteria used for training the model is not the same as the
criteria used to judge the efficacy of a model.
By using a lot of data overfitting can be avoided, overfitting happens relatively as you have a small
dataset, and you try to learn from it. But if you have a small database and you are forced to come with a
model based on that. In such situation, you can use a technique known as cross validation. In this
method the dataset splits into two section, testing and training datasets, the testing dataset will only test
the model while, in training dataset, the datapoints will come up with the model.
In this technique, a model is usually given a dataset of a known data on which training (training data set)
is run and a dataset of unknown data against which the model is tested. The idea of cross validation is to
define a dataset to “test” the model in the training phase.
The inductive machine learning involves the process of learning by examples, where a system, from a
set of observed instances tries to induce a general rule.
• Decision Trees
• Neural Networks (back propagation)
• Probabilistic networks
• Nearest Neighbor
• Support vector machines
• Supervised Learning
• Unsupervised Learning
• Semi-supervised Learning
• Reinforcement Learning
• Transduction
• Learning to Learn
9) What are the three stages to build the hypotheses or model in machine learning?
• Model building
• Model testing
• Applying the model
The standard approach to supervised learning is to split the set of example into the training set and the
test.
115
In various areas of information science like machine learning, a set of data is used to discover the
potentially predictive relationship known as ‘Training Set’. Training set is an examples given to the
learner, while Test set is used to test the accuracy of the hypotheses generated by the learner, and it is
the set of example held back from the learner. Training set are distinct from Test set.
• Artificial Intelligence
• Rule based inference
• Classifications
• Speech recognition
• Regression
• Predict time series
• Annotate strings
17) What is the difference between artificial learning and machine learning?
Designing and developing algorithms according to the behaviours based on empirical data are known as
Machine Learning. While artificial intelligence in addition to machine learning, it also covers other
aspects like knowledge representation, natural language processing, planning, robotics etc.
A classifier in a Machine Learning is a system that inputs a vector of discrete or continuous feature
values and outputs a single discrete value, the class.
In Naïve Bayes classifier will converge quicker than discriminative models like logistic regression, so you
need less training data. The main advantage is that it can’t learn interactions between features.
116
20) In what areas Pattern Recognition is used?
• Computer Vision
• Speech Recognition
• Data Mining
• Statistics
• Informal Retrieval
• Bio-Informatics
Genetic programming is one of the two techniques used in machine learning. The model is based on the
testing and selecting the best choice among a set of results.
Inductive Logic Programming (ILP) is a subfield of machine learning which uses logical programming
representing background knowledge and examples.
The process of selecting models among different mathematical models, which are used to describe the
same data set is known as Model Selection. Model selection is applied to the fields of statistics, machine
learning and data mining.
24) What are the two methods used for the calibration in Supervised Learning?
The two methods used for predicting good probabilities in Supervised Learning are
• Platt Calibration
• Isotonic Regression
These methods are designed for binary classification, and it is not trivial.
When there is sufficient data ‘Isotonic Regression’ is used to prevent an overfitting issue.
26) What is the difference between heuristic for rule learning and heuristics for decision trees?
The difference is that the heuristics for decision trees evaluate the average quality of a number of
disjointed sets while rule learners only evaluate the quality of the set of instances that is covered with the
candidate rule.
In Machine Learning, Perceptron is an algorithm for supervised classification of the input into one of
several possible non-binary outputs.
117
Bayesian logic program consists of two components. The first component is a logical one ; it consists of
a set of Bayesian Clauses, which captures the qualitative structure of the domain. The second
component is a quantitative one, it encodes the quantitative information about the domain.
Bayesian Network is used to represent the graphical model for probability relationship among a set of
variables.
30) Why instance based learning algorithm sometimes referred as Lazy learning algorithm?
Instance based learning algorithm is also referred as Lazy learning algorithm as they delay the induction
or generalization process until classification is performed.
31) What are the two classification methods that SVM ( Support Vector Machine) can handle?
To solve a particular computational program, multiple models such as classifiers or experts are
strategically generated and combined. This process is known as ensemble learning.
Ensemble learning is used to improve the classification, prediction, function approximation etc of a model.
Ensemble learning is used when you build component classifiers that are more accurate and
independent from each other.
36) What is the general principle of an ensemble method and what is bagging and boosting in
ensemble method?
The general principle of an ensemble method is to combine the predictions of several models built with a
given learning algorithm in order to improve robustness over a single model. Bagging is a method in
ensemble for improving unstable estimation or classification schemes. While boosting method are used
sequentially to reduce the bias of the combined model. Boosting and Bagging both can reduce errors by
reducing the variance term.
The expected error of a learning algorithm can be decomposed into bias and variance. A bias term
measures how closely the average classifier produced by the learning algorithm matches the target
118
function. The variance term measures how much the learning algorithm’s prediction fluctuates for
different training sets.
Incremental learning method is the ability of an algorithm to learn from new data that may be available
after classifier has already been generated from already available dataset.
PCA (Principal Components Analysis), KPCA ( Kernel based Principal Component Analysis) and ICA
( Independent Component Analysis) are important feature extraction techniques used for dimensionality
reduction.
In Machine Learning and statistics, dimension reduction is the process of reducing the number of
random variables under considerations and can be divided into feature selection and feature extraction.
Support vector machines are supervised learning algorithms used for classification and regression
analysis.
• Data Acquisition
• Ground Truth Acquisition
• Cross Validation Technique
• Query Type
• Scoring Metric
• Significance Test
43) What are the different methods for Sequential Supervised Learning?
• Sliding-window methods
• Recurrent sliding windows
• Hidden Markow models
• Maximum entropy Markow models
• Conditional random fields
• Graph transformer networks
44) What are the areas in robotics and information processing where sequential prediction
problem arises?
The areas in robotics and information processing where sequential prediction problem arises are
• Imitation Learning
• Structured prediction
• Model based reinforcement learning
119
45) What is batch statistical learning?
Statistical learning techniques allow learning a function or predictor from a set of observed data that can
make predictions about unseen or future data. These techniques provide guarantees on the performance
of the learned predictor on the future unseen data based on a statistical assumption on the data
generating process.
PAC (Probably Approximately Correct) learning is a learning framework that has been introduced to
analyze learning algorithms and their statistical efficiency.
47) What are the different categories you can categorized the sequence learning process?
• Sequence prediction
• Sequence generation
• Sequence recognition
• Sequential decision
• Genetic Programming
• Inductive Learning
50) Give a popular application of machine learning that you see on day to day basis?
The recommendation engine implemented by major ecommerce websites uses Machine Learning.
Ans : The project I dealt with is detection of dementia using machine learning . Dementia is a neuro -degenerative
disorder , which is one of the most common among older people.
Its kind of memory loss mostly in age group of above 65 years. We basically collected data-set from kaggle and
performed EDA, data visualization and build models using various machine learning algorithms and predicted the
output by training and testing data . which results in detecting whether a person is demented or not and technical
stack we used are pychram, jupyter notebook. We where group of 4 who worked on this project and we where able
to complete our project within the deadline .
Ans: My favourite subjects are Python ,Networking, C ,C++, Big data & cloud computing,AI and machine learning.
120
3) What is Polymorphism?
Ans : Polymorphism is a concept by which we can perform a single action in different ways. Polymorphism is derived
from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
Or function having same name but perform different operations that different situations.
ANS:
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it
abstract methods. can have default and static methods also.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Ans:Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule
which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class private. Now, we can
use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
121
Ans : Layers of OSI model are:
7) What is UNIX?
Ans:UNIX is a complete package of the operating system developed mainly for servers, workstations, and
mainframes. It is a copyrighted named. It can be used by its copyrighters only. It contains a completely different
coding developed by AT&T labs, highly secured, has listed about 85-120 viruses till date.
ANS: Android is an open-source, Linux-based operating system used in mobiles, tablets, televisions etc. Andy Rubin
is the founder of Android. Android 11”R” is the latest version of Android.
PROGRAM:
1. class programme
2. {
3. public static void main(String args[])
4. {
5. int i;
6. int array[]= new int[11];
7. array[0]= -1;
8. array[1]=1;
9. System.out.println("The Fibonacci series is: ");
10. for(i=2; i<array.length; i++)
11. {
12. array[i]= array[i-2] + array[i-1];
13. System.out.print(array[i]+ " " );
14. }
15. }
122
16. }
Output:
The Fibonacci series is:
0 1 1 2 3 5 8 13 21
12
123
1234
PROGRAM:
1. class Pyramid
2. {
3. public static void main(String[] args)
4. {
5. for(int i=1; i<=5 ;i++) // i is used for row elements
6. {
7. for(int j=0; j<i; j++) // j is used for column elements
8. {
9. System.out.print(j+1);
10. }
11. System.out.println();
12. }
13. }
14. }
Output:
1
12
123
1234
12345
11) Name the major data structures used in RDBMS, Network data model &
Hierarchical data model.
123
12) Give some advantages of DBMS.
ANS: DESC in SQL is used to describe a schema as well as to retrieve rows from table in descending order.
Ans:ER Model is based on real world that consists of basic objects called entities and of relationship among these
objects. Entities represent a set of attributes in a database.
ANS: well,my name xyz, which means _________ , I am an optimistic in nature , I am from the place which is called
garden city I.e, bangalore. I am B.Tech in computer Science student at Reva University,Bangalore. My areas of
interests include data and analytics , cloud and big data , security .As I talk about my background , we are four
members of our family : my parents, me and my sister. My father is a bank manager and mother is home-maker. I
have elder sister she is doing her Mtech presently.
17) Tell me about your academics and if you have any backlog.
Answer: Sir/Mam, I have an aggregate of 9.61 CGPA in B.tech without any backlog in my whole journey of
academics. I completed my Intermediate from xyz college with 89.33% and I have 88.5% in high school which I
completed from xyz school, bangalore in ____ board.
Answer: I am good in Data and Analytics. I have a good knowledge of C, python , cloud computing and machine
learning languages. I am also good in databases and have a great command on MySQL queries.
124
Technology is a $25 billion company with a 60-year legacy of delivering results for thousands of
clients in more than 70 countries.
Answer: Strength: I am good at analytics and leadership skills and I am good at working in team environments as I
have worked on projects in a team and successfully completed the project in a given deadline and I am a fast learner.
Weakness: I am very detailed oriented. If task is assigned to me I would use up personal time to complete a task and
this could be unnecessary pressure on me sometimes.
Answer: I want to do the job as a well-skilled Data analytics and security engineer in an organization where I will be
a well- respected team leader with the renowned personality.
Is there anything that I could learn to build my skills that are required for your company?
125