Category Archives: Programming

Articles and Interview Questions,Tips related to Programming – Interview Sortout

Python Interview Questions

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. 

Nowadays the popularity of python is increasing day by day. Python is easy to learn and has vast libraries. In the field of Machine Learning, Deep Learning and Artificial Intelligence Python are the top priority in the implementation tool.  You can find on google the trends of top programming languages.

Since the demand and popularity are on top, so the career opportunity in Python programming and related fields is high. Keeping this in mind we have created a set of some useful Python Interview Questions and Answers, so that one may find a proper guide for an Interview. 

Python Interview Questions are very useful when you are going for an Interview for the designation of Python Developer or Machine Learning or any Related fields to Python. These python interview questions and answers are equally useful for freshers and experienced.

While representing this set of questions along with answers we hope that they will be useful for visitors.

What is Python?

Python is an Interpreted programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, built-in data structure and it is open-source.

What are the key features of Python?

  • Python is an interpreted language. That means Python does not need to be compiled before it is run. 
  • Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. 
  • Python is well suited to object-orientated programming in that it allows the definition of classes along with composition and inheritance. 
  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first-class objects
  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C based extensions so bottlenecks can be optimized away and often are. 

What type of language is python? Programming or scripting?

Python is capable of scripting, but in a general sense, it is considered as a general-purpose programming language.

What is PEP 8?

PEP 8 is a coding convention, a set of recommendations about how to write your Python code more readable.

What are Python packages?

Python packages are namespaces containing multiple modules.

What is the difference between abs () and fabs ()?

abs() is a built-in function that works with integer, float and complex numbers also.

fabs() is defined in the math module which doesn’t work with complex numbers.

How Python is interpreted?

Python is an interpreted language because Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

How memory is managed in Python?

Python has an awesome feature of memory management. The following points will explain memory management in python:

  • Python memory 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 and the interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by the Python memory manager. The core API gives access to some tools for the programmer to code.
  • Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and makes it available to the heap space.

 

What are the tools that help to find bugs or perform the static analysis?

PyChecker is a static analysis tool that detects bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

 

What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

 

What is the difference between list and tuple?

The difference between list and tuple is that the list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.

 

How are arguments passed by value or by reference?

Everything in Python is an object and all variables hold references to the objects. The reference values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.

 

What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

 

What is the built-in type does python provides?

There are mutable and Immutable types of Pythons built-in types Mutable built-in types

  • List
  • Sets
  • Dictionaries

Immutable built-in types

  • Strings
  • Tuples
  • Numbers

 

What is namespace in Python?

In Python, every name introduced has a place where it lives and can be hooked for. This is known as a namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.

 

What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

A deep copy is used to store the values that are already copied. The deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

 

What is lambda in Python?

It is a single expression anonymous function often used as an inline function.

 

Why lambda forms in python does not have statements?

A lambda form in python does not have statements as it is used to make a new function object and then return them at runtime.

 

Does python support multiple inheritances?

Multiple inheritances mean that a class can be derived from more than one parent class. Python does support multiple inheritances, unlike Java.

 

What is a pass in Python?

Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.

 

What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

 

What is encapsulation in Python?

Encapsulation means binding the code and the data together. A Python class is an example of encapsulation.

 

How do you do data abstraction in Python?

Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

 

How to use access specifiers?

Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.  

 

In Python what are iterators?

In Python, iterators are used to iterate a group of elements, containers like a list.

 

What is the unit test in Python?

A unit testing framework in Python is known as a unit test. It supports the sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.

 

Explain what Flask is and its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs.

A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify it. The user can modify the session if only it has the secret key Flask.secret_key.

 

In Python what is slicing?

A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.

 

What are the generators in Python?

The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.

 

What is PYTHONPATH?

It is an environment variable that is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.

 

What is type conversion in Python?

Type conversion refers to the conversion of one data type into another.

int() : converts any data type into integer type

float() : converts any data type into float type

ord() : converts characters into integer

hex() : converts integers to hexadecimal

oct() : converts integer to octal

tuple() : This function is used to convert to a tuple.

set() : This function returns the type after converting to set.

list() : This function is used to convert any data type to a list type.

dict() : This function is used to convert a tuple of order (key,value) into a dictionary.

str() : Used to convert integer into a string.

 

What is docstring in Python?

A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.

 

How can you copy an object in Python?

To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.

 

What is a negative index in Python?

Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.

 

How you can convert a number to a string?

In order to convert a number into a string, use the inbuilt function str(). If you want an octal or hexadecimal representation, use the inbuilt function oct() or hex().

 

What is the difference between Xrange and range?

Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.

 

Mention the differences between Django, Pyramid, and Flask.

  • Flask is a “microframework” primarily build for a small application with simpler requirements. In a flask, you have to use external libraries. Flask is ready to use.
  • Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
  • Django can also be used for larger applications just like Pyramid. It includes an ORM.

 

What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of Python program is a package of modules. A package can have modules or subfolders.

 

Why indentation required in python?

Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.

 

Mention what are the rules for local and global variables in Python?

Local variables: If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be local.

Global variables: Those variables that are only referenced inside a function are implicitly global.

List out the inheritance styles in Django.

In Django, there are three possible inheritance styles:

  1. Abstract Base Classes: This style is used when you only want the parent’s class to hold information that you don’t want to type out for each child model.
  2. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table.
  3. Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields.

 

Why are local variable names beginning with an underscore discouraged?

  • they are used to indicate a private variables of a class
  • they confuse the interpreter
  • they are used to indicate global variables
  • they slow down execution

 

What is the purpose of the PYTHONCASEOK environment variable?

PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

 

Explain how can you make a Python Script executable on Unix?

To make a Python Script executable on Unix, you need to do two things,

  • Script file’s mode must be executable and
  • the first line must begin with # ( #!/usr/local/bin/python)

How can you share global variables across modules?

To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.

 

What are the supported data types in Python?

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

 

Explain how to delete a file in Python?

By using a command os.remove (filename) or os.unlink(filename)

 

Explain how you can generate random numbers in Python?

To generate random numbers in Python, you need to import command as

import random

random.random()

This returns a random floating-point number in the range [0,1)

 

What is self in Python?

 

Self is an instance of an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional.  It helps to differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.

 

What are tuples in Python?

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

 

How will you check if all characters in a string are alphanumeric?

We will use the method isalnum().

 

Does Python allow you to program in a structured style?

Yes. It does allow to code is structured as well as Object-oriented style. It offers excellent flexibility to design and implement your application code depending on the requirements of your application.

 

Explain how can you access a module written in Python from C?

You can access a module written in Python from C by following method,

Module = =PyImport_ImportModule(“<modulename>”);

 

Mention the use of // operator in Python?

It is a Floor Divisionoperator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.

 

Mention five benefits of using Python?

  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners

What is module and package in Python?

In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of the Python program is a package of modules. A package can have modules or subfolders.

 

What is difference between pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

  • Having the built-in data types saves programming time and effort from declaring variables

 

What is a dictionary in Python?

Ans: The built-in data types in Python are called the dictionary. It defines one-to-one relationships between keys and values. Dictionaries contain a pair of keys and their corresponding values. Dictionaries are indexed by keys.

 

Mention the use of the split function in Python?

The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all the words present in the string.

 

What tools can be used to unit test your Python code?

The best and easiest way is to use ‘unittest’ python standard library to test units/classes. The features supported are very similar to the other unit testing tools such as JUnit, TestNG.

 

What is the starting point of Python code execution?

As Python is an interpreter, it starts reading the code from the source file and starts executing them.

 

Explain what is Flask & its benefits?

Flask is a web microframework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jinja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.

 

Mention what is the difference between Django, Pyramid, and Flask?

Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use.

The pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. The pyramid is heavily configurable.

Like Pyramid, Django can also used for larger applications. It includes an ORM.

 

How to comment on multiple lines in python?

Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment on multiple lines. All you need to do is hold the ctrl key and left-click in every place wherever you want to include a # character and type a # just once. This will comment on all the lines where you introduced your cursor.

 

Which module(s) of Python can be used to measure the performance of your application code?

Time module can be used to calculate the time at different stages of your application and use the Logging module to log data to a file system in any preferred format.

 

Mention what is Flask-WTF and what are their features?

Flask-WTF offers simple integration with WTForms. Features include for Flask WTF are

  • Integration with wtforms
  • Secure form with csrf token
  • Global csrf protection
  • Internationalization integration
  • Recaptcha supporting
  • File upload that works with Flask Uploads

 

Does the same Python code work on multiple platforms without any changes?

As long as you have the Python environment on your target platform (Linux, Windows, Mac), you can run the same code.

How do you make use of Arrays in Python?

Python does not support Arrays. However, you can use List collection type which can store an unlimited number of elements.

Explain what is the common way for the Flask script to work?

The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

 

What are the different environment variables identified by Python?

PYTHONPATH: This environment variable helps the interpreter as to where to locate the module files imported in the program.

PYTHONSTARTUP: This environment variable contains the path of the Initialization file containing the source code.

PYTHONCASEOK: This variable is used to find the first case-insensitive match in the import statement

 

Explain how you can access sessions in Flask?

A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.

 

What are a help () and dir() in python?

help() is a built-in function that can be used to return the Python documentation of a particular object, methods, attributes, etc.

dir() displays a list of attributes for the objects which are passed as an argument. If dir() is without the argument then it returns a list of names in current local space.

 

What is the difference between locals() and globals ()?

locals() is accessed within the function and it returns all names that can be accessed locally from that function.

 

Spread the love

Stack Interview Questions

The stack is always a favourite part of the interviewer in any programming interview. Stack has an important place in Linear data structure and used to implement complex solutions. Stack Interview Questions are the best collection of concepts and questions asked in the data structure Interview.

Stacks are important part of data structures and comes under abstract data structures. They allow access to only one data item at a time and that is the last item inserted.


Since internally other data structures are used by stack, they are abstract data type. Stacks use array. Stacks are useful to perform many operations in other data types.
Few examples of Stack implementation:

  • Stack is used by Binary trees in traversing of nodes.
  • Stack is used by Graphs in searching the vertices of the graph.
  • Stacks can be used to process tasks, messages etc.

To crack Stack interview and to give perfect answers to stack interview questions and answers, It is very important to have basic concepts of stack and other data types like array.

Here we have given the basic concept of stack and implementation of stack using C language.

While keeping in mind the practical implementation and complexity we have given plenty of examples of stack implementation and operations using C Programming.

What is a Stack?



A stack is a linear data structure and represented a list of the element in which an element may be inserted or deleted only from one end, called the top of the stack.

Elements in the stack are arranged in a linear fashion. Unlike an array, we can not access an element randomly.

According to the behaviour of Stack, we can have two important operations

  1. PUSH and
  2. POP

Insertion of an element in the stack from the top is called PUSH and removal of an element from the stack is called POP.

We can only access the last element inserted in a Stack. Hence We can say an Item can either Inserted or Deleted At only one end of the stack and that end is the TOP. This is why We called it a LIFO – Last In First Out.

Main Features of Stack


  1. The stack is a Linear type data structure
  2. Allow only the last element to access
  3. Random access of element is not allowed
  4. The stack is an ordered list of similar data type
  5. When a stack is completely full it is called Overflow Stack and If completely empty it is called Underflow Stack.
  6. A stack is a recursive data structure. Here is a structural definition of a Stack:
    1. a stack is either empty or
    2. it consisted of a top and the rest which is a stack;

Application of Stack

  • We can use stack reverse a string. You push a given string to stack – character by character – and then POP character from the stack.
  • Undo Operations in the text editor is an application of stack PUSH and POP.

Basic Operations on Stack

Stack allowed the following operation with data stored it with:

  1. Push operation
  2. Pop operation
  3. Peek operation
  4. isFull
  5. isEmpty

Algorithm for PUSH Operation in Stack

Consider MAX represents the last position of the element to be inserted and TOP is the current position. TOP initially points to 0.


Algorithm POP Operation in Stack

The function will return the popped value from the stack

Implementation of Stack



The stack can be implemented as

  1. Using Array
  2. Using a Linked list

Array and linked list both are used to implement a stack. Both have some advantages and disadvantages associated with them. Here are some relative comparisons between these two.

  • The array is a collection of similar data types elements while the linked list is a collection of elements of the same type connected to each other by pointers.
  • Array consumes memory in a contiguous manner. Also, the size of array is decided at compile time. This kind of memory allocation is called Static memory allocation. But in case of linked list memory allocated at runtime. The size of the list can be increased or decreased at runtime. This kind of memory allocation is called dynamic memory allocation.
  • The size of the array is fixed. Memory allocated as soon as the array is declared. In the case of a linked list, size can grow or shrink. 
  • In array, due to memory allocation in contiguous in manner, insertion and deletion take more time in comparison to linked list.
  • Accessing an element in an array is faster. Also, any element of an array can be easily accessed by using indexing. This is not in the case of a linked list. You have to transverse from the starting point to access any element.

 

Implement Stack using an Array



A working Example of Implementation of Stack using Array

Implement Stack using a Linked list



A working Example of Implementation of Stack using Linked List

Spread the love

Binary Search Tree Data Structure

A tree is best thought of in this sort of picture. You have a root node at the very top and it has child nodes and each of those child nodes, they have child nodes themselves, and so on.

Very often when we’re talking about trees we talk about binary trees. 

Binary Tree 

A binary tree means that each node has no more than two child nodes. 

That is that each node has a left node and a right node. Of course one or both of those could also be null.      

Binary Search Tree

A binary search tree is a binary tree that fulfills a specific ordering property and a special tree data structure. So on any subtree, the left nodes are less than the root node which is less than all of the right notes. This ordering property makes finding a node very fast because we have a pretty good idea of where it would be. 

How Searching Works Binary Search Tree?

Let’s choose a node, it’s bigger than the root node, so let’s go to the right. Now the next node, if it’s smaller than that node so it must be on the left unless it should be in right. And so very quickly we can start to zoom in on where that node will be because at each operation we’ve chopped off hopefully about half of the nodes and very quickly we find the node we’re looking for. 

Inserting an Element

Inserts work much like finding an element works. We start with some element we want to insert like say, 19, and we say is it bigger or smaller than the route? 

Let say, it’s bigger so let’s go to the right. Now compare it to the next node? If it’s smaller so let’s go to the left. We will do this over and over again until we get to an empty spot or a null node and then we say ok that’s where we should insert our new element. 

Now the one problem here is that if we get elements in a particular order, we could get really imbalanced. Suppose we have a new binary search tree and we just follow the properties of insertion.

So we insert 1 and then 2 to it’s right and then 3 to it’s right and 4 to it’s right, we’re going to get this data structure that looks less like a tree and more like a long list.

 And then inserts and finds will no longer be so fast. There are some algorithms that can ensure that our tree stays balanced, that is roughly the same number of nodes will be on the left side of the subtree and on the right.

These algorithms get pretty complicated so we’re not gonna go into the details here, but it’s worth knowing that they’re built into a lot of programming languages and in a lot of cases and Data Structures Interview Questions you’ll just assume that you have a balanced tree. 

Traversing Through a Tree

The last operation to talk about is traversing or walking through a tree. So there are three common ways we walk through a tree we can do an 

  1. Inorder traversal
  2. Preorder traversal
  3. Postorder traversal. 

A Preorder traversal means that you visit the root first and then you visit it’s left nodes and it’s right nodes. 

In Inorder traversal, you visit the left nodes first then the current node and then you go to the right nodes. 

In a Post Order Traversal, the root node comes up last so you visit the left nodes and then the right nodes, then the current root node. 

Typically in binary search trees, we want to do in order traversals because that actually allows the nodes to be printed in order. 

Implement A Binary Search Tree

Spread the love

Tree Data structures Interview Questions for Freshers

The tree is a nonlinear data structure and a very important part of computer programming. It is a very flexible, versatile and powerful data structure.

The tree can be used to represent data items possessing hierarchical relationships. Items in a tree are arranged as interconnected nodes and edges.

There is a special data item known as root and rest are known as subtrees. This segment is based on the Tree data structure Interview Questions asked in various programming interviews.

The tree data structure is an important part of data structure and played a very vital role in solving complex problems.

This segment is based on concepts and theory of Trees Data structure and very helpful for fresher candidates in an interview.

What are the main applications of Trees?

A tree is a hierarchical representation of data and a non-linear data structure. Hence it has application according to its properties :

  • To Represent hierarchical data
  • To Store data in a sorted fashion
  • To make the searching process easy

What is root?

The first item in the hierarchy is known as the root and it is placed at the top of the tree. A root is known as root is known and it is a terminal node having a degree greater than zero.

What is a node?

Each item in a tree is known as a Node. Nodes are connected to each other and hence they have a degree.

What is the degree of node?

The degree is known as the connectivity of a node. The number of subtrees connected to a node is known as the Degree of Node.

In the Given Tree :

  • Degree of A = 3
  • Degree of B = 0
  • Degree of D = 2
  • Degree of E = 0
  • Degree of F = 0

What is the Degree of Tree?

There are several nodes in a tree data structure.
Each Node has its degree, the number of the connected subtrees.
The degree of the node having the maximum degree is Known as the Degree of Tree.
For Example in the above tree, the Degree of Tree is 3, because the degree of Node A is 3 and It is maximum.

What are siblings?

Nodes having common parents are siblings.
We can say the nodes remain at the same level in a tree are siblings if they are connected to a common node.
The common node is known as Parent.
For Example, D is parent and E and F are siblings.

What is the edge?

The line which is connecting two nodes is known as Edge.

What is the path in a tree?

If we select a node as the source and another as a destination node, then the sequence of the node between these two nodes is known as path.

  • There may be many possible sequences so there may be many paths between two nodes.
  • The path is represented as node pairs. For example, in the given Tree structure the path between A and G is (A, D) (D, E) (E, G).

What is a forest?

The set of Disjointed trees is known as a forest.
When several subtrees are there and they are not joined by a root then this set is known as a forest.

What is a binary tree?

A tree is a special case of a tree when any node can not have more than 2 children.

Each node can have at most two children.

We can structure a binary tree in three parts

  1. Root
  2. Left subtree
  3. Right Subtree

How many types of binary trees are there?

The most popular types of binary trees are as follows :

  • Full Binary Tree
  • Complete Binary Tree
  • Perfect Binary Tree

Full Binary Tree

A Binary Tree will be known as the full binary tree if each node of the tree has either two children or zero children.

The node having zero children is known as a leaf node, so a Full Binary tree is a tree where all nodes have two children except the leaf nodes.

A binary tree having every level is completed except the leaf nodes,

 

Perfect Binary Tree

In a Perfect Binary tree, all the internal nodes have two children and all the leaf nodes are at the same depth.

 

Spread the love

Java Programming Books Deitel : Java How to Program [Book Review ]

Being a programmer for quite some time, I feel that programming cannot be learned from books, what one needs is a sheer practice of solving problems in programming.  But there are few Java Programming books that make learning of Java interesting.  

Java How to Program is one of the Best Java Books. After reading this book I can say this is a Good Java book. Although There are Advanced Java Books  in the market but for a beginner this Java Text Book is an early guide.

Learning Java with the help of a book is a bit tough if you are a beginner and don’t have any previous programming experience. 

You need to have at least a basic knowledge of programming concepts. Before referring to any book, I would suggest you learn Java concepts from the internet. 

You may also like Java Interview Questions and Answers

And If you want to refer a book to learn Core Java then I would suggest you “Java: How to Program” by Harvey and Paul Deitel. 

I read it, and I felt like they took my hand and guided me through all the concepts- from the easiest to the most complex and career-demanding. 

I felt this is one of the best books to learn the concepts easily and in no time.

Topics Covered in this book are :

  1. Introduction to Computers and Java
  2. Introduction to java programming
  3. Introduction to Object-Oriented Paradigm
  4. Java Classes, Objects, Methods
  5. Strings
  6. Control Statements
  7. Arrays and ArrayLists
  8. Dive into inheritance
  9. Dive into polymorphism
  10. Java exception handling
  11. Develop real-life projects using Java
  12. GUI components
  13. Graphics and Java 2D
  14. Java regular expressions
  15. Files and Streams
  16. Recursion
  17. Searching, sorting, and Big O notation
  18. Some data structures in Java
  19. Applets and Introduction to Java Web
  20. JDBC Connection (Connecting Java to a database)

The book is available in Paperback and Kindle Edition in India. This book is helpful in concept building and understanding the basic programming skills too. This book covers a detailed section about OOPs – Object Oriented Programming System.

More Details about the book is :

Pages: 1288 pages

Publishing House: Pearson Education; Eleventh edition (30 July 2018)

Language: English

The book is highly appreciated and recommended by its readers. It has near about 4-star ratings on amazon. The Amazon bestseller rank is #131255.

About the author: Harvey and Paul Deitel

Harvey M. Deitel, CEO of Deitel & Associates, Inc. has 40 years of experience in the computing field including extensive industry and academic experience. He is one of the world’s leading computer science instructors and seminar presenters.

More Books by this author Click Here 

You may also visit xadmin.net for java tutorials. 

Spread the love

What is New in PHP 7

PHP 7 is introduced as the next version of PHP.

The earlier one is PHP 5.6. The latest version is scalable and more flexible, faster and easy to implement complex logic.

Many new features are introduced with PHP 7.

These features are equally useful for the interview aspirants. Few of them are explained :

PHP 7 Features

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Unicode codepoint escape syntax
  • Closure::call()
  • Group use declarations

Scalar type declarations

There may be two scalar types of declarations :

  • coercive(default)
  • strict

We can enforce the types for parameters either coercively or strictly are :

  • strings (string)
  • integers (int)
  • floating-point numbers (float)
  • booleans (bool)

For Example in Coercive mode:

<?php
	function addTheNumbers(int ...$ints)
	{
	    return array_sum($ints);
	}
	var_dump(addTheNumbers(3, '7', 7.8));
?>

Declaration of Return Type

PHP 7 started support for return type while declaring a function.
The return type declarations specify the type of value that will be returned after execution.

For example :

<?php
function sumOfArrays(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(sumOfArrays([10,20,30], [14,15,16], [17,18,19]));
?>

In the above function, the accepted argument are arrays and the return type of the function is also an array.

Null coalescing operator

This is a comparison and validation operator added to PHP 7 and It is used as a ternary in conjunction with isset() function.
If the expression exists and not NULL then it returns the first operator else it returns the second one.

For example :

<?php
	$booktitle = $_GET['title'] ?? 'no_books';
?>

If the title is set in $_GET and the value of the $_GET[‘title’] is NOT NULL then the value of $booktitle will be the $_GET[‘title’]. In a condition of failure the title will be ‘no_books’.

Spaceship operator

This is a pure comparison operator and compares the values of two variables. It returns -1, 0 and 1. It compares less than, equal to and greater than.

Have a look at examples :

<?php 
// Integers
echo 7 <=> 7; // 0
echo 7 <=> 8; // -1
echo 8 <=> 7; // 1

// Floats
echo 7.5 <=> 7.5; // 0
echo 7.5 <=> 8.5; // -1
echo 8.5 <=> 7.5; // 1

// Strings
echo "b" <=> "b"; // 0
echo "b" <=> "c"; // -1
echo "c" <=> "b"; // 1
?>

Constant arrays using define()

In PHP 7 we can define an array as a constant, like strings and numbers. It can be done using the define() function.

<?php
define('SUPER_HEROS', [
    'Iron Man',
    'Thor',
    'Captain America',
    'Spidar Man'
]);

echo SUPER_HEROS[1]; // outputs "Thor"
?>

Anonymous classes

PHP 7 has introduced support for Anonymous classes. Anonymous classes can be used in place of the full class definition for throwaway objects.

<?php
interface Logger {
    public function log(string $msg);
}

class Application {
    private $logger;

    public function getLogger(): Logger {
         return $this->logger;
    }

    public function setLogger(Logger $logger) {
         $this->logger = $logger;
    }
}

$app = new Application;
$app->setLogger(new class implements Logger {
    public function log(string $msg) {
        echo $msg;
    }
});

var_dump($app->getLogger());
?>

Unicode codepoint escape syntax

A valid Unicode codepoint character can be converted to UTF-8 corresponding character. All the leading 0’s will be neglected.

<?php 
	echo "\u{aa}";
	echo "\u{0000aa}";
	echo "\u{9999}";
?>

The above example will output:

ª
ª (same as before but with optional leading 0’s)

Closure::call()

Closure::call() is a way of temporarily binding an object scope to a closure.


<?php class MyClass { private $val = 1; } $getVal = function() {return $this->val;}; 
echo $getVal->call(new MyClass);
?>

Group use declarations

Classes, functions, and constants being imported from the same namespace can now be grouped together in a single-use statement.

<?php
	use some\namespace\{ClassA, ClassB, ClassC as C};
	use function some\namespace\{fn_a, fn_b, fn_c};
	use const some\namespace\{ConstA, ConstB, ConstC};
?>

Here we don’t need to import one by one, we can import all the classes in a single call. Similarly the functions and constants also.

Now we are able to understand the new updates in PHP 7. Hope this will help. Happy Learning 🙂

Spread the love

Yashwant Kanetkar’s Let us C Book Review

Book Name: Let Us C

Authored By: Yashwant Kanetkar

The book doesn’t need an introduction, Let Us C, One of the best book for fundamentals of not only C language but of programming. The first programming book for most of the programmer in their life.

In the journey from your very first program to print “hello world” to writing complex algorithm you can’t deny the concepts you have learned from this book. This book has sold 3 millions of copies.

The Best Computer Programming Book

The book is focused on concept building and strengthening the foundation of programming skills. The book starts with the “hello world”. Everything in this book is fundamental. You can recommend this book to any newbie. This is best Computer Programming book.

This equally useful for both the beginners and for those who are experienced and want to improve their fundamentals.

If you want to know the answers to the following questions and you are going to start programming, then just start with Let Us C.

  • how you will use keywords?
  • how you will use loops?
  • how you will use conditional statements?
  • how you will use pointers?
  • what are arrays?
  • what are functions?
  • how you can define your own function?
  • what is return type?
  • what is recursion?
  • what is pointer?

About the author: Yashwant Kanetkar

Yashvant Kanetkar has authored several books on many programming languages. He is a post-graduate from IIT Kanpur and He is recognized and awarded as Microsoft Most Valuable Professional multiple times for his contribution.

Content and language

The structure of the book is revised and improved many times. We can it designed in a way that we can’t complain about the hierarchy of concepts. The language in the book is very clear and to the point. It is easy to understand and grasp.

After so many editions have been published you will find zero printing and spelling error in this book. The book is loved by millions of readers worldwide because of its content and representation. You cant find any complex sentence. The simplicity is being taken care of.

The flow of concepts was explained by beautiful examples and algorithms.
Every concept in this book is defined with practical implementation. The success of this book is language and content that is self-explaining.

You can say it is a self-learning guide for beginners. As C is the mother of all the modern computer languages, this book is also the mother of all the modern programming language books.

What you will find in this book?

The book is focused to build the fundamental programming skills of readers, so you can find the following things in this book:

  • The syntax of C language.
  • The fundamental concepts of variables and their types, memory management.
  • The conditional structures like If-else and switch-case.
  • The loops like for, while and do while.
  • The fundamental of continue, goto.
  • The library functions and user-defined functions.
  • About the recursion.
  • The fundamental mathematical operations using C programming.
  • Graphics Library and programs that uses these libraries.
  • About return type and void, main.
  • Fundamental algorithms like swapping, factorial, prime number, odd and even number, star pattern printing.
  • Using pointers, call by value and call by reference concepts.
  • Common bugs and error.
  • Exception handling using try and catch statement.

Readers Review and ratings

The book has given a tremendous response and wonderful feedback from the readers. It is owned by 30 million users and continues. It has enough 5-stars ratings and positive feedback on websites. You should definitely go for it.

Spread the love

BEGINNER’S GUIDE TO LEARN PYTHON IN 7 DAYS[Book Review]

Author Name:

Ramsey Hamilton

Overview:

Python is one of the trending programming languages of the time having huge demand in the Software Development Industry.

There is a number of books written to guide Python Programming.

This Book is one of them that says that one can learn Python in seven days.

The book is very well structured and mention every aspect to guide the readers about Python.

This is one of the best python textbooks. This book is counted in the best programming books.

It is always recommended to read a book when you are going to learn anything from the beginning and This book is fulfilling the requirement of beginners.

Examples and programs are well explained and details are being given.

The book is enriched with a number of famous algorithms and recursion problems.

It is worth reading this book if you are looking for a book on Python. The book is available in Paperback Edition(Printed) and Kindle Edition.

This book is offering clear, concise and practical code snippets to illustrate both syntax and logic of the Python programming language.

Although the book contains only basic concepts readers will surely need one more advanced version of this book has advanced concepts.

Language :

The language of the book is very nice and one can understand it after just one look.

Content in the book are well organized and well placed and connected.

Never you fill that they have escaped something that you should know.

It is like building blocks of concepts. The language of this book makes it the best notebook.

As you start reading the pages one by one you will be adding more and more concepts to your understandings. Overall the content is comprehensive, well-explained and well-curated.

 

What are the main contents in this book:

  • How to set up the environment for Python
  • Getting started with Python
  • Defining variables and reserved Keywords
  • Looping structure in Python along with doing, while,do-while, for
  • Conditional statement
  • Switch Case statement
  • Functions and User-defined functions
  • Dictionaries, Lists, and Tuples
  • Classes and Objects in Python
  • What is a module in Python
  • File IO Operations
  • Error and Exceptional Handling

Customers Rating and Reviews on Amazon:

This is the highest rated book in its category on Amazon and more than 50% Ratings are 5 stars, more than 20% Ratings are 4 stars and overall it has 4.1 out of 5-star rating.

The user has given a wonderful response to this book.

This book is highly recommended by users.

According to readers, this is well suited for beginners and It covers all basic and fundamental concepts of Python Programming language.

Some of the readers have complained about spelling mistakes and lack of proofreading and that is already known to Author and Publishers.

I hope the latest version will resolve the errors.

Spread the love

What is the Storage Engine in MySQL

Following Question Based on MySQL Storage Engine covered in this Section:

  1. What is storage engine?
  2. How many types of storage engines are there in MySQL?
  3. What are the features of Different type of storage engines?
  4. Why Memory is faster than MyISAM and InnoDB?
  5. Which one is the Transaction Compatible Engine?
  6. Which are the storage engine in MySQL , do not use Indexing?
  7. What are the main difference between in MyISAM and InnoDB?
  8. Which version of MySQL support Transaction?

MySQL Storage Engine

Storage Engine in MySQL is the bottom most layer and stores data in various formats. Based on their techniques and compatibility for different types of application we choose which one would be suitable. MySQL has number of storage engines. Few of them are transactional and few are non-transactional. Here is the list of popular storage engines in MySQL:

  1. MyISAM
  2. InnoDB
  3. Memory(HEAP)
  4. Archive
  5. CSV
  6. MERGE

MyISAM

This is a non-transactional storage engine and a table can hold up to 256 TB data. Before MySQL 5.5 MyISAM was the default storage engine, but after Introduction of transaction support InnoDB is the default storage Engine in MySQL. Data in MyISAM is compressed and optimized for quick access. Earlier it was known as ISAM. It can repair the corrupted tables itself on startup.

InnoDB

InnoDB is the most widely used storage engine now a days and used as a default storage engine in MySQL. It is transaction safe and compatible to ACID properties of database transactions. It supports all the DML, DDL and DCL operations. It can hold up-to 64 TB data in a table. It also uses compression techniques to store data.

MEMORY

Memory Engines store data in Memory. It uses the hash index techniques to store data and hence the access of data is comparatively faster than MyISAM and InnoDB. In Memory data is stored in the form of HEAP tables.

Archive

The engine is used for archiving the records. It can be used to archive the huge amount of data and records. It stores data in compressed format and when an access request is come it serves the data after decompressing the archives. We can not have Indexing in Archive engines so we have to scan all the data to get the particular records.

CSV

CSV is a well-known spreadsheet format. It is also used for Non-SQL based systems to store and retrieve data. Data is stored CSV format or comma separated formats. This is also a non-indexing technique. We can not have a NULL value in CSV. It also required to read full table to get a record. Hence it is slower than InnoDB and MyISAM.

MERGE

MERGE is storage engine that uses MyISAM tables as component and merged them to store as a single table. MERGE tables use Indexes of component tables, they do not have their own indexes. When we run DROP command then It does not drop tables in real, but the merger splits.

Spread the love

PHP Advanced Interview Questions and Answers For Experienced

We brought here some advanced PHP interview questions that need special attention while preparing for an Interview.

We have collected these questions and answers from various sources and candidates have been appeared in multiple PHP Developer Interviews.

These questions are useful for Freshers searching jobs for PHP developers and also for the people looking for a change having 2+ years experience.

Find the latest PHP MySQL interview questions and answers for experienced in 2020.

These are not pure practical based questions but they have a huge impact on your selection for the right job.

How we can set default time-zone in PHP?
Using library function date_default_timezone_set() we can set default time-zone:

<?php date_default_timezone_set("America/New_York"); echo "Time in Default Zone is : " . date("h:i:sa"); ?>

What is difference between == and === ?
Both are the comparison operator. The first one (==) is ‘Equal to’ and the second one (===) is ‘identical to’. ‘Equal to’ is used to compare the values of variables. ‘Identical to’ is used to compare values as well as the type of variables.

For Example :

<?php $x = 1250; $y = '1250'; if($x==$y){ echo 'X and Y are Equal'; }else{ echo 'X and Y are Not equal'; } if($x===$y){ echo 'X and Y are Identical'; }else{ echo 'X and Y are Not Identical'; } ?>

What is difference between != and !== ?
Both are the comparison operator. The first one (!=) is ‘Not Equal’ and second one (!==) is ‘Not identical’. ‘Not equal’ is used to compare the values of variables. ‘Not Identical’ is used to compare values as well as the type of variables.

For Example :

<?php $x = 1250; $y = '1250'; if($x!=$y){ echo 'X and Y are Not equal'; }else{ echo 'X and Y are Equal'; } if($x!==$y){ echo 'X and Y are Not Identical'; }else{ echo 'X and Y are Identical'; } ?>

How do I get PHP Errors to display?
Use the following code snippet to on error reporting in a PHP script:

<?php 
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);

But we can not display PHP parse error this way. We need to modify php.ini file and need to ‘on’ the display error:

display_errors = on

What is the difference between Notice Errors and Warning Errors in PHP?
Notice and Warning are the Non-fatal Errors and Not let the script halted.
Notice is an Advisory message regarding what you should prefer to do with this line of code.
For example, using an undefined variable is a Notice.

 

 

 

The warning is the message saying that you are going wrong and that may cause an error in the future so, you may correct that. For example, including a not existing script will throw a Warning.

 

 

What is the use of break and continue in the PHP loop?
Break: It terminates the loop and exit from the iteration.

Continue: It escapes the current iteration and starts a new iteration in the loop.

What are the common types of errors that occur in Php execution?

Php has Identified numbers of Error detection categories. Following are the common errors in PHP:

E_ERROR: A fatal error and halts the script from further execution.

E_WARNING: Run time warning that detects something is wrong that you need to correct to avoid future errors.

E_PARSE: Compilation error when the code is parsed. We need to on the error reporting in php.ini file to get this.

E_NOTICE: Run time notice to notify that you should go follow the suggested message.

E_CORE_ERROR: It is a fatal error that halts the script and occurs at the initial startup of PHP.

E_CORE_WARNING: Warnings that occurs at the initial startup of PHP.

E_COMPILE_ERROR: Fatal error on compilation occurs at the initial startup of PHP.

E_USER_ERROR : User-generated error message.

E_USER_WARNING: User-generated warning message.

E_USER_NOTICE: User-generated notice message.

E_STRICT: Run-time notices.

E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error

E_ALL: Catches all errors and warnings

Difference between mysql_connect and mysql_pconnect?
When mysql_pconnect() is used to create and maintain a persistent connection to the database that means a SQL link that does not close when the execution of your script ends whereas mysql_connect() creates a new connection each time when it called.

When a persistent connection is created and again a connection request is called the mysql_pconnect() return the earlier established connection rather than creating a new instance of connection.

What do you understand by &$name?
Using the reference of the variable rather than a copy of that.

If we pass the reference of a variable in a function as an argument and the value is changed then the value of the original variable outside the function is also changed.

This is passing by reference.

What is New in PHP 7?
PHP 7 has many new features. Here is the list of PHP 7 New features:

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Unicode codepoint escape syntax
  • Closure::call()
  • Group use declarations

When you are going for a PHP Developer job you should also focus on Jquery Interview Questions, PHP-MySQL Interview Questions, PHP Functions asked in Interviews.
I hope you enjoyed learning. You can ask any question based on the Above topic or you can submit questions here in the comment box.

Spread the love

CakePHP 4.0.0 alpha is released

The new and most awaited version of the rapid development framework is released by the core team of CakePHP.

The alpha released yet is not recommended for development purpose, until the stable version come. Removing the drawbacks and implementing new features , library support and improved performance the new version of cakephp will be rocking soon.

What are the new features in CakePHP 4.0.0

The Directory structure and the Bake console is rewritten to ease the development process and to increase development speed.

CakePHP was using Foundation framework for CSS and UI , but they are going to discontinue this associations and will go with the new one i.e. milligram.

Automatic Time zone handling by the ORM if any difference is found between Database timezone and server timezone.

All the deprecated features will be removed completely in new version.

CakePHP will not support PHP 5.6 and PHP 7.0, The minimum version that will be acceptable is PHP 7.1.0. Further It will be modified to PHP 7.2.0 as a minimum acceptable version of PHP.

An improved type-hinting will be added.

Error and warning reporting system is improved.

Validation messages will be embedded in Form helper and date-time input is introduced.

Authentication functionality has been split into standalone plugins Authentication and Authorization.

Spread the love

What is Singleton Design Pattern?

Singleton pattern is a technique to provide a class global state. Once we have created the instance of the class we can use the existing instance multiple times. So it restricts the multiple instantiation of a class.It is a great example of re-usability in Object Oriented Programming System.

How it works?
We restrict the constructor while declaring it as private , of the class to access it from outside and a static method is created that returns the instance.

Example in PHP:

<?php 
class SingletonClass {
  private static $the_instance = null;
  
  //the private constructor
  private function __construct()
  {
    
  }
 
 //public static function to return the instance
  public static function getInstance()
  {
    if (self::$the_instance == null)
    {
      self::$the_instance = new SingletonClass();
    }
 
    return self::$the_instance;
  }
}
?>

Usage of Singleton Class:

Connecting A database and use exiting connection, to avoid multiple open connection issue:

<?php 
	class DB {

	  private static $instance = null;
	  private $conn;
	  
	  private $host = 'localhost';
	  private $user = 'root';
	  private $pass = 'password';
	  private $name = 'my_database_name';
	   
	  private function __construct()
	  {
	    $this->conn = new PDO("mysql:host={$this->host};
	    dbname={$this->name}", $this->user,$this->pass,
	    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
	  }
	  
	  public static function getInstance()
	  {
	    if(!self::$instance)
	    {
	      self::$instance = new DB();
	    }
	   
	    return self::$instance;
	  }
	  
	  public function dbConnection()
	  {
	    return $this->conn;
	  }
	} 
?>

Now creating an Instance using the static method:


<?php 
	$the_instance = DB::getInstance();
	$conn = $the_instance->getConnection();
?>
Spread the love

Embedded using C Interviews Questions and Answers

What is an Embedded system? Describe Embedded C.

In simple words, the Embedded system can be referred to as customizing hardware with customizing the software. Embedded systems are controller-based which is embedded with software to perform specific tasks.

Embedded C is an extended version of C language which is used to develop microcontroller-based systems.

 

What are little endian and big endian types of storage? How can you identify which type of allocation a system follows?

Big-endian and little-endian are two formats to store multibyte data types into the computer’s memory. Big-endian format and little-endian format. In Big-endian format, MSB(most significant byte) gets memory first and LSB (least significant byte) in last.

In the case of little-endian format the LSB byte gets memory first and MSB byte in last.

Suppose an integer having value 0x12345678.

In the case of big-endian 0x12 gets stored first in memory, then  0x34, then 0x56 and in the last 0x78.

In the case of little-endian 0x78 gets stored first in memory, then  0x56, then 0x34 and in the last 0x12.

0x12 0x34 0x56 0x78
0x2000 0x2001 0x2002 0x2003 0x2004
Memory address
Big Endian Format
0x78 0x56 0x34 0x12
0x2000 0x2001 0x2002 0x2003 0x2004
Memory address
Little Endian Format

 

Write a C program to identify little and big endian.

#include <stdio.h>

int main ()

{

 unsigned int x = 0x12345678;

 char *c = (char*) &x;

 if (*c == 0x78)

 {

   printf (“Architecture is little endian. \n);

 }

 else

 {

    printf (“Architecture is big endian. \n);

 }

 return 0;

}

 

What is ISR(Interrupt Service Routine)?

ISR refers to the Interrupt service routine. Whenever an interrupt occurs, the controller completes the execution of the current instruction and starts the execution of an Interrupt Service Routine. This process is also known as an interrupt handler.  

 

What is a Qualifier in C?

Qualifiers are the keywords which are used to modify the values of variables. There are two types of the qualifier in C.

Const

Const qualifier used with a variable when we want to make variable to unchangeable. If you will try to change, the compiler will give you an error.

Volatile

Variable qualified with volatility prevents the compiler to optimize that variable. The values of the variable can be changed by code outside the scope of the current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in a temporary register.

 

What is a ‘volatile’ variable, can a variable be both constant and volatile, can a pointer be volatile?

Consider the following example:

volatile int x;

When the compiler finds the variable qualified with the volatile qualifier, it clearly comes to know to the compiler that it will not be involved in any change related to the variable. The value of this variable can be changed anytime by any external source.

A single variable can be const as well as volatile. Example

int volatile *const y;

y is a constant pointer to a volatile integer.

Yes, volatile pointers are possible in c.

int *volatile value;

 

What is interrupt latency? How to reduce interrupt latency?

Whenever a microcontroller receives any interrupt, first it completes currently executing the instruction , then provides service to interrupt and again continues the executing instruction from the same position where the controller skipped.

So, it takes some time to microcontroller to provide service to interrupt. The amount of time(Number of cycle) taken by microcontroller to start servicing to interrupt known as interrupt latency.

Interrupt latency can be minimized by writing short ISR routine and by not delaying interrupts for more time.

 

Can we use any function inside the ISR?

Yes, we can but doing so will increase interrupt latency. That’s why it is not recommended as in many cases latency should be as small as possible and using a function inside the ISR will also decrease performance.

 

What are storage classes?

Storage classes used to classify variable as per their scope (visibility) and  lifetime. Default value and storing value place also different to each other. There are four types of storage classes.

 

Variable Scope Lifetime Default Value
Auto Local Within the function Garbage value
register Local Within the function Garbage value
Static Local Till the end of the program Zero
extern Global Till the end of the program Zero

Note: Only register variables get memory in a CPU register (if CPU register has vacant memory). Other three variables get memory in RAM memory locations.

 

What is use of static keyword?

Static keyword can be used with variable as well as functions. The life of static variable lasts till the end of the programs and scope is local(Visible within the function only). Still static variable holds  their value after they are out of their scope.

#include<stdio.h>

int increment()

{

 static int count = 0;

 count++;

 return count;

}

  

int main()

{

 printf(“%d “, increment());

 printf(“%d “, increment());

 return 0;

}

Output: 1 2

Function with static within any source file can accessible to only that source file.By using static we make function local only to source file within it is defined.

 

What is use of register storage class?

In register storage class CPU registers are used to store values.

for example. If you want to store variable which will be frequently required then you can store it in the register like in case of loops. However it is not guaranteed that variable will get store in register.

It is like a request to CPU to allow the variable to store in CPU’s register.

If CPU has vacant register to store variable ,it permits otherwise ignore the request and variable gets allocated in ram memory.

Note: We cannot obtain the address of a register variable using pointers.

 

What is Synchronous and asynchronous data transmission?

Serial data communication has two types.

Synchronous data transmission

Synchronous transmission needs a clock signal between the source and target to let the target know of the new byte.synchronous transmission data is transmitted in the form of data bundles. So data rate of it very high.

Asynchronous data transmission

Asynchronous transmission has no need of clock signal between the source and target. It sends start and stop bit to start and stop the transmission. It send single-byte data at a time so data rate of it is not much good.

Synchronous vs. Asynchronous Transmission

  1. In synchronous mode, data is transmitted in the bundle but in asynchronous mode, data is transmitted byte by byte.
  2. Synchronous required a clock signal between the source and destination to acknowledge the destination about information while in asynchronous clock signal is not required.
  3. Data transfer rate of synchronous is faster compared to asynchronous .
  4. Synchronous mode has lower overhead compared to asynchronous transmission.

 

What is Baud Rate? How it differs from Bit Rate?

In data communication, data are transferred along with signal. The number of the signal transferred per second is known is Baud rate. Bite rate is a number of bits (data) transferred per second. As a single signal may contain more than 1 bit while transferring the data. The relation between the two is given below.

Bit rate = baud rate x the number of bit per baud

 

What is memory leak ? How we can avoid it?

The memory leak is a condition where the programmer allocates memory in the heap area by using dynamic memory allocation and forget two deallocate. So, it is recommended to use the free() function to deallocate memory which is allocated by dynamic memory allocation once the use of memory location is not further needed.

 

How to set, clear and toggle a single bit of variable?

The value represents the initial variable and position represents the position of bit in a variable.

Setting a Bit:

Value |= (1 << position)

Clearing a Bit:

Value &= ~ (1<<position)

Toggling a Bit:

Value ^= (1 << position)

 

What is Dynamic Memory Allocation(DMA)? What is the difference between malloc() and malloc()?

Dynamic memory allocation (DMA) is the process of allocating memory for variables at run time of the program. This kind of allocation allocates memory in the heap area of memory.

malloc function takes one argument at calling but calloc takes two arguments. Also, memory allocated by calloc is initialized with zero.

These functions always return pointer of type void which can be cast into a pointer of any form.

Syntax: For 5 element of int type variable. ptr is int type pointer.

ptr = (int *) malloc (5*sizeof(int))

ptr =  (int*) calloc (5, sizeof(int))

 

What are void pointers in C?

Void pointer also known as generic pointers. There is no data type associated with these, so these can be typed cast to any type.

 

What is a dangling pointer?

A pointer pointing to deleted or deallocated memory  location is known as dangling pointer. To try to access this type of pointer causes undefined behavior or segmentation fault.

 

What is a wild pointer?

An uninitialized pointer is known as a wild pointer. When we declare any pointer without giving any address, it shows an arbitrary memory location. As we assign it a memory location, it is not a wild pointer anymore.

Ex:

int main()

{

           int a;

           int* ptr;              //Wild pointer

           ptr = &a;           //Not more wild pointer

           return;

}

 

Explain the meaning of these pointers?

 

  • int *ptr;
  • cons int * ptr;
  • int * const ptr;
  • const int *const ptr;

 

int *ptr

It is a pointer to a variable. We can change the value pointer pointing to and also the value of ptr.

 

const int * ptr

It is a pointer to a constant.  It can be also declared as int const *ptr. We can change the pointer to point other variable but we can not change the value of it by using the pointer.

 

int * const ptr

It is a constant pointer to a variable. We can change the value of the variable by using pointer but we can not change the pointer to point other variables.  

 

const int *const ptr

It is a constant pointer to a constant variable. Neither we can change the pointer to point other variable nor we can change the value using the pointer.

 

Spread the love

Android Technical Written Questions and Answers

Which of these can be used to fully abstract a class from its implementation?

  1. Objects  
  2. Packages
  3. Interfaces
  4. None of the Mentioned.                  

Answer: 3

Which of these keywords is used by a class to use an interface defined previously?

  1. import
  2. Import
  3. implements
  4. Implements                                 

Answer: 3

 

Which of these operators can be used to concatenate two or more String objects?

  1. +  
  2.  +=   
  3.  &  
  4.  ||                                                           

 

Answer: 1

 

Which of these methods of class String is used to extract a single character from a String object?

  1. CHARAT()
  2. charat()
  3. charAt()
  4. ChatAt()                                 

 

Answer: 3

 

Which of the following can be operands of arithmetic operators?

  1. Numeric
  2. Boolean
  3. Characters
  4. Both Boolean & Characters                

 

Answer: 4

 

What is an activity in Android?

  1. Activity performs the actions on the screen
  2. Manage the Application content
  3. Screen UI
  4. None of the above                                                           

 

Answer: 1

 

What are the layouts available in android?

  1. Linear Layout
  2. Frame Layout
  3. Table Layout
  4. Relative Layout
  5. All of the above                                                                 

 

Answer: 5

 

A type of class that will be responsible to design main screen activity on first time launch of application is called:

  1. Activity class
  2. Parent class
  3. Child class
  4. Inherited class                                                                 

 

Answer: 1

 

Android component that manages appearance and format on screen is called

  1. fragment
  2. intent
  3. view
  4. layout

 

Answer: 4

 

Android component that works like a database

  1. Services
  2. Activities
  3. Broadcast Receivers
  4. Content Providers

 

Answer: 4

 

What is the o/p of the following program?


public class MyClass{

public static void main(String[] args) {

int[] dest = new int[]{0,1,2,3,4,5};

   System.out.println(dest[0]+ dest[5]+dest[2]);

 }

}

 

  1. 052
  2. Compilation Error
  3. 7
  4. 152                                                                       

 

Answer :3

Write a java program to reverse a string?

Solution:  


String str = "MyJava";

char[] strArray = str.toCharArray();

for (int i = strArray.length - 1; i &gt;= 0; i--)
{
 System.out.print(strArray[i]);     //Output : avaJyM
}

 

How do you find duplicate characters in a string?

Solution:       


class DuplicateCharactersInString{

 static void duplicateCharCount(String inputString){

 //Creating a HashMap containing char as key and it's occurrences as value

HashMap&lt;Character, Integer&gt; charCountMap = new HashMap&lt;Character, Integer&gt;();

 //Converting given string to char array

 char[] strArray = inputString.toCharArray();

 //checking each char of strArray

for (char c : strArray)

{

if(charCountMap.containsKey(c))

{

//If char is present in charCountMap, incrementing it's count by 1

            charCountMap.put(c, charCountMap.get(c)+1);

}

else

{
//If char is not present in charCountMap,

  //putting this char to charCountMap with 1 as it's value

 charCountMap.put(c, 1);

  }

}

  //Getting a Set containing all keys of charCountMap

Set&lt;Character&gt; charsInString = charCountMap.keySet();

System.out.println("Duplicate Characters In "+inputString);

 //Iterating through Set 'charsInString'

 for (Character ch : charsInString)

{
 if(charCountMap.get(ch) &gt; 1){

 //If any char has a count of more than 1, printing it's count

               System.out.println(ch +" : "+ charCountMap.get(ch));
 }

 }

  }

   public static void main(String[] args)

  {

 duplicateCharCount("JavaJ2EE");

duplicateCharCount("Fresh Fish");

 duplicateCharCount("Better Butter");

 }

}

Output :

 

Duplicate Characters In JavaJ2EE

E : 2

a : 2

J : 2

Duplicate Characters In Fresh Fish

F : 2

s : 2

h : 2

Duplicate Characters In Better Butter

t : 4

e : 3

r : 2

B : 2

 

How many objects will be created in the following code and where they will be stored?

String s1 = new String(“abc”);

String s2 = new String(“abc”);

 

Two objects will be created and they will be stored in the heap memory.

 

Java program to sum the elements of an array?

 

Solution:


class SumOfArray{

   public static void main(String args[]){

      int[] array = {10, 20, 30, 40, 50, 10};

     int sum = 0;

     //Advanced for loop

      for( int num : array) {

          sum = sum+num;

     }

      System.out.println("Sum of array elements is:"+sum);

   }
}

Output:

 

Sum of array elements is:160

More Interview Questions and Answers on Android:

20 Android Interview Questions and Answers : Basic Level

Android Interview Questions and Answers for freshers

Spread the love

Top 5 Programming Languages of Time

A comprehensive overview of the great programming languages of the modern era is here. Be it Java programming, javascript, swift and object-oriented languages. The comparison is very tough because they all have some unique features that can not be replaced. It is on the application and usability that what we are going to opt.

Java

Java is the most popular Object Oriented Programming language and first choice of the programmers. It is a WORA i.e. Write Once and Run Anywhere. A compiled Java code can be run on any platform without recompilation and that is the beauty of Language. Compiled byte-code run on JVM – Java Virtual Machine.

Created by

Java is developed by James Gosling a Canadian and at Sun Sun Microsystem in the year 1995 . Right now Sun Microsystem is acquired by Oracle.

The latest version released in March 2019 is Java SE 12.

Features of Java

  1. Object Oriented Programming Systems
  2. Robust and Reliable
  3. Used for High-performance applications
  4. Portable and Platform independent

Which Type of Applications can be designed on Java

  1. Web Applications and Websites like banking, ticket booking applications.
  2. Mobile Applications like Games.
  3. Desktop Applications
  4. Web Servers

Java Development Frameworks : Hibernate,Spring MVC,Apache Struts etc

Website : https://www.java.com

Python

High performance and most lovable programming language of the recent time is Python. It is popular because of its different syntax and style of coding standard. Unlike almost the language it doesn’t use semicolon (;) and multiple white spaces.It is an High- Level and interpreted Language.

Created by-

Python is created by Guido van Rossum and in 1991 the first release was available for public use.

Features of Python-

  1. Readability
  2. Automatic memory management
  3. Run time type casting
  4. The rich and comprehensive library
  5. Object-oriented Programming System

Applications of Python-

  1. Artificial Intelligence
  2. Machine Learning
  3. Web applications
  4. IoT- Internet of Things
  5. Automation
  6. Software Testing
  7. Python is widely used in scientific and numeric computing.
  8. Desktop GUI

Python Development Frameworks : Django, Pyramid, Flask , Bottle etc.

Websites : https://www.python.org

JavaScript

JavaScript is all time hit and fit. One of the core technological part of WWW after HTML and CSS. It is a simple, lightweight and powerful client-side programming language. JavaScript is Object Based Language, not a full-fledged Object Oriented Programming Language. Nowadays JavaScript is developed as a most significant tool for software and website development. It is easy to animate and make interactive web pages using JavaScript. Now JavaScript is under Oracle.

Created by-

Developed in 1995 by Netscape and was known as Live Script. It is also known as ES6 Script . The task of development was done under supervision of  Brendan Eich .

Features of JavaScript-

  1. Prototype Language
  2. Lightweight
  3. Object-based
  4. Event Driven Language
  5. It depends on the Host Environment.

Application of JavaScript-

  1. Interactive web pages
  2. Animations
  3. One Page applications
  4. Asynchronous Loading
  5. With Node Js it can be used as a Server side tool.

JavaScript Framework : Angular,React,Vue,Django etc.

Website: https://www.javascript.com/

C Programming

C is an imperative and structured procedural programming language. It is known as the Mother of All the modern programming language. Almost the languages use syntax similar to that of C.It provide Low-level memory access and fastest among all language. Almost the Operating systems are written in C including Windows,Mac, Linux.

Developed By-

C was originally developed at Bell Labs by Dennis Ritchie, between 1972 and 1973. This is the most popular programming language nowadays.

Features of C-

  1. Structured and robust,reliable
  2. Fast and procedural
  3. Low memory access
  4. Cross platform compatibility

Applications-

  1. System Software and OS.
  2. Widely used in Embedded systems.
  3. Various range of application software.
  4. Supercomputers.
  5. Develop New Programming languages and compilers.

Swift

Swift is inherited from Objective C. Largely Objective C is used by Apple to develop its product.  Now swift is an alternative of Objective C.It is a Protocol Oriented Programming Language and widely used for Developing applications for iOS,Mac . Swift works with  Apple’s Cocoa and Cocoa Touch frameworks.

According to fact represented by Wikipedia , Swift won first place for Most Loved Programming Language in the Stack Overflow Developer Survey 2015 and second place in 2016.

Development of Swift-

Development of Swift started in July 2010 by Chris Lattner and was introduced at Apple’s 2014 Worldwide Developers Conference.

Features of Swift-

  1. Protocol oriented Programming language
  2. Compiled Programming language
  3. Dynamic Dispatch
  4. Late binding
  5. Named parameters

Applications of Swift-

  1. An alternative to Objective C
  2. Widely used for Apple Inc. Products, like iOS, Mac,watchOS, tvOS etc.

Frameworks for Swift: Cocoa and Cocoa Touch frameworks

Source from https://en.wikipedia.org/

More Useful articles:-

20 Android Interview Questions and Answers : Basic Level

https://www.interviewsortout.com/c-programming-interview-questions-and-answersresults/

OOPS interview questions and answers

Spread the love

C Programming Interview Questions and Answers

What is the purpose of printf() and scanf()?
printf () and scanf() are the two main functions in C Language that can be used to send output and receive input from the standard output and input respectively. They are defined in stdio.h

How to check equality between two variable in C language?
In C language the operator “==” is used to check equality of two values, while the symbol “=” is used for assignment. For example the expression: y==x will be evaluated to either 0 or 1 (depending on the actual value of x and y), while the expression y=x will assign y the value of x.

What is meant by increment operators in C?
In C language there is a short way of incrementing (++) or decrementing (–) a variable by 1. These operators are called increment operators. They can have the form of prefix (e.g., ++x) or postfix (e.g., x++).

What will be the value of the variable y in the following expression:
x=7;
y=5+x++;
The value of y will be 12, since the old value of x (here 7) will be added to 5 before x is incremented.

Write down the output of this C program:

#include 
int main(){
   int x, y;
   x=y=15;
   printf("x=%d,  y=%d\n", x,y);
  return 0;
}

The output will be:
x=15, y=15

What are the two operators that used in dynamic memory allocation in C?
malloc() and free(). The function malloc() can allocate a block of memory dynamically, while free can free this block.

How arrays are declared in C language?
Arrays in the C language are declared by giving the data type following by the variable name and finally the array size in two brackets. For example the expression:

int x[10];

declares an array called x of type integer with 10 elements.

Can two C structures added together using the plus operator?
no, in C language you cannot apply arithmetic operators directly on the structure. Instead, you will need to manipulate the structure element individually.

What is mean by function declaration and function definition in C language?
In C language , the function can be first declared to tell the compile about its signature. This will allows such functions to be called in program position before its actual definition. However, function definitions involve writing exactly what this function should do when it is executed.

How structures are declared and defined inside the C language?
Structures in C languages are usually declared by the word struct followed by the name of the structure. The elements of the structure are enclosed in curly brackets and the structure definition is terminated by a semicolon at the end. For example, the following lines are an example for declaring a structure called Point:

struct Point{
   int x;
   int y;
};

In C language, after a structure is declared it can be used after words by writing the word structure followed by the variable name, for example:

struct Point p1;

What is the purpose of C pre-processors in the C languages?
In C language the pre-processors directives are not part of the compiler, instead they instruct the compile to perform certain operations at compile time. For example, the include directive (#include) is used to ask the compile to include a header file to the currently compiled code.

How to declare an array of 100 integer values in C?
This can be declared as:

int a[100];

How to pass an array of type float to a Function?
Array can be passed to functions in many ways. For example they can be passed to functions as a pointer, for example:

void somefunc(int*a);

or as a sized array:

void somefunc(int a[10]);

It can also be passed as upsized array:

void somefunc(int a[]);

In this last approach, we will need to pass the array size as a seprate variable.

Declare a two dimensional array in C of size 10×50
It can be declared as follows:

int a[10][50];

The first parameter in brackets will represent the number of rows while the second parameter will represent the number of columns.

Describe the difference between for and while loops in C language.
In C language, as well as in many other computer languages, for loops can be used when the beginning and end of the loop is definitely known. In this case, it will be very convenient to use for loop. However, if we do not know exactly the start and end of the loop, we can use while loop instead.

What is meant by recursion in C language?
Recursion simply means a function that calls itself. In can view viewed as an alternative approach for using loops. All the calling parameter of the function is stored in the stack. The values are kept until the function is returned. A function that is used in a recursion should continue a trivial condition will stop the recursion from repeating forever. Otherwise and infinite loop could happen.

  1. Which of the following is not a logical operator in C language:
    !=
  2. ==,
  3. |= ,
  4. &&

The operator |= is not a logical operator. It is used as a combination of bitwise or and assignment operators.

What is the meaning of a pointer variables in C language?
In C language, a pointer variable is a variable that point to an address in memory. This is an efficient way in C language in order to access variable addresses from different locations in the program code.

Consider the following C program:

#include 
int main(){
   int x=7;
   int *px;
   px=&amp;x;
  *px=18;
   printf("x=%d", x);
   return 0;
}

What will be the output of this program?
x=18

What is the purpose of the function sizeof() in C language?
The sizeof() in C language is used to calculate and return the size of variable and data types.

When one should use do while loop in C language?
Do while loop is used in C language to repeat the loop at least one time before the loop condition for termination. Therefore it is very helpful in certain scenarios where we need to execute the code at least one time before deciding to terminate or not.

What is the difference between const pointer and pointer variable in C language?
const pointers are defined in this way:

int *const ptr;

They can be used to refer to the address of other variables like this
ptr=&var
However, what we cannot do using const point is the increment operator. In other words, we cannot write something like this:
ptr++;
In contrast, pointer variables can be modified by either ways.

How to allocate dynamic two dimensional arrays in C language?
There are many different ways to dynamically allocate two dimensional arrays. May be the best way is to tread them as static arrays by allocating rows of pointers and each row is then assigned to a dynamic array representing the columns. So we can do it in these steps:

int** a;     
/*assume this array is of type int*/

a=(int**)malloc(sizeof(int*)*rows);    
/*rows represent the number of rows in the array*/
if(a==NULL) return;                            
/*make sure the memory is correctly allocated for rows*/
int i;
for(i=0;i&lt; rows; i++)
  a[i]=(int)malloc(sizeof(int)*cols);    
/*allocate memory for each row*/

/*TODO: make sure memory is correctly allocated*/

What is the meaning of ternary operator and how can it be used in C language?
Ternary operator is a simple expression that can be used instead of if statement. It has the following syntax:
condition? value if true: value if value;
for example:

y=x&gt;10? 2:1;

So y in this example with take either the value of 2 or 1 depending on whether x is greater than 10 or not.

How to open a file in C language?
In C language, we can use the open() function to open a file and get a point to it.

How to read/write data from/to a C file ?
There are many different ways to read/write data from and into a file. For example:
The functions: read(), write(), fscanf(), and fprintf() can be used to read/write data from/to the file.

What are the bitwise shift operators in C language?
Bitwise shift operators shift the bits of a variable. There are many types of them:
>> signed right shift operator.
>>> unsigned right shift operator.
<< left operators.
These operators can be used to manipulate variables by shifting the bit left or right.

How can you return a more than one variable in C language?
The standard way in C language is to return only one value from a function. But as a workaround we can user pointers and structures to return more than one value from the function.

Write a simple function in C language that takes two variables and then exchange their values ?

void exchange(int* var1, int* var2){
    int temp=*var1;
    *var1=*var2
    *var2=temp;
}

What is the purpose of the switch statement in C language?
Switch statement in C language are used to select one branch to execute in case of the existence of more than one alternatives.

When switch statement is preferred to be used over if-else statement?
If there are just a few branches then if-else statement can be used. Otherwise, switch can be much helpful.

What is the purpose of break and continue keywords?
break and continue are used in combination with loop statements (for, while, etc). The break statement will enforce the loop to exit from that point where break is called. But continue will ask the loop not to continue executing the remaining statements and jump back in a new iteration.

How can you specify command line arguments to your C program?
The main function can be supplied with two other variables: argc and argv and can be written in the form:
int main(int argc, char** argv){

}
The first variable will count the number of arguments, while the actual arguments will be supplied in argv.

What is the purpose of the default keyword in the C language?
The default keyword can be used in combination with switch statement to handle the default case that is not listed in any of the other cases.

How are nested loops suitable for accessing two dimensional arrays?
Two dimensional arrays consist of rows and columns. Each row can be viewed as another array with a dimension equal to the number of columns. So nested loops can look perfect for this scenario, when the outer loop will work on rows, while inner look handle columns.

How many dimensions we define for arrays in C language?
There is no limit for the number of dimensions that have be used for an array in C language. However, practically, we can use many dimension as much as the system resources permit.

What will be the output of the following C program?

#include 
int main(){
  int x=2, y=4;
 printf("%d", x==y? 5:7);
 return 0;
}

Output : 7

How the standard input and output files are represented in C language?
There are two keywords in the C language to represent standard input and output files: stdin and stdout. The former is used for standard input while the later can be used to refer to the standard output files.

Are arrays in C language passed by value or as a pointer?
When arrays are passed to functions, they are passed as pointers. One reason for this design is that arrays take much space and if they are passed by value, they will need to be copied in memory each time the function is called.

Does C language provide support for concurrency and multi-threading?
No, C does not support concurrency and multi threading. However, there are platform dependent libraries that can support that (e.g., pthreads in Linux and Linux like systems).

Spread the love