Tag Archives: programming

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

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

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

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

Common Programming Interview questions and Answers

No, any technical interview can be completed without logical questions based on simple programming techniques. When you are going for a Programmer profile, you must know the simple logic applied to make complex programs. Here is the collection of such important logical questions asked in an interview.These collection includes reverse string,factorial,star printing pattern,swap,leap year,prime number,odd-even number,palindrome etc.

 

Write PHP script to reverse string without using any PHP function.


	function reverseString($string){
		$i=0;
		$output_string='';
		while($string[$i]){
			$output_string=$string[$i].$output_string;
			$i++;
		}
		return $output;
	}
	$my_string="this is a string to be reversed";
	$output=reverseString($my_string);

 

Write a program to find Factorial Of a number without using recursion.


function findFactorial($n){
	$factorial = 1;
	if($n&amp;lt;=1){
		return $factorial;
	}else if($n&amp;gt;1){
		$i=0;
		while($n-$i){
			$factorial = $factorial*($n-$i);
			$i++;
		}
	}

	return $factorial;

}
echo findFactorial(10);

 

Write a program to find Factorial of a number using recursion.


function findFactorialRec($number){
	if($number &amp;lt;= 1){    
        return 1;   
    }   
    else{   
        return $number * findFactorialRec($number - 1);   
    }   
}
echo findFactorialRec(10);

 

Write a program to print the following Pattern

*
*  *
*  *  *
*  *  *  *
*  *  *  *  *


$n=5;
for ($i=1;$i&amp;lt;=$n;$i++){
	for ($j=0; $j &amp;lt; $i ; $j++) { 
		echo "# ";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a program to print the following Pattern.

                                 *
                             *  *
                          *  *  *
                      *  *  *  *
                   *  *  *  *  *


for ($i=1;$i&amp;lt;=$n;$i++){
	for ($j=$n-$i; $j &amp;gt; 0 ; $j--) { 
		echo "+";
	}
	for ($k=0; $k &amp;lt; $i ; $k++) { 
		echo "*";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a program to print the following Pattern.

                                  *
                               * * *
                            * * * * *
                         * * * * * * *
                      * * * * * * * * *


$n=5;
for ($i=0; $i &amp;lt;$n-1 ; $i++) { 
	for($j=$n-$i;$j&amp;gt;0;$j--){
		echo "+";
	}
	for($k=1;$k&amp;lt;=(2*$i)+1;$k++){
		echo "*";
	}
	echo "&amp;lt;br&amp;gt;";
}
echo "&amp;lt;br&amp;gt;";

 

Write a function to check if a string is a palindrome or not.


function checkPalindrome($string){
	$length=strlen($string);
	if($length&amp;gt;1){
		$mid = floor($length/2);
		$pal=true;
		for ($i=0; $i &amp;lt;=$mid; $i++) { 
			if($string[$i]!=$string[$length-($i+1)]){
				$pal=false;
				break;
			}
		}
		if($pal==false){
			return "NOT A PALINDROM";
		}else{
			return "PALINDROM";
		}
	}
}

$string ="ABCDEfEDCBA";
echo checkPalindrome($string);

 

Write a program to check whether a given number is prime or not:


function checkPrime($number){
	$check=0;
	for($i=2;$i&amp;lt;=($number/2);$i++)
	{
		if($number%$i==0){
			$check++;
			if($check==1){
			 	break ;
			}
		}
	}
	if($check==0){
		echo "$number is a Prime Number";
	}else{
		echo "$number is not a Prime Number";
	}
}

 

Write a function to test a given year is Leap Year:


function checkLeapYear($year){
	if($year%4==0){
		echo "$year is a leap year";
	}else{
   		echo "$year is not a leap year";
 	}
}

 

Write a program to swap two numbers without using any temporary variable.


function swapNumbers($a,$b){
	$a=$a+$b;
	$b=$a-$b;
	$a=$a-$b;
	echo "Now A is $a and B is $b";
}

 

Write a program to check that a given number is odd or even.


function checkOddEven($number){ 
	if($number % 2 == 0){ 
		echo "$number is EVEN"; 
	} 
	else{ 
		echo "$number is ODD"; 
	} 
} 

 

Spread the love