IT Interview Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 262

1. Explain four major OOP concepts in Java.

Real life example

Ans: Definition of OOP Concepts in Java


The main ideas behind Java’s Object-Oriented Programming, OOP
concepts
include abstraction, encapsulation, inheritance and polymorphism.
Basically, Java OOP concepts let us create working methods and
variables, then re-use all or part of them without compromising security.
Grasping OOP concepts is key to understanding how Java works.
Java defines OOP concepts as follows:

• Abstraction. Using simple things to represent complexity. We


all know how to turn the TV on, but we don’t need to know how
it works in order to enjoy it. In Java, abstraction means simple
things like objects, classes and variables represent more
complex underlying code and data. This is important because it
lets you avoid repeating the same work multiple times.
• Encapsulation. The practice of keeping fields within a class
private, then providing access to those fields via public
methods. Encapsulation is a protective barrier that keeps the
data and code safe within the class itself. We can then reuse
objects like code components or variables without allowing
open access to the data system-wide.
• Inheritance. A special feature of Object-Oriented
Programming in Java, Inheritance lets programmers create
new classes that share some of the attributes of existing
classes. Using Inheritance lets us build on previous work
without reinventing the wheel.
• Polymorphism. Allows programmers to use the same word in
Java to mean different things in different contexts. One form of
polymorphism is method overloading. That’s when the code
itself implies different meanings. The other form is method
overriding. That’s when the values of the supplied variables
imply different meanings. Let’s delve a little further.

How OOP Concepts in Java Work


OOP concepts in Java work by letting programmers create components
that are reusable in different ways while maintaining security.

How Abstraction Works


Abstraction lets programmers create useful and reusable tools. For
example, a programmer can create several different types of objects,
which can be variables, functions or data structures. Programmers can
also create different classes of objects as ways to define the objects.
For instance, a class of variable might be an address. The class might
specify that each address object shall have a name, street, city and zip
code. The objects, in this case, might be employee addresses, customer
addresses or supplier addresses.

How Encapsulation Works


Encapsulation lets us reuse functionality without jeopardizing security.
It’s a powerful, time-saving OOP concept in Java. For example, we may
create a piece of code that calls specific data from a database. It may be
useful to reuse that code with other databases or processes.
Encapsulation lets us do that while keeping our original data private. It
also lets us alter our original code without breaking it for others who
have adopted it in the meantime.

How Inheritance Works


Inheritance is another labor-saving Java OOP concept that works by
letting a new class adopt the properties of another. We call the inheriting
class a subclass or a child class. The original class is often called
the parent. We use the keyword extends to define a new class that
inherits properties from an old class.

How Polymorphism Works


Polymorphism in Java works by using a reference to a parent class to
affect an object in the child class. We might create a class called “horse”
by extending the “animal” class. That class might also implement the
“professional racing” class. The “horse” class is “polymorphic,” since it
inherits attributes of both the “animal” and “professional racing” class.
Two more examples of polymorphism in Java are method overriding and
method overloading.
In method overriding, the child class can use the OOP polymorphism
concept to override a method of its parent class. That allows a
programmer to use one method in different ways depending on whether
it’s invoked by an object of the parent class or an object of the child
class.
In method overloading, a single method may perform different
functions depending on the context in which it’s called. This means a
single method name might work in different ways depending on what
arguments are passed to it.
Example 1: For example consider we have a Class of Cars under which
Santro Xing, Alto and WaganR represents individual Objects.In this
context each Car Object will have its own, Model,Year of Manufacture,
Colour, Top Speed, Engine Power etc.,which form Properties of the Car
class and the associated actions i.e., object functions like Start, Move,
Stop form the Methods of Car Class.No memory is allocated when a
class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class
is created.
Example 2: An architect will have the blueprints for a house....those
blueprints will be plans that explain exactly what properties the house
will have and how they are all layed out. However it is just the
blueprint, you can't live in it. Builders will look at the blueprints and use
those blueprints to make a physical house. They can use the same
blueprint to make as many houses as they want....each house will have
the same layout and properties. Each house can accommodate it's own
families...so one house might have the Smiths live in it, one house might
have the Jones live in it.

What is OOP?

OOP - Object-Oriented Programming is a programming paradigm that


is based on objects. (Objects - real-world entities like book, vehicle,
tree, etc..)

Now let's see what are OOP concepts.

There are 4 OOP concepts. They are,

1. Polymorphism

2. Inheritance

3. Encapsulation

4. Abstraction

Let's discuss it one by one.

1. Polymorphism
Polymorphism is the ability to exit in many forms.

Example 1: We can take a boy as a real-world example. This boy can be


a student, a player, and a writer. So that this boy can exist in different
ways in different situations.

Example 2: Sound of animals. People have the same sound but


different animals make different sounds. The following diagram shows
few different sounds make by animals.
This what we called as polymorphism.

2. Inheritance

Inheritance means it allows classes to inherit common properties from


the parent class.

Example 1: let's assume that there is a class as Vehicle. All vehicles are
not the same. We can inherit common properties like color, size, type
from the parent vehicle class and create classes like Car, Bus, Bike.
Example 2: let's take another parent class as Animals. Here also we can
inherit common properties like name, sound, color, breed from Animal
class and create classes like Dog, Cat, Horse and etc.
3. Encapsulation

Encapsulation means it binds data and code together into one unit.

Example1; the most commonly used example is the medical capsule.


This capsule mixes few types of medicines and stored in one capsule.
Example 2: another example for encapsulation is a large organization.
An organization is consists of several departments like the production
department, purchase department, sales department, and Accounts
department. It combines all these departments together and had
formed the organization.
This is what we called as encapsulation.

4. Abstraction

In abstraction, it displays only the important information by hiding the


implementation part.

Example 1: Let's take the ATM machine. In an ATM machine, we can


perform functions like withdraw cash, deposit cash, check balance,
print bills, and so on. Even though it performs a lot of actions it doesn’t
show us the process. It has hidden its process by showing only the
main things like getting inputs and giving the output.
Example 2: The next example is the most commonly used mobile
phones. On a mobile phone, we can perform so many actions like
making a call, sending messages, take pictures, download software and
etc. We perform a lot of things but here also we don't know the inside
process of these things. Which means the implementation parts are
hidden.
This is what we called as an abstraction

• 2. How OOPS implemented in C++?


Ans: TABLE OF CONTENT:
1. Introduction
2. Class
3. Objects
4. Encapsulation
5. Abstraction
6. Polymorphism
7. Inheritance
8. Dynamic Binding
9. Message Passing
Object-oriented programming – As the name suggests uses objects in
programming. Object-oriented programming aims to implement real-world
entities like inheritance, hiding, polymorphism, etc in programming. The main
aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
Characteristics of an Object Oriented Programming language

Class: The building block of C++ that leads to Object-Oriented programming is


a Class. It is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of
that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with
different names and brand but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car
is the class and wheels, speed limits, mileage are their properties.
• A Class is a user-defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions define the properties and behaviour of the
objects in a Class.
• In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects
which shares some common properties and behaviours.
Object: An Object is an identifiable entity with some characteristics and
behaviour. An Object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.

class person

char name[20];

int id;

public:

void getdetails(){}

};

int main()
{

person p1; // p1 is a object

Object take up space in memory and have an associated address like a record
in pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can
interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and type of response returned
by the objects.
Encapsulation: In normal terms, Encapsulation is defined as wrapping up of
data and information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the functions that
manipulate them.
Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section etc. The
finance section handles all the financial transactions and keeps records of all
the data related to finance. Similarly, the sales section handles all the sales-
related activities and keeps records of all the sales. Now there may arise a
situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly
access the data of the sales section. He will first have to contact some other
officer in the sales section and then request him to give the particular data. This
is what encapsulation is. Here the data of the sales section and the employees
that can manipulate them are wrapped under a single name “sales section”.

Encapsulation in C++
Encapsulation also leads to data abstraction or hiding. As using encapsulation
also hides the data. In the above example, the data of any of the section like
sales, finance or accounts are hidden from any other section.
Abstraction: Data abstraction is one of the most essential and important
features of object-oriented programming in C++. Abstraction means displaying
only essential information and hiding the details. Data abstraction refers to
providing only essential information about the data to the outside world, hiding
the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes
will stop the car but he does not know about how on pressing accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what
abstraction is.
• Abstraction using Classes: We can implement Abstraction in C++ using
classes. The class helps us to group data members and member functions
using available access specifiers. A Class can decide which data member
will be visible to the outside world and which is not.
• Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow() method present in math.h
header file. Whenever we need to calculate the power of a number, we
simply call the function pow() present in the math.h header file and pass the
numbers as arguments without knowing the underlying algorithm according
to which the function is actually calculating the power of numbers.
Polymorphism: The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a message to be displayed
in more than one form.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behaviour in different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The
behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
• Operator Overloading: The process of making an operator to exhibit different
behaviours in different instances is known as operator overloading.
• Function Overloading: Function overloading is using a single function name
to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, some
times there are 2 integers, some times there are 3 integers. We can write the
Addition Method with the same name having different parameters, the
concerned method will be called according to parameters.
Inheritance: The capability of a class to derive properties and characteristics
from another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming.
• Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.
• Super Class:The class whose properties are inherited by sub class is called
Base Class or Super class.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Dynamic Binding: In dynamic binding, the code to be executed in response to
function call is decided at runtime. C++ has virtual functions to support this.

Message Passing: Objects communicate with one another by sending and


receiving information to each other. A message for an object is a request for
execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves specifying
the name of the object, the name of the function and the information to be sent.

Table of Contents
What Are OOPS Concepts In C++?
Why Do You Need Object-Oriented Programming?
Basic Object-Oriented Programming (OOPS) Concept in C++
Advantages of OOPs
Conclusion

The main intent of introducing the C++ programming language was to add object-
oriented features to the C language. OOPs offer several benefits or advantages to the
designer and user, and there are various areas where OOPs play an essential role,
including user interface design, simulation, and modeling, etc. This article on OOPs
concepts in c++ will help you understand and learn all about C++ object-oriented
programming.

What Are OOPS Concepts In C++?

OOPs, or Object-oriented programming is an approach or a programming pattern where


the programs are structured around objects rather than functions and logic. It makes the
data partitioned into two memory areas, i.e., data and functions, and helps make the
code flexible and modular.

Object-oriented programming mainly focuses on objects that are required to be


manipulated. In OOPs, it can represent data as objects that have attributes and
functions.
Why Do You Need Object-Oriented Programming?

The earlier approaches to programming were not that good, and there were several
limitations as well. Like in procedural-oriented programming, you cannot reuse the code
again in the program, and there was the problem of global data access, and the
approach couldn’t solve the real-world problems very well.

In object-oriented programming, it is easy to maintain the code with the help of classes
and objects. Using inheritance, there is code reusability, i.e., you don’t have to write the
same code again and again, which increases the simplicity of the program. Concepts
like encapsulation and abstraction provide data hiding as well.

Now have a look at some basic concepts of C++ OOPs.

Basic Object-Oriented Programming (OOPS) Concept in


C++

There are some basic concepts that act as the building blocks of OOPs.

• Classes & Objects

• Abstraction

• Encapsulation

• Inheritance

• Polymorphism

So now, you will understand each of these concepts in detail.

• Object

An Object can be defined as an entity that has a state and behavior, or in other words,
anything that exists physically in the world is called an object. It can represent a dog, a
person, a table, etc.

An object means the combination of data and programs, which further represent an
entity.
• Classes

Class can be defined as a blueprint of the object. It is basically a collection of objects


which act as building blocks.

A class contains data members (variables) and member functions. These member
functions are used to manipulate the data members inside the class.
• Abstraction

Abstraction helps in the data hiding process. It helps in displaying the essential features
without showing the details or the functionality to the user. It avoids unnecessary
information or irrelevant details and shows only that specific part which the user wants
to see.

• Encapsulation
The wrapping up of data and functions together in a single unit is known as
encapsulation. It can be achieved by making the data members' scope private and the
member function’s scope public to access these data members. Encapsulation makes
the data non-accessible to the outside world.

• Inheritance

Inheritance is the process in which two classes have an is-a relationship among each
other and objects of one class acquire properties and features of the other class. The
class which inherits the features is known as the child class, and the class whose
features it inherited is called the parent class. For example, Class Vehicle is the parent
class, and Class Bus, Car, and Bike are child classes.
Let’s have a look at an example of inheritance.

As we can see, there are two classes named parent and child. In line 12, the child class
inherits the parent class. Initially, you created an instance of the child class, through
which you are calling name1 and name2 variables; both of these string variables are
holding Harley and Davidson, respectively.

Since child class is inheriting parent class, when you call using the object of the child
class, you get the result name1 as Harley and name2 as Davidson.

Below is the output.


• Polymorphism

Polymorphism means many forms. It is the ability to take more than one form. It is a
feature that provides a function or an operator with more than one definition. It can be
implemented using function overloading, operator overload, function overriding, virtual
function.

Let’s have a look at an example where we are implementing function overriding.


As you can see in the above example, there are three classes. Class Animal is the
parent class, Class Cheetah, which is the derived class, and Class Dolphin is again the
derived class of Animal class.

All three classes have a function of the same name, i.e., speed, but the definition of this
speed function is different in all three classes. Inside the main function, firstly, you are
invoking the speed function using the object of the parent class, then using the object of
child class Cheetah, you are again invoking the function, and similarly, you are invoking
the function using the object of dolphin class.

Below is the output of the above program. You can see that when you call the function
using the object of the parent class, it invokes the function of the parent class. But when
you call the function using the object of the child class, it overrides the parent class
function and prints the function of the child class.

Now go through the advantages of C++ OOPs.

Advantages of OOPs

There are various advantages of object-oriented programming.

• OOPs provide reusability to the code and extend the use of existing classes.

• In OOPs, it is easy to maintain code as there are classes and objects, which helps in making
it easy to maintain rather than restructuring.

• It also helps in data hiding, keeping the data and information safe from leaking or getting
exposed.

• Object-oriented programming is easy to implement.

Conclusion

After reading this tutorial on OOPS Concepts in C++, you would have understood why
you need Object-oriented programming, what C++ OOPs are, and the basic concepts of
OOPs like polymorphism, inheritance encapsulation, etc. You also learned about the
advantages of C++ OOPs, along with examples of polymorphism and inheritance.

If you are perhaps looking to build a career in software development, check the Post-
Graduate Program in Full Stack Development by Simplilearn. It can prove to be the
ideal solution to help you build your career in the right way.

Do you have any questions regarding this tutorial on OOPS concepts in C+? If you do,
then please put them in the comments section. We’ll help you solve your queries. To
learn more about C++OOPs, click on the following link: C++ OOPs

• 3.What is SDLC
Ans: SDLC stands for Software Development Life Cycle. SDLC is a process that
consists of a series of planned activities to develop or alter the Software Products. This
tutorial will give you an overview of the SDLC basics, SDLC models available and their
application in the industry. This tutorial also elaborates on other related methodologies
like Agile, RAD and Prototyping.

Why to Learn SDLC?


Software Development Life Cycle (SDLC) is a process used by the software industry to
design, develop and test high quality softwares. The SDLC aims to produce a high-
quality software that meets or exceeds customer expectations, reaches completion
within times and cost estimates.
SDLC is a process followed for a software project, within a software organization. It
consists of a detailed plan describing how to develop, maintain, replace and alter or
enhance specific software. The life cycle defines a methodology for improving the quality
of software and the overall development process.
• SDLC is the acronym of Software Development Life Cycle.
• It is also called as Software Development Process.
• SDLC is a framework defining tasks performed at each step in the software
development process.
• ISO/IEC 12207 is an international standard for software life-cycle processes. It
aims to be the standard that defines all the tasks required for developing and
maintaining software.
SDLC Models
There are various software development life cycle models defined and designed which
are followed during the software development process. These models are also referred
as Software Development Process Models. Each process model follows a Series of
steps unique to its type to ensure success in the process of software development.
Following are the most important and popular SDLC models followed in the industry −

• Waterfall Model
• Iterative Model
• Spiral Model
• V-Model
• Big Bang Model
Other related methodologies are Agile Model, RAD Model, Rapid Application
Development and Prototyping Models.

Audience
This tutorial is relevant to all those professionals contributing in any manner towards
Software Product Development and its release. It is a handy reference for the quality
stakeholders of a Software project and the program/project managers. By the end of this
tutorial, the readers will develop a comprehensive understanding of SDLC and its related
concepts and will be able to select and follow the right model for any given Software
project.

Prerequisites
There are no specific prerequisites for this SDLC tutorial and any software professional
can go through this tutorial to get a bigger picture of how the high-quality software
applications and products are designed. A good understanding of programming or
testing or project management will give you an added advantage and help you gain
maximum from this tutorial.
Software Development Life Cycle (SDLC) is a process used by the software industry to
design, develop and test high quality softwares. The SDLC aims to produce a high-
quality software that meets or exceeds customer expectations, reaches completion
within times and cost estimates.
• SDLC is the acronym of Software Development Life Cycle.
• It is also called as Software Development Process.
• SDLC is a framework defining tasks performed at each step in the software
development process.
• ISO/IEC 12207 is an international standard for software life-cycle processes. It
aims to be the standard that defines all the tasks required for developing and
maintaining software.

What is SDLC?
SDLC is a process followed for a software project, within a software organization. It
consists of a detailed plan describing how to develop, maintain, replace and alter or
enhance specific software. The life cycle defines a methodology for improving the quality
of software and the overall development process.
The following figure is a graphical representation of the various stages of a typical SDLC.

A typical Software Development Life Cycle consists of the following stages −

Stage 1: Planning and Requirement Analysis


Requirement analysis is the most important and fundamental stage in SDLC. It is
performed by the senior members of the team with inputs from the customer, the sales
department, market surveys and domain experts in the industry. This information is then
used to plan the basic project approach and to conduct product feasibility study in the
economical, operational and technical areas.
Planning for the quality assurance requirements and identification of the risks associated
with the project is also done in the planning stage. The outcome of the technical feasibility
study is to define the various technical approaches that can be followed to implement
the project successfully with minimum risks.

Stage 2: Defining Requirements


Once the requirement analysis is done the next step is to clearly define and document
the product requirements and get them approved from the customer or the market
analysts. This is done through an SRS (Software Requirement
Specification) document which consists of all the product requirements to be designed
and developed during the project life cycle.

Stage 3: Designing the Product Architecture


SRS is the reference for product architects to come out with the best architecture for the
product to be developed. Based on the requirements specified in SRS, usually more than
one design approach for the product architecture is proposed and documented in a DDS
- Design Document Specification.
This DDS is reviewed by all the important stakeholders and based on various parameters
as risk assessment, product robustness, design modularity, budget and time constraints,
the best design approach is selected for the product.
A design approach clearly defines all the architectural modules of the product along with
its communication and data flow representation with the external and third party modules
(if any). The internal design of all the modules of the proposed architecture should be
clearly defined with the minutest of the details in DDS.

Stage 4: Building or Developing the Product


In this stage of SDLC the actual development starts and the product is built. The
programming code is generated as per DDS during this stage. If the design is performed
in a detailed and organized manner, code generation can be accomplished without much
hassle.
Developers must follow the coding guidelines defined by their organization and
programming tools like compilers, interpreters, debuggers, etc. are used to generate the
code. Different high level programming languages such as C, C++, Pascal, Java and
PHP are used for coding. The programming language is chosen with respect to the type
of software being developed.

Stage 5: Testing the Product


This stage is usually a subset of all the stages as in the modern SDLC models, the testing
activities are mostly involved in all the stages of SDLC. However, this stage refers to the
testing only stage of the product where product defects are reported, tracked, fixed and
retested, until the product reaches the quality standards defined in the SRS.

Stage 6: Deployment in the Market and Maintenance


Once the product is tested and ready to be deployed it is released formally in the
appropriate market. Sometimes product deployment happens in stages as per the
business strategy of that organization. The product may first be released in a limited
segment and tested in the real business environment (UAT- User acceptance testing).
Then based on the feedback, the product may be released as it is or with suggested
enhancements in the targeting market segment. After the product is released in the
market, its maintenance is done for the existing customer base.

SDLC Models
There are various software development life cycle models defined and designed which
are followed during the software development process. These models are also referred
as Software Development Process Models". Each process model follows a Series of
steps unique to its type to ensure success in the process of software development.
Following are the most important and popular SDLC models followed in the industry −

• Waterfall Model
• Iterative Model
• Spiral Model
• V-Model
• Big Bang Model
Other related methodologies are Agile Model, RAD Model, Rapid Application
Development and Prototyping Models.
The Waterfall Model was the first Process Model to be introduced. It is also referred to
as a linear-sequential life cycle model. It is very simple to understand and use. In a
waterfall model, each phase must be completed before the next phase can begin and
there is no overlapping in the phases.
The Waterfall model is the earliest SDLC approach that was used for software
development.
The waterfall Model illustrates the software development process in a linear sequential
flow. This means that any phase in the development process begins only if the previous
phase is complete. In this waterfall model, the phases do not overlap.

Waterfall Model - Design


Waterfall approach was first SDLC Model to be used widely in Software Engineering to
ensure success of the project. In "The Waterfall" approach, the whole process of
software development is divided into separate phases. In this Waterfall model, typically,
the outcome of one phase acts as the input for the next phase sequentially.
The following illustration is a representation of the different phases of the Waterfall
Model.

The sequential phases in Waterfall model are −


• Requirement Gathering and analysis − All possible requirements of the system
to be developed are captured in this phase and documented in a requirement
specification document.
• System Design − The requirement specifications from first phase are studied in
this phase and the system design is prepared. This system design helps in
specifying hardware and system requirements and helps in defining the overall
system architecture.
• Implementation − With inputs from the system design, the system is first
developed in small programs called units, which are integrated in the next phase.
Each unit is developed and tested for its functionality, which is referred to as Unit
Testing.
• Integration and Testing − All the units developed in the implementation phase
are integrated into a system after testing of each unit. Post integration the entire
system is tested for any faults and failures.
• Deployment of system − Once the functional and non-functional testing is done;
the product is deployed in the customer environment or released into the market.
• Maintenance − There are some issues which come up in the client environment.
To fix those issues, patches are released. Also to enhance the product some
better versions are released. Maintenance is done to deliver these changes in the
customer environment.
All these phases are cascaded to each other in which progress is seen as flowing steadily
downwards (like a waterfall) through the phases. The next phase is started only after the
defined set of goals are achieved for previous phase and it is signed off, so the name
"Waterfall Model". In this model, phases do not overlap.

Waterfall Model - Application


Every software developed is different and requires a suitable SDLC approach to be
followed based on the internal and external factors. Some situations where the use of
Waterfall model is most appropriate are −
• Requirements are very well documented, clear and fixed.
• Product definition is stable.
• Technology is understood and is not dynamic.
• There are no ambiguous requirements.
• Ample resources with required expertise are available to support the product.
• The project is short.

Waterfall Model - Advantages


The advantages of waterfall development are that it allows for departmentalization and
control. A schedule can be set with deadlines for each stage of development and a
product can proceed through the development process model phases one by one.
Development moves from concept, through design, implementation, testing, installation,
troubleshooting, and ends up at operation and maintenance. Each phase of development
proceeds in strict order.
Some of the major advantages of the Waterfall Model are as follows −
• Simple and easy to understand and use
• Easy to manage due to the rigidity of the model. Each phase has specific
deliverables and a review process.
• Phases are processed and completed one at a time.
• Works well for smaller projects where requirements are very well understood.
• Clearly defined stages.
• Well understood milestones.
• Easy to arrange tasks.
• Process and results are well documented.

Waterfall Model - Disadvantages


The disadvantage of waterfall development is that it does not allow much reflection or
revision. Once an application is in the testing stage, it is very difficult to go back and
change something that was not well-documented or thought upon in the concept stage.
The major disadvantages of the Waterfall Model are as follows −
• No working software is produced until late during the life cycle.
• High amounts of risk and uncertainty.
• Not a good model for complex and object-oriented projects.
• Poor model for long and ongoing projects.
• Not suitable for the projects where requirements are at a moderate to high risk of
changing. So, risk and uncertainty is high with this process model.
• It is difficult to measure progress within stages.
• Cannot accommodate changing requirements.
• Adjusting scope during the life cycle can end a project.
• Integration is done as a "big-bang. at the very end, which doesn't allow identifying
any technological or business bottleneck or challenges early.
In the Iterative model, iterative process starts with a simple implementation of a small
set of the software requirements and iteratively enhances the evolving versions until the
complete system is implemented and ready to be deployed.
An iterative life cycle model does not attempt to start with a full specification of
requirements. Instead, development begins by specifying and implementing just part of
the software, which is then reviewed to identify further requirements. This process is then
repeated, producing a new version of the software at the end of each iteration of the
model.

Iterative Model - Design


Iterative process starts with a simple implementation of a subset of the software
requirements and iteratively enhances the evolving versions until the full system is
implemented. At each iteration, design modifications are made and new functional
capabilities are added. The basic idea behind this method is to develop a system through
repeated cycles (iterative) and in smaller portions at a time (incremental).
The following illustration is a representation of the Iterative and Incremental model −
Iterative and Incremental development is a combination of both iterative design or
iterative method and incremental build model for development. "During software
development, more than one iteration of the software development cycle may be in
progress at the same time." This process may be described as an "evolutionary
acquisition" or "incremental build" approach."
In this incremental model, the whole requirement is divided into various builds. During
each iteration, the development module goes through the requirements, design,
implementation and testing phases. Each subsequent release of the module adds
function to the previous release. The process continues till the complete system is ready
as per the requirement.
The key to a successful use of an iterative software development lifecycle is rigorous
validation of requirements, and verification & testing of each version of the software
against those requirements within each cycle of the model. As the software evolves
through successive cycles, tests must be repeated and extended to verify each version
of the software.

Iterative Model - Application


Like other SDLC models, Iterative and incremental development has some specific
applications in the software industry. This model is most often used in the following
scenarios −
• Requirements of the complete system are clearly defined and understood.
• Major requirements must be defined; however, some functionalities or requested
enhancements may evolve with time.
• There is a time to the market constraint.
• A new technology is being used and is being learnt by the development team while
working on the project.
• Resources with needed skill sets are not available and are planned to be used on
contract basis for specific iterations.
• There are some high-risk features and goals which may change in the future.

Iterative Model - Pros and Cons


The advantage of this model is that there is a working model of the system at a very
early stage of development, which makes it easier to find functional or design flaws.
Finding issues at an early stage of development enables to take corrective measures in
a limited budget.
The disadvantage with this SDLC model is that it is applicable only to large and bulky
software development projects. This is because it is hard to break a small software
system into further small serviceable increments/modules.
The advantages of the Iterative and Incremental SDLC Model are as follows −
• Some working functionality can be developed quickly and early in the life cycle.
• Results are obtained early and periodically.
• Parallel development can be planned.
• Progress can be measured.
• Less costly to change the scope/requirements.
• Testing and debugging during smaller iteration is easy.
• Risks are identified and resolved during iteration; and each iteration is an easily
managed milestone.
• Easier to manage risk - High risk part is done first.
• With every increment, operational product is delivered.
• Issues, challenges and risks identified from each increment can be utilized/applied
to the next increment.
• Risk analysis is better.
• It supports changing requirements.
• Initial Operating time is less.
• Better suited for large and mission-critical projects.
• During the life cycle, software is produced early which facilitates customer
evaluation and feedback.
The disadvantages of the Iterative and Incremental SDLC Model are as follows −
• More resources may be required.
• Although cost of change is lesser, but it is not very suitable for changing
requirements.
• More management attention is required.
• System architecture or design issues may arise because not all requirements are
gathered in the beginning of the entire life cycle.
• Defining increments may require definition of the complete system.
• Not suitable for smaller projects.
• Management complexity is more.
• End of project may not be known which is a risk.
• Highly skilled resources are required for risk analysis.
• Projects progress is highly dependent upon the risk analysis phase.
The spiral model combines the idea of iterative development with the systematic,
controlled aspects of the waterfall model. This Spiral model is a combination of iterative
development process model and sequential linear development model i.e. the waterfall
model with a very high emphasis on risk analysis. It allows incremental releases of the
product or incremental refinement through each iteration around the spiral.

Spiral Model - Design


The spiral model has four phases. A software project repeatedly passes through these
phases in iterations called Spirals.

Identification
This phase starts with gathering the business requirements in the baseline spiral. In the
subsequent spirals as the product matures, identification of system requirements,
subsystem requirements and unit requirements are all done in this phase.
This phase also includes understanding the system requirements by continuous
communication between the customer and the system analyst. At the end of the spiral,
the product is deployed in the identified market.

Design
The Design phase starts with the conceptual design in the baseline spiral and involves
architectural design, logical design of modules, physical product design and the final
design in the subsequent spirals.

Construct or Build
The Construct phase refers to production of the actual software product at every spiral.
In the baseline spiral, when the product is just thought of and the design is being
developed a POC (Proof of Concept) is developed in this phase to get customer
feedback.
Then in the subsequent spirals with higher clarity on requirements and design details a
working model of the software called build is produced with a version number. These
builds are sent to the customer for feedback.

Evaluation and Risk Analysis


Risk Analysis includes identifying, estimating and monitoring the technical feasibility and
management risks, such as schedule slippage and cost overrun. After testing the build,
at the end of first iteration, the customer evaluates the software and provides feedback.
The following illustration is a representation of the Spiral Model, listing the activities in
each phase.

Based on the customer evaluation, the software development process enters the next
iteration and subsequently follows the linear approach to implement the feedback
suggested by the customer. The process of iterations along the spiral continues
throughout the life of the software.
Spiral Model Application
The Spiral Model is widely used in the software industry as it is in sync with the natural
development process of any product, i.e. learning with maturity which involves minimum
risk for the customer as well as the development firms.
The following pointers explain the typical uses of a Spiral Model −
• When there is a budget constraint and risk evaluation is important.
• For medium to high-risk projects.
• Long-term project commitment because of potential changes to economic
priorities as the requirements change with time.
• Customer is not sure of their requirements which is usually the case.
• Requirements are complex and need evaluation to get clarity.
• New product line which should be released in phases to get enough customer
feedback.
• Significant changes are expected in the product during the development cycle.

Spiral Model - Pros and Cons


The advantage of spiral lifecycle model is that it allows elements of the product to be
added in, when they become available or known. This assures that there is no conflict
with previous requirements and design.
This method is consistent with approaches that have multiple software builds and
releases which allows making an orderly transition to a maintenance activity. Another
positive aspect of this method is that the spiral model forces an early user involvement
in the system development effort.
On the other side, it takes a very strict management to complete such products and there
is a risk of running the spiral in an indefinite loop. So, the discipline of change and the
extent of taking change requests is very important to develop and deploy the product
successfully.
The advantages of the Spiral SDLC Model are as follows −
• Changing requirements can be accommodated.
• Allows extensive use of prototypes.
• Requirements can be captured more accurately.
• Users see the system early.
• Development can be divided into smaller parts and the risky parts can be
developed earlier which helps in better risk management.
The disadvantages of the Spiral SDLC Model are as follows −
• Management is more complex.
• End of the project may not be known early.
• Not suitable for small or low risk projects and could be expensive for small
projects.
• Process is complex
• Spiral may go on indefinitely.
• Large number of intermediate stages requires excessive documentation.
The V-model is an SDLC model where execution of processes happens in a sequential
manner in a V-shape. It is also known as Verification and Validation model.
The V-Model is an extension of the waterfall model and is based on the association of a
testing phase for each corresponding development stage. This means that for every
single phase in the development cycle, there is a directly associated testing phase. This
is a highly-disciplined model and the next phase starts only after completion of the
previous phase.

V-Model - Design
Under the V-Model, the corresponding testing phase of the development phase is
planned in parallel. So, there are Verification phases on one side of the ‘V’ and Validation
phases on the other side. The Coding Phase joins the two sides of the V-Model.
The following illustration depicts the different phases in a V-Model of the SDLC.
V-Model - Verification Phases
There are several Verification phases in the V-Model, each of these are explained in
detail below.

Business Requirement Analysis


This is the first phase in the development cycle where the product requirements are
understood from the customer’s perspective. This phase involves detailed
communication with the customer to understand his expectations and exact requirement.
This is a very important activity and needs to be managed well, as most of the customers
are not sure about what exactly they need. The acceptance test design planning is
done at this stage as business requirements can be used as an input for acceptance
testing.

System Design
Once you have the clear and detailed product requirements, it is time to design the
complete system. The system design will have the understanding and detailing the
complete hardware and communication setup for the product under development. The
system test plan is developed based on the system design. Doing this at an earlier stage
leaves more time for the actual test execution later.

Architectural Design
Architectural specifications are understood and designed in this phase. Usually more
than one technical approach is proposed and based on the technical and financial
feasibility the final decision is taken. The system design is broken down further into
modules taking up different functionality. This is also referred to as High Level Design
(HLD).
The data transfer and communication between the internal modules and with the outside
world (other systems) is clearly understood and defined in this stage. With this
information, integration tests can be designed and documented during this stage.

Module Design
In this phase, the detailed internal design for all the system modules is specified, referred
to as Low Level Design (LLD). It is important that the design is compatible with the
other modules in the system architecture and the other external systems. The unit tests
are an essential part of any development process and helps eliminate the maximum
faults and errors at a very early stage. These unit tests can be designed at this stage
based on the internal module designs.

Coding Phase
The actual coding of the system modules designed in the design phase is taken up in
the Coding phase. The best suitable programming language is decided based on the
system and architectural requirements.
The coding is performed based on the coding guidelines and standards. The code goes
through numerous code reviews and is optimized for best performance before the final
build is checked into the repository.

Validation Phases
The different Validation Phases in a V-Model are explained in detail below.

Unit Testing
Unit tests designed in the module design phase are executed on the code during this
validation phase. Unit testing is the testing at code level and helps eliminate bugs at an
early stage, though all defects cannot be uncovered by unit testing.

Integration Testing
Integration testing is associated with the architectural design phase. Integration tests are
performed to test the coexistence and communication of the internal modules within the
system.

System Testing
System testing is directly associated with the system design phase. System tests check
the entire system functionality and the communication of the system under development
with external systems. Most of the software and hardware compatibility issues can be
uncovered during this system test execution.

Acceptance Testing
Acceptance testing is associated with the business requirement analysis phase and
involves testing the product in user environment. Acceptance tests uncover the
compatibility issues with the other systems available in the user environment. It also
discovers the non-functional issues such as load and performance defects in the actual
user environment.

V- Model ─ Application
V- Model application is almost the same as the waterfall model, as both the models are
of sequential type. Requirements have to be very clear before the project starts, because
it is usually expensive to go back and make changes. This model is used in the medical
development field, as it is strictly a disciplined domain.
The following pointers are some of the most suitable scenarios to use the V-Model
application.
• Requirements are well defined, clearly documented and fixed.
• Product definition is stable.
• Technology is not dynamic and is well understood by the project team.
• There are no ambiguous or undefined requirements.
• The project is short.

V-Model - Pros and Cons


The advantage of the V-Model method is that it is very easy to understand and apply.
The simplicity of this model also makes it easier to manage. The disadvantage is that
the model is not flexible to changes and just in case there is a requirement change, which
is very common in today’s dynamic world, it becomes very expensive to make the
change.
The advantages of the V-Model method are as follows −
• This is a highly-disciplined model and Phases are completed one at a time.
• Works well for smaller projects where requirements are very well understood.
• Simple and easy to understand and use.
• Easy to manage due to the rigidity of the model. Each phase has specific
deliverables and a review process.
The disadvantages of the V-Model method are as follows −
• High risk and uncertainty.
• Not a good model for complex and object-oriented projects.
• Poor model for long and ongoing projects.
• Not suitable for the projects where requirements are at a moderate to high risk of
changing.
• Once an application is in the testing stage, it is difficult to go back and change a
functionality.
• No working software is produced until late during the life cycle.
The Big Bang model is an SDLC model where we do not follow any specific process.
The development just starts with the required money and efforts as the input, and the
output is the software developed which may or may not be as per customer requirement.
This Big Bang Model does not follow a process/procedure and there is a very little
planning required. Even the customer is not sure about what exactly he wants and the
requirements are implemented on the fly without much analysis.
Usually this model is followed for small projects where the development teams are very
small.

Big Bang Model ─ Design and Application


The Big Bang Model comprises of focusing all the possible resources in the software
development and coding, with very little or no planning. The requirements are
understood and implemented as they come. Any changes required may or may not need
to revamp the complete software.
This model is ideal for small projects with one or two developers working together and is
also useful for academic or practice projects. It is an ideal model for the product where
requirements are not well understood and the final release date is not given.

Big Bang Model - Pros and Cons


The advantage of this Big Bang Model is that it is very simple and requires very little or
no planning. Easy to manage and no formal procedure are required.
However, the Big Bang Model is a very high risk model and changes in the requirements
or misunderstood requirements may even lead to complete reversal or scraping of the
project. It is ideal for repetitive or small projects with minimum risks.
The advantages of the Big Bang Model are as follows −
• This is a very simple model
• Little or no planning required
• Easy to manage
• Very few resources required
• Gives flexibility to developers
• It is a good learning aid for new comers or students.
The disadvantages of the Big Bang Model are as follows −
• Very High risk and uncertainty.
• Not a good model for complex and object-oriented projects.
• Poor model for long and ongoing projects.
• Can turn out to be very expensive if requirements are misunderstood.
Agile SDLC model is a combination of iterative and incremental process models with
focus on process adaptability and customer satisfaction by rapid delivery of working
software product. Agile Methods break the product into small incremental builds. These
builds are provided in iterations. Each iteration typically lasts from about one to three
weeks. Every iteration involves cross functional teams working simultaneously on
various areas like −

• Planning
• Requirements Analysis
• Design
• Coding
• Unit Testing and
• Acceptance Testing.
At the end of the iteration, a working product is displayed to the customer and important
stakeholders.

What is Agile?
Agile model believes that every project needs to be handled differently and the existing
methods need to be tailored to best suit the project requirements. In Agile, the tasks are
divided to time boxes (small time frames) to deliver specific features for a release.
Iterative approach is taken and working software build is delivered after each iteration.
Each build is incremental in terms of features; the final build holds all the features
required by the customer.
Here is a graphical illustration of the Agile Model −

The Agile thought process had started early in the software development and started
becoming popular with time due to its flexibility and adaptability.
The most popular Agile methods include Rational Unified Process (1994), Scrum (1995),
Crystal Clear, Extreme Programming (1996), Adaptive Software Development, Feature
Driven Development, and Dynamic Systems Development Method (DSDM) (1995).
These are now collectively referred to as Agile Methodologies, after the Agile Manifesto
was published in 2001.
Following are the Agile Manifesto principles −
• Individuals and interactions − In Agile development, self-organization and
motivation are important, as are interactions like co-location and pair
programming.
• Working software − Demo working software is considered the best means of
communication with the customers to understand their requirements, instead of
just depending on documentation.
• Customer collaboration − As the requirements cannot be gathered completely
in the beginning of the project due to various factors, continuous customer
interaction is very important to get proper product requirements.
• Responding to change − Agile Development is focused on quick responses to
change and continuous development.

Agile Vs Traditional SDLC Models


Agile is based on the adaptive software development methods, whereas the
traditional SDLC models like the waterfall model is based on a predictive approach.
Predictive teams in the traditional SDLC models usually work with detailed planning and
have a complete forecast of the exact tasks and features to be delivered in the next few
months or during the product life cycle.
Predictive methods entirely depend on the requirement analysis and planning done
in the beginning of cycle. Any changes to be incorporated go through a strict change
control management and prioritization.
Agile uses an adaptive approach where there is no detailed planning and there is clarity
on future tasks only in respect of what features need to be developed. There is feature
driven development and the team adapts to the changing product requirements
dynamically. The product is tested very frequently, through the release iterations,
minimizing the risk of any major failures in future.
Customer Interaction is the backbone of this Agile methodology, and open
communication with minimum documentation are the typical features of Agile
development environment. The agile teams work in close collaboration with each other
and are most often located in the same geographical location.

Agile Model - Pros and Cons


Agile methods are being widely accepted in the software world recently. However, this
method may not always be suitable for all products. Here are some pros and cons of the
Agile model.
The advantages of the Agile Model are as follows −
• Is a very realistic approach to software development.
• Promotes teamwork and cross training.
• Functionality can be developed rapidly and demonstrated.
• Resource requirements are minimum.
• Suitable for fixed or changing requirements
• Delivers early partial working solutions.
• Good model for environments that change steadily.
• Minimal rules, documentation easily employed.
• Enables concurrent development and delivery within an overall planned context.
• Little or no planning required.
• Easy to manage.
• Gives flexibility to developers.
The disadvantages of the Agile Model are as follows −
• Not suitable for handling complex dependencies.
• More risk of sustainability, maintainability and extensibility.
• An overall plan, an agile leader and agile PM practice is a must without which it
will not work.
• Strict delivery management dictates the scope, functionality to be delivered, and
adjustments to meet the deadlines.
• Depends heavily on customer interaction, so if customer is not clear, team can be
driven in the wrong direction.
• There is a very high individual dependency, since there is minimum
documentation generated.
• Transfer of technology to new team members may be quite challenging due to
lack of documentation.
The RAD (Rapid Application Development) model is based on prototyping and
iterative development with no specific planning involved. The process of writing the
software itself involves the planning required for developing the product.
Rapid Application Development focuses on gathering customer requirements through
workshops or focus groups, early testing of the prototypes by the customer using iterative
concept, reuse of the existing prototypes (components), continuous integration and rapid
delivery.

What is RAD?
Rapid application development is a software development methodology that uses
minimal planning in favor of rapid prototyping. A prototype is a working model that is
functionally equivalent to a component of the product.
In the RAD model, the functional modules are developed in parallel as prototypes and
are integrated to make the complete product for faster product delivery. Since there is
no detailed preplanning, it makes it easier to incorporate the changes within the
development process.
RAD projects follow iterative and incremental model and have small teams comprising
of developers, domain experts, customer representatives and other IT resources working
progressively on their component or prototype.
The most important aspect for this model to be successful is to make sure that the
prototypes developed are reusable.

RAD Model Design


RAD model distributes the analysis, design, build and test phases into a series of short,
iterative development cycles.
Following are the various phases of the RAD Model −

Business Modelling
The business model for the product under development is designed in terms of flow of
information and the distribution of information between various business channels. A
complete business analysis is performed to find the vital information for business, how it
can be obtained, how and when is the information processed and what are the factors
driving successful flow of information.

Data Modelling
The information gathered in the Business Modelling phase is reviewed and analyzed to
form sets of data objects vital for the business. The attributes of all data sets is identified
and defined. The relation between these data objects are established and defined in
detail in relevance to the business model.

Process Modelling
The data object sets defined in the Data Modelling phase are converted to establish the
business information flow needed to achieve specific business objectives as per the
business model. The process model for any changes or enhancements to the data object
sets is defined in this phase. Process descriptions for adding, deleting, retrieving or
modifying a data object are given.

Application Generation
The actual system is built and coding is done by using automation tools to convert
process and data models into actual prototypes.

Testing and Turnover


The overall testing time is reduced in the RAD model as the prototypes are independently
tested during every iteration. However, the data flow and the interfaces between all the
components need to be thoroughly tested with complete test coverage. Since most of
the programming components have already been tested, it reduces the risk of any major
issues.
The following illustration describes the RAD Model in detail.

RAD Model Vs Traditional SDLC


The traditional SDLC follows a rigid process models with high emphasis on requirement
analysis and gathering before the coding starts. It puts pressure on the customer to sign
off the requirements before the project starts and the customer doesn’t get the feel of
the product as there is no working build available for a long time.
The customer may need some changes after he gets to see the software. However, the
change process is quite rigid and it may not be feasible to incorporate major changes in
the product in the traditional SDLC.
The RAD model focuses on iterative and incremental delivery of working models to the
customer. This results in rapid delivery to the customer and customer involvement during
the complete development cycle of product reducing the risk of non-conformance with
the actual user requirements.

RAD Model - Application


RAD model can be applied successfully to the projects in which clear modularization is
possible. If the project cannot be broken into modules, RAD may fail.
The following pointers describe the typical scenarios where RAD can be used −
• RAD should be used only when a system can be modularized to be delivered in
an incremental manner.
• It should be used if there is a high availability of designers for Modelling.
• It should be used only if the budget permits use of automated code generating
tools.
• RAD SDLC model should be chosen only if domain experts are available with
relevant business knowledge.
• Should be used where the requirements change during the project and working
prototypes are to be presented to customer in small iterations of 2-3 months.

RAD Model - Pros and Cons


RAD model enables rapid delivery as it reduces the overall development time due to the
reusability of the components and parallel development. RAD works well only if high
skilled engineers are available and the customer is also committed to achieve the
targeted prototype in the given time frame. If there is commitment lacking on either side
the model may fail.
The advantages of the RAD Model are as follows −
• Changing requirements can be accommodated.
• Progress can be measured.
• Iteration time can be short with use of powerful RAD tools.
• Productivity with fewer people in a short time.
• Reduced development time.
• Increases reusability of components.
• Quick initial reviews occur.
• Encourages customer feedback.
• Integration from very beginning solves a lot of integration issues.
The disadvantages of the RAD Model are as follows −
• Dependency on technically strong team members for identifying business
requirements.
• Only system that can be modularized can be built using RAD.
• Requires highly skilled developers/designers.
• High dependency on Modelling skills.
• Inapplicable to cheaper projects as cost of Modelling and automated code
generation is very high.
• Management complexity is more.
• Suitable for systems that are component based and scalable.
• Requires user involvement throughout the life cycle.
• Suitable for project requiring shorter development times.
The Software Prototyping refers to building software application prototypes which
displays the functionality of the product under development, but may not actually hold
the exact logic of the original software.
Software prototyping is becoming very popular as a software development model, as it
enables to understand customer requirements at an early stage of development. It helps
get valuable feedback from the customer and helps software designers and developers
understand about what exactly is expected from the product under development.

What is Software Prototyping?


Prototype is a working model of software with some limited functionality. The prototype
does not always hold the exact logic used in the actual software application and is an
extra effort to be considered under effort estimation.
Prototyping is used to allow the users evaluate developer proposals and try them out
before implementation. It also helps understand the requirements which are user specific
and may not have been considered by the developer during product design.
Following is a stepwise approach explained to design a software prototype.

Basic Requirement Identification


This step involves understanding the very basics product requirements especially in
terms of user interface. The more intricate details of the internal design and external
aspects like performance and security can be ignored at this stage.

Developing the initial Prototype


The initial Prototype is developed in this stage, where the very basic requirements are
showcased and user interfaces are provided. These features may not exactly work in
the same manner internally in the actual software developed. While, the workarounds
are used to give the same look and feel to the customer in the prototype developed.

Review of the Prototype


The prototype developed is then presented to the customer and the other important
stakeholders in the project. The feedback is collected in an organized manner and used
for further enhancements in the product under development.
Revise and Enhance the Prototype
The feedback and the review comments are discussed during this stage and some
negotiations happen with the customer based on factors like – time and budget
constraints and technical feasibility of the actual implementation. The changes accepted
are again incorporated in the new Prototype developed and the cycle repeats until the
customer expectations are met.
Prototypes can have horizontal or vertical dimensions. A Horizontal prototype displays
the user interface for the product and gives a broader view of the entire system, without
concentrating on internal functions. A Vertical prototype on the other side is a detailed
elaboration of a specific function or a sub system in the product.
The purpose of both horizontal and vertical prototype is different. Horizontal prototypes
are used to get more information on the user interface level and the business
requirements. It can even be presented in the sales demos to get business in the market.
Vertical prototypes are technical in nature and are used to get details of the exact
functioning of the sub systems. For example, database requirements, interaction and
data processing loads in a given sub system.

Software Prototyping - Types


There are different types of software prototypes used in the industry. Following are the
major software prototyping types used widely −

Throwaway/Rapid Prototyping
Throwaway prototyping is also called as rapid or close ended prototyping. This type of
prototyping uses very little efforts with minimum requirement analysis to build a
prototype. Once the actual requirements are understood, the prototype is discarded and
the actual system is developed with a much clear understanding of user requirements.

Evolutionary Prototyping
Evolutionary prototyping also called as breadboard prototyping is based on building
actual functional prototypes with minimal functionality in the beginning. The prototype
developed forms the heart of the future prototypes on top of which the entire system is
built. By using evolutionary prototyping, the well-understood requirements are included
in the prototype and the requirements are added as and when they are understood.

Incremental Prototyping
Incremental prototyping refers to building multiple functional prototypes of the various
sub-systems and then integrating all the available prototypes to form a complete system.

Extreme Prototyping
Extreme prototyping is used in the web development domain. It consists of three
sequential phases. First, a basic prototype with all the existing pages is presented in the
HTML format. Then the data processing is simulated using a prototype services layer.
Finally, the services are implemented and integrated to the final prototype. This process
is called Extreme Prototyping used to draw attention to the second phase of the process,
where a fully functional UI is developed with very little regard to the actual services.

Software Prototyping - Application


Software Prototyping is most useful in development of systems having high level of user
interactions such as online systems. Systems which need users to fill out forms or go
through various screens before data is processed can use prototyping very effectively to
give the exact look and feel even before the actual software is developed.
Software that involves too much of data processing and most of the functionality is
internal with very little user interface does not usually benefit from prototyping. Prototype
development could be an extra overhead in such projects and may need lot of extra
efforts.

Software Prototyping - Pros and Cons


Software prototyping is used in typical cases and the decision should be taken very
carefully so that the efforts spent in building the prototype add considerable value to the
final software developed. The model has its own pros and cons discussed as follows.
The advantages of the Prototyping Model are as follows −
• Increased user involvement in the product even before its implementation.
• Since a working model of the system is displayed, the users get a better
understanding of the system being developed.
• Reduces time and cost as the defects can be detected much earlier.
• Quicker user feedback is available leading to better solutions.
• Missing functionality can be identified easily.
• Confusing or difficult functions can be identified.
The Disadvantages of the Prototyping Model are as follows −
• Risk of insufficient requirement analysis owing to too much dependency on the
prototype.
• Users may get confused in the prototypes and actual systems.
• Practically, this methodology may increase the complexity of the system as scope
of the system may expand beyond original plans.
• Developers may try to reuse the existing prototypes to build the actual system,
even when it is not technically feasible.
• The effort invested in building prototypes may be too much if it is not monitored
properly.

• 4. Four major concepts related to object-oriented programmings


are:

Ans: The four basics of object-oriented programming


The four basics of object-oriented programming
Object-oriented programming has four basic concepts: encapsulation, abstraction,
inheritance, and polymorphism. Even if these concepts seem incredibly complex,
understanding the general framework of how they work will help you understand the
basics of an OOP computer program. Below, we outline these four basic principles and
what they entail:
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1. Encapsulation
The word, “encapsulate,” means to enclose something. Just like a pill "encapsulates" or
contains the medication inside of its coating, the principle of encapsulation works in a
similar way in OOP: by forming a protective barrier around the information contained
within a class from the rest of the code.
In OOP, we encapsulate by binding the data and functions which operate on that data
into a single unit, the class. By doing so, we can hide private details of a class from the
outside world and only expose functionality that is important for interfacing with it. When
a class does not allow calling code access to its private data directly, we say that it is
well encapsulated.
Example: Elaborating on the person class example from earlier, we might have private
data in the class, such as "socialSecurityNumber," that should not be exposed to other
objects in the program. By encapsulating this data member as a private variable in the
class, outside code would not have direct access to it, and it would remain safe within
that person’s object.
If a method is written in the person class to perform, say, a bank transaction called
"bankTransaction()," that function could then access the "socialSecurityNumber"
variable as necessary. The person’s private data would be well encapsulated in such a
class.
2. Abstraction
Often, it’s easier to reason and design a program when you can separate the interface
of a class from its implementation, and focus on the interface. This is akin to treating a
system as a “black box,” where it’s not important to understand the gory inner workings
in order to reap the benefits of using it.
This process is called “abstraction” in OOP, because we are abstracting away the gory
implementation details of a class and only presenting a clean and easy-to-use interface
via the class’ member functions. Carefully used, abstraction helps isolate the impact of
changes made to the code, so that if something goes wrong, the change will only affect
the implementation details of a class and not the outside code.
Example: Think of a stereo system as an object with a complex logic board on the
inside. It has buttons on the outside to allow for interaction with the object. When you
press any of the buttons, you're not thinking about what happens on the inside because
you can't see it. Even though you can't see the logic board completing these functions
as a result of pressing a button, it's still performing them., albeit hidden to you.
This is the concept of abstraction, which is incredibly useful in all areas of engineering
and also applied to great effect in object-oriented programming.
Example: In OOP, we might have a class defined to represent the human body. One
might define some functions as part of its publicly facing interface such as “walk()” or
“eatFood().” Calling code could call these functions and remain completely oblivious to
the complex inner workings of the human body and its necessary functions to perform
the act of walking or eating. These details are completely hidden in the implementation
of the walk() and eatFood() body functions and are, therefore, us abstracted away from
the end user. In these cases, it’s not important for calling code to understand how the
brain coordinates walking or how the stomach manages digesting the food, but rather
simply that a human walked or ate.
3. Inheritance
Object-oriented languages that support classes almost always support the notion of
“inheritance.” Classes can be organized into hierarchies, where a class might have one
or more parent or child classes. If a class has a parent class, we say it is derived or
inherited from the parent class and it represents an “IS-A” type relationship. That is to
say, the child class “IS-A” type of the parent class.
Therefore, if a class inherits from another class, it automatically obtains a lot of the
same functionality and properties from that class and can be extended to contain
separate code and data. A nice feature of inheritance is that it often leads to good code
reuse since a parent class’ functions don’t need to be re-defined in any of its child
classes.
Consider two classes: one being the superclass—or parent—and the other being the
subclass—or child. The child class will inherit the properties of the parent class, possibly
modifying or extending its behavior. Programmers applying the technique of inheritance
arrange these classes into what is called an “IS-A” type of relationship.
Example: For instance, in the animal world, an insect could be represented by an
Insect superclass. All insects share similar properties, such as having six legs and an
exoskeleton. Subclasses might be defined for grasshoppers and ants. Because they
inherit or are derived from the Insect class, they automatically share all insect
properties.
4. Polymorphism
In OOP, polymorphism allows for the uniform treatment of classes in a hierarchy.
Therefore, calling code only needs to be written to handle objects from the root of the
hierarchy, and any object instantiated by any child class in the hierarchy will be handled
in the same way.
Because derived objects share the same interface as their parents, the calling code can
call any function in that class’ interface. At run-time, the appropriate function will be
called depending on the type of object passed leading to possibly different behaviors.
Example: Suppose we have a class called, “Animal” and two child classes, “Cat,” and
“Dog.” If the Animal class has a method to make a noise, called, “makeNoise,” then, we
can override the "makeNoise" function that is inherited by the sub-classes, "Cat" and
"Dog," to be “meow” and “bark,” respectively. Another function can, then, be written that
accepts any Animal object as a parameter and invokes its "makeNoise" member
function. The noise will be different: either a “meow” or a “bark” depending on the type
of animal object that was actually passed to the function.

• 5.What is BigData
Ans: https://www.oracle.com/in/big-data/what-is-big-data/

• 6.Difference btw C AND PYTHON


Ans: Here are some of the differences between C and Python.
C Python

An Imperative programming model is An object-oriented programming model


basically followed by C. is basically followed by Python.

Variables are declared in C. Python has no declaration.

Python has OOP which is a part of the


C doesn’t have native OOP. language.

No pointers functionality is available in


Pointers are available in C language. Python.

C is a compiled language. Python is an interpreted language.

There is a limited number of built-in functions There is a large library of built-in


available in C. functions in Python.

It is easy to implement data structures in


Implementation of data structures requires its Python with built-in insert, append
functions to be explicitly implemented. functions.

Python is firstly compiled to a byte-code


C is compiled directly to machine code which and then it is interpreted by a large C
is executed directly by the CPU program.

Declaring of variable type in C is a necessary There is no need to declare a type of


condition. variable in Python.
C Python

Python has some complex data


C does not have complex data structures. structures.

C is statically typed. Python is dynamically typed.

Syntax of C is harder than python because of


which programmers prefer to use python
instead of C It is easy to learn, write and read Python
programs than C.

Python programs are saved by .py


C programs are saved with .c extension. extension.

The assignment gives an error in line.


For example, a=5 gives an error in
An assignment is allowed in a line. python.

In C language testing and debugging is In Python, testing and debugging are


harder. directly not harder than in C.

C is complex than Python. Python is much easier than C.

The basic if statement in Python is


The basic if statement in c is represented as: represented as:
if () if:

The basic if-else statement in Python is The basic if-else statement is


represented as: represented as:
if ( ) if :
else else:

C language is fast. Python programming language is slow


C Python

Python uses indentation to identify


C uses {} to identify a separate block of code. separate blocks of code.

It is not mandatory to mark the end of


It is mandatory to mark the end of every every statement with a semicolon in
statement with a semicolon in C. Python.

• 7.What is header file


Ans: A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files. There are two types of
header files: the files that the programmer writes and the files that comes with your
compiler.
You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes
along with your compiler.
Including a header file is equal to copying the content of the header file but we do not do
it because it will be error-prone and it is not a good idea to copy the content of a header
file in the source files, especially if we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system
wide global variables, and function prototypes in the header files and include that header
file wherever it is required.

Include Syntax
Both the user and the system header files are included using the preprocessing
directive #include. It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard
list of system directories. You can prepend directories to this list with the -I option while
compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file'
in the directory containing the current file. You can prepend directories to this list with
the -I option while compiling your source code.

Include Operation
The #include directive works by directing the C preprocessor to scan the specified file
as input before continuing with the rest of the current source file. The output from the
preprocessor contains the output already generated, followed by the output resulting
from the included file, followed by the output that comes from the text after
the #include directive. For example, if you have a header file header.h as follows −
char *test (void);
and a main program called program.c that uses the header file, like this −
int x;
#include "header.h"

int main (void) {


puts (test ());
}

the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);

int main (void) {


puts (test ());
}

Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice
and it will result in an error. The standard way to prevent this is to enclose the entire real
contents of the file in a conditional, like this −
#ifndef HEADER_FILE
#define HEADER_FILE

the entire header file file

#endif

This construct is commonly known as a wrapper #ifndef. When the header is included
again, the conditional will be false, because HEADER_FILE is defined. The preprocessor
will skip over the entire contents of the file, and the compiler will not see it twice.
Computed Includes
Sometimes it is necessary to select one of the several different header files to be
included into your program. For instance, they might specify configuration parameters to
be used on different sorts of operating systems. You could do this with a series of
conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif

But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a
macro for the header name. This is called a computed include. Instead of writing a
header name as the direct argument of #include, you simply put a macro name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if
the #include had been written that way originally. SYSTEM_H could be defined by your
Makefile with a -D option.

• 8.what is Function
Ans: C - Functions

A function is a group of statements that together perform a task. Every C program has
at least one function, which is main(), and all the most trivial programs can define
additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call.
For example, strcat() to concatenate two strings, memcpy() to copy one memory
location to another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}

A function definition in C programming consists of a function header and a function body.


Here are all the parts of a function −
• Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that
define what the function does.

Example
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top
of the file calling the function.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function.
A called function performs a defined task and when its return statement is executed or
when its function-ending closing brace is reached, it returns the program control back to
the main program.
To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.
For example −
Live Demo

#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

We have kept max() along with main() and compiled the source code. While running the
final executable, it would produce the following result −
Max value is : 200

Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a
function −

Sr.No. Call Type & Description

1 Call by value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on
the argument.

2 Call by reference

This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within
a function cannot alter the arguments used to call the function.

Computer Programming - Functions

A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of
code reusing. You have already seen various functions like printf() and main(). These
are called built-in functions provided by the language itself, but we can write our own
functions as well and this tutorial will teach you how to write and use those functions in
C programming language.
Good thing about functions is that they are famous with several names. Different
programming languages name them differently, for example, functions, methods, sub-
routines, procedures, etc. If you come across any such terminology, then just imagine
about the same concept, which we are going to discuss in this tutorial.
Let's start with a program where we will define two arrays of numbers and then from
each array, we will find the biggest number. Given below are the steps to find out the
maximum number from a given set of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Set max = L1
3. Take next number Li from the list and do the following
4. If max is less than Li
5. Set max = Li
6. If Li is last number from the list then
7. Print value stored in max and come out
8. Else prepeat same process starting from step 3

Let's translate the above program in C programming language −


Live Demo
#include <stdio.h>

int main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, max;

/* Process first set of numbers available in set1[] */


max = set1[0];
i = 1;
while( i < 5 ) {
if( max < set1[i] ) {
max = set1[i];
}
i = i + 1;
}

printf("Max in first set = %d\n", max );

/* Now process second set of numbers available in set2[] */


max = set2[0];
i = 1;
while( i < 5 ) {
if( max < set2[i] ) {
max = set2[i];
}
i = i + 1;
}
printf("Max in second set = %d\n", max );
}

When the above code is compiled and executed, it produces the following result −
Max in first set = 50
Max in second set = 501
If you are clear about the above example, then it will become easy to understand why
we need a function. In the above example, there are only two sets of numbers, set1 and
set2, but consider a situation where we have 10 or more similar sets of numbers to find
out the maximum numbers from each set. In such a situation, we will have to repeat,
processing 10 or more times and ultimately, the program will become too large with
repeated code. To handle such situation, we write our functions where we try to keep
the source code which will be used again and again in our programming.
Now, let's see how to define a function in C programming language and then in the
subsequent sections, we will explain how to use them.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function

return [expression];
}

A function definition in C programming consists of a function header and a function body.


Here are all the parts of a function −
• Return Type − A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
• Parameter List − A parameter is like a placeholder. When a function is invoked,
you pass a value as a parameter. This value is referred to as the actual parameter
or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that
defines what the function does.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform a defined task.
Now, let's write the above example with the help of a function −
Live Demo

#include <stdio.h>

int getMax( int set[] ) {


int i, max;

max = set[0];
i = 1;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int max;

/* Process first set of numbers available in set1[] */


max = getMax(set1);
printf("Max in first set = %d\n", max );

/* Now process second set of numbers available in set2[] */


max = getMax(set2);
printf("Max in second set = %d\n", max );
}

When the above code is compiled and executed, it produces the following result −
Max in first set = 50
Max in second set = 501

Functions in Java
If you are clear about functions in C programming, then it is easy to understand them in
Java as well. Java programming names them as methods, but the rest of the concepts
remain more or less same.
Following is the equivalent program written in Java. You can try to execute it to see the
output −
public class DemoJava {
public static void main(String []args) {
int[] set1 = {10, 20, 30, 40, 50};
int[] set2 = {101, 201, 301, 401, 501};
int max;

/* Process first set of numbers available in set1[] */


max = getMax(set1);
System.out.format("Max in first set = %d\n", max );

/* Now process second set of numbers available in set2[] */


max = getMax(set2);
System.out.format("Max in second set = %d\n", max );
}
public static int getMax( int set[] ) {
int i, max;
max = set[0];
i = 1;

while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
}

When the above program is executed, it produces the following result −


Max in first set = 50
Max in second set = 501

Functions in Python
Once again, if you know the concept of functions in C and Java programming, then
Python is not much different. Given below is the basic syntax of defining a function in
Python −
def function_name( parameter list ):
body of the function

return [expression]
Using this syntax of function in Python, the above example can be written as follows −
Live Demo

def getMax( set ):


max = set[0]
i = 1

while( i < 5 ):
if( max < set[i] ):
max = set[i]

i = i + 1
return max

set1 = [10, 20, 30, 40, 50]


set2 = [101, 201, 301, 401, 501]

# Process first set of numbers available in set1[]


max = getMax(set1)
print "Max in first set = ", max

# Now process second set of numbers available in set2[]


max = getMax(set2)
print "Max in second set = ", max

When the above code is executed, it produces the following result −


Max in first set = 50
Max in second set = 501

• 9.What is NULL pointer

Ans: A Null Pointer is a pointer that does not point to any memory location. It stores
the base address of the segment. The null pointer basically stores the Null value while
void is the type of the pointer.

A null pointer is a special reserved value which is defined in a stddef header file. Here,
Null means that the pointer is referring to the 0th memory location.

If we do not have any address which is to be assigned to the pointer, then it is known as
a null pointer. When a NULL value is assigned to the pointer, then it is considered as
a Null pointer.

Applications of Null Pointer


Following are the applications of a Null pointer:

Competitive questions on Structures in Hindi

Keep Watching

o It is used to initialize o pointer variable when the pointer does not point to a valid memory
address.
o It is used to perform error handling with pointers before dereferencing the pointers.
o It is passed as a function argument and to return from a function when we do not want to
pass the actual memory address.

Examples of Null Pointer


int*ptr=(int*)0;
float*ptr=(float*)0;
char*ptr=(char*)0;
double*ptr=(double*)0;
char*ptr='\0';
int *ptr=NULL;

Let's look at the situations where we need to use the null pointer.

o When we do not assign any memory address to the pointer variable.

1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. printf("Address: %d", ptr); // printing the value of ptr.
6. printf("Value: %d", *ptr); // dereferencing the illegal pointer
7. return 0;
8. }

In the above code, we declare the pointer variable *ptr, but it does not contain the address
of any variable. The dereferencing of the uninitialized pointer variable will show the
compile-time error as it does not point any variable. According to the stack memory
concept, the local variables of a function are stored in the stack, and if the variable does
not contain any value, then it shows the garbage value. The above program shows some
unpredictable results and causes the program to crash. Therefore, we can say that keeping
an uninitialized pointer in a program can cause serious harm to the computer.

How to avoid the above situation?

We can avoid the above situation by using the Null pointer. A null pointer is a pointer
pointing to the 0th memory location, which is a reserved memory and cannot be
dereferenced.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=NULL;
5. if(ptr!=NULL)
6. {
7. printf("value of ptr is : %d",*ptr);
8. }
9. else
10. {
11. printf("Invalid pointer");
12. }
13. return 0;
14. }

In the above code, we create a pointer *ptr and assigns a NULL value to the pointer,
which means that it does not point any variable. After creating a pointer variable, we add
the condition in which we check whether the value of a pointer is null or not.

o When we use the malloc() function.

1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. ptr=(int*)malloc(4*sizeof(int));
6. if(ptr==NULL)
7. {
8. printf("Memory is not allocated");
9. }
10. else
11. {
12. printf("Memory is allocated");
13. }
14. return 0;
15. }

In the above code, we use the library function, i.e., malloc(). As we know, that malloc()
function allocates the memory; if malloc() function is not able to allocate the memory,
then it returns the NULL pointer. Therefore, it is necessary to add the condition which will
check whether the value of a pointer is null or not, if the value of a pointer is not null
means that the memory is allocated.

NULL pointer in C

At the very high level, we can think of NULL as a null pointer which is used in C for
various purposes. Some of the most common use cases for NULL are
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid
memory address yet.
b) To check for a null pointer before accessing any pointer variable. By doing so, we
can perform error handling in pointer related code e.g. dereference pointer variable
only if it’s not NULL.
c) To pass a null pointer to a function argument when we don’t want to pass any valid
memory address.
The example of a is

int * pInt = NULL;

The example of b is
if(pInt != NULL) /*We could use if(pInt) as well*/

{ /*Some code*/}

else

{ /*Some code*/}

The example of c is

int fun(int *ptr)

/*Fun specific stuff is done with ptr here*/

return 10;

fun(NULL);

It should be noted that NULL pointer is different from an uninitialized and dangling
pointer. In a specific program context, all uninitialized or dangling or NULL pointers
are invalid but NULL is a specific invalid pointer which is mentioned in C standard
and has specific purposes. What we mean is that uninitialized and dangling pointers
are invalid but they can point to some memory address that may be accessible
through the memory access is unintended.

#include <stdio.h>

int main()

{
int *i, *j;

int *ii = NULL, *jj = NULL;

if(i == j)

printf("This might get printed if both i and j are same by chance.");

if(ii == jj)

printf("This is always printed coz ii and jj are same.");

return 0;

By specifically mentioning NULL pointer, C standard gives mechanism using which a


C programmer can use and check whether a given pointer is legitimate or not. But
what exactly is NULL and how it’s defined? Strictly speaking, NULL expands to an
implementation-defined null pointer constant which is defined in many header files
such as “stdio.h”, “stddef.h”, “stdlib.h” etc. Let us see what C standards say about null
pointer. From C11 standard clause 6.3.2.3,
“An integer constant expression with the value 0, or such an expression cast to type void
*, is called a null pointer constant. If a null pointer constant is converted to a pointer
type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a
pointer to any object or function.”
Before we proceed further on this NULL discussion :), let’s mention few lines about C
standard just in case you wants to refer it for further study. Please note that ISO/IEC
9899:2011 is the C language’s latest standard which was published in Dec 2011. This
is also called the C11 standard. For completeness, let us mention that previous
standards for C were C99, C90 (also known as ISO C) and C89 (also known as ANSI C).
Though the actual C11 standard can be purchased from ISO, there’s a draft document
which is available in public domain for free.
Coming to our discussion, NULL macro is defined as ((void *)0) in header files of most
of the C compiler implementations. But C standard is saying that 0 is also a null
pointer constant. It means that the following is also perfectly legal as per standard.

int * ptr = 0;

Please note that 0 in the above C statement is used in pointer-context and it’s different
from 0 as integer. This is one of the reasons why the usage of NULL is preferred
because it makes it explicit in code that programmer is using null pointer, not integer
0. Another important concept about NULL is that “NULL expands to an
implementation-defined null pointer constant”. This statement is also from C11 clause
7.19. It means that internal representation of the null pointer could be non-zero bit
pattern to convey NULL pointer. That’s why NULL always needn’t be internally
represented as all zeros bit pattern. A compiler implementation can choose to
represent “null pointer constant” as a bit pattern for all 1s or anything else. But again,
as a C programmer, we needn’t worry much on the internal value of the null pointer
unless we are involved in Compiler coding or even below the level of coding. Having
said so, typically NULL is represented as all bits set to 0 only. To know this on a
specific platform, one can use the following

#include<stdio.h>

int main()

printf("%d",NULL);

return 0;

Most likely, it’s printing 0 which is the typical internal null pointer value but again it
can vary depending on the C compiler/platform. You can try few other things in above
program such as printf(“‘%c“,NULL) or printf(“%s”,NULL) and
even printf(“%f”,NULL). The outputs of these are going to be different depending on
the platform used but it’d be interesting especially usage of %f with NULL!
Can we use sizeof() operator on NULL in C? Well, usage of sizeof(NULL) is allowed but
the exact size would depend on platform.

#include<stdio.h>

int main()

printf("%lu",sizeof(NULL));

return 0;

Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its
size would be equal to any pointer. If the pointer size of a platform is 4 bytes, the
output of the above program would be 4. But if pointer size on a platform is 8 bytes,
the output of the above program would be 8.
What about dereferencing of NULL? What’s going to happen if we use the following C
code

#include<stdio.h>

int main()

int * ptr = NULL;

printf("%d",*ptr);

return 0;

}
On some machines, the above would compile successfully but crashes when the
program is run through it needn’t show the same behaviour across all the machines.
Again it depends on a lot of factors. But the idea of mentioning the above snippet is
that we should always check for NULL before accessing it.
Since NULL is typically defined as ((void*)0), let us discuss a little bit about void type
as well. As per C11 standard clause 6.2.5, “The void type comprises an empty set of
values; it is an incomplete object type that cannot be completed”. Even C11 clause
6.5.3.4 mentions that “The sizeof operator shall not be applied to an expression that has
function type or an incomplete type, to the parenthesized name of such a type, or to an
expression that designates a bit-field member.” Basically, it means that void is an
incomplete type whose size doesn’t make any sense in C programs but
implementations (such as gcc) can choose sizeof(void) as 1 so that the flat memory
pointed by void pointer can be viewed as untyped memory i.e. a sequence of bytes.
But the output of the following needn’t to same on all platforms.

#include<stdio.h>

int main()

printf("%lu",sizeof(void));

return 0;

On gcc, the above would output 1. What about sizeof(void *)? Here C11 has mentioned
guidelines. From clause 6.2.5, “A pointer to void shall have the same representation and
alignment requirements as a pointer to a character type”. That’s why the output of the
following would be same as any pointer size on a machine.

#include<stdio.h>

int main()

{
printf("%lu",sizeof(void *));

return 0;

Inspite of mentioning machine dependent stuff as above, we as C programmers


should always strive to make our code as portable as possible. So we can conclude on
NULL as follows:
1. Always initialize pointer variables as NULL.
2. Always perform a NULL check before accessing any pointer.

• 10. What is ARRAY


Ans: Introduction to Arrays

An array is a collection of items stored at contiguous memory locations. The idea is


to store multiple items of the same type together. This makes it easier to calculate
the position of each element by simply adding an offset to a base value, i.e., the
memory location of the first element of the array (generally denoted by the name of
the array). The base value is index 0 and the difference between the two indexes is
the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is
placed a value (let’s say one of your friends). Here, you can identify the location of
any of your friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.
The above image can be looked at as a top-level view of a staircase where you are at
the base of the staircase. Each element can be uniquely identified by its index in the
array (in a similar way as you could identify your friends by the step on which they
were on in the above example).
Array’s size
In C language, array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it neither can you expand it. The reason was that for
expanding, if we change the size we can’t be sure ( it’s not possible every time) that
we get the next memory location to us as free. The shrinking will not work because
the array, when declared, gets memory statically allocated, and thus compiler is the
only one can destroy it.
Types of indexing in an array:
• 0 (zero-based indexing): The first element of the array is indexed by a subscript
of 0.
• 1 (one-based indexing): The first element of the array is indexed by the subscript
of 1.
• n (n-based indexing): The base index of an array can be freely chosen. Usually,
programming languages allowing n-based indexing also allow negative index
values, and other scalar data types like enumerations, or characters may be used
as an array index.

• C++
• C

#include <iostream>
using namespace std;

int main()

// Creating an integer array named arr of size 10.

int arr[10];

// accessing element at 0 index and setting its value

// to 5.

arr[0] = 5;

// access and print value at 0 index we get the output

// as 5.

cout << arr[0];

return 0;

Output
5
Here the value 5 is printed because the first element has index zero and at zeroth
index we already assigned the value 5.
Advantages of using arrays:
• Arrays allow random access to elements. This makes accessing elements by
position faster.
• Arrays have better cache locality that makes a pretty big difference in
performance.
• Arrays represent multiple data items of the same type using a single name.
Disadvantages of using arrays:
You can’t change the size i.e. once you have declared the array you can’t change its
size because of static memory allocation. Here Insertion(s) and deletion(s) are
difficult as the elements are stored in consecutive memory locations and the shifting
operation is costly too.
Now if take an example of implementation of data structure Stack using array there
are some obvious flaw.
Let’s take the POP operation of the stack. The algorithm would go something like
this.
1. Check for the stack underflow
2. Decrement the top by 1
So there what we are doing is that, the pointer to the topmost element is
decremented means we are just bounding our view actually that element stays there
taking up of the memory space. If you have any primitive datatype then it might be
ok but the object of an array would take a lot of memory.
Examples –
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};

// An Integer array in C/C++/Java


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

// Item at i'th index in array is typically accessed


// as "arr[i]". For example arr1[0] gives us 'g'
// and arr2[3] gives us 40.
Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is
simply called an array.
Applications on Array
1. Array stores data elements of the same data type.
2. Arrays can be used for CPU scheduling.
3. Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables,
etc.

Arrays in C/C++
• Difficulty Level : Easy
• Last Updated : 27 Jan, 2022
An array in C/C++ or be it in any programming language is a collection of similar
data items stored at contiguous memory locations and elements can be accessed
randomly using indices of an array. They can be used to store collection of primitive
data types such as int, float, double, char, etc of any particular type. To add to it, an
array in C/C++ can store derived data types such as the structures, pointers etc.
Given below is the picture representation of an array.

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of objects,
but if we want to store a large number of instances, it becomes difficult to manage
them with normal variables. The idea of an array is to represent many instances in
one variable.
Array declaration in C/C++:
Note: In above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete
since GCC 2.5
There are various ways in which we can declare an array. It can be done by
specifying its type and size, by initializing it or both.
Array declaration by specifying size
• C

// Array declaration by specifying size

int arr1[10];

// With recent C/C++ versions, we can also

// declare an array of user specified size

int n = 10;

int arr2[n];

Array declaration by initializing elements


• C

// Array declaration by initializing elements

int arr[] = { 10, 20, 30, 40 }

// Compiler creates an array of size 4.

// above is same as "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying size and initializing elements


• C

// Array declaration by specifying size and initializing

// elements

int arr[6] = { 10, 20, 30, 40 }

// Compiler creates an array of size 6, initializes first

// 4 elements as specified by user and rest two elements as

// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"

Advantages of an Array in C/C++:


1. Random access of elements using array index.
2. Use of fewer line of code as it creates a single array of multiple elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing fewer line of code.
Disadvantages of an Array in C/C++:
1. Allows a fixed number of elements to be entered which is decided at the time of
declaration. Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to
be managed in accordance with the new memory allocation.
Facts about Array in C/C++:
• Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts with 0
and goes till size of array minus 1.
• Name of the array is also a pointer to the first element of array.
Example:
• C
• C++

#include <stdio.h>

int main()

int arr[5];

arr[0] = 5;

arr[2] = -10;

arr[3 / 2] = 2; // this is same as arr[1] = 2

arr[3] = arr[0];
printf("%d %d %d %d", arr[0],

arr[1], arr[2], arr[3]);

return 0;

Output
5 2 -10 5
No Index Out of bound Checking:
There is no index out of bounds checking in C/C++, for example, the following
program compiles fine but may produce unexpected output when run.
• C
• C++

// This C program compiles fine

// as index out of bound

// is not checked in C.

#include <stdio.h>

int main()

int arr[2];
printf("%d ", arr[3]);

printf("%d ", arr[-2]);

return 0;

Output
-449684907 4195777
In C, it is not a compiler error to initialize an array with more elements than the
specified size. For example, the below program compiles fine and shows just
Warning.

• C

#include <stdio.h>

int main()

// Array declaration by initializing it

// with more elements than specified size.

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


return 0;

Warnings:
prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:33: note: (near initialization for 'arr')
• Note: The program won’t compile in C++. If we save the above program as a .cpp,
the program generates compiler error “error: too many initializers for ‘int [2]'”.

The elements are stored at contiguous memory locations


Example:
• C
• C++

// C program to demonstrate that

// array elements are stored

// contiguous locations
#include <stdio.h>

int main()

// an array of 10 integers.

// If arr[0] is stored at

// address x, then arr[1] is

// stored at x + sizeof(int)

// arr[2] is stored at x +

// sizeof(int) + sizeof(int)

// and so on.

int arr[5], i;

printf("Size of integer in this compiler is %lu\n",

sizeof(int));

for (i = 0; i < 5; i++)

// The use of '&' before a variable name, yields

// address of variable.
printf("Address arr[%d] is %p\n", i, &arr[i]);

return 0;

Output
Size of integer in this compiler is 4
Address arr[0] is 0x7ffe75c32210
Address arr[1] is 0x7ffe75c32214
Address arr[2] is 0x7ffe75c32218
Address arr[3] is 0x7ffe75c3221c
Address arr[4] is 0x7ffe75c32220
Another way to traverse the array

• C++

#include<bits/stdc++.h>

using namespace std;

int main()

int arr[6]={11,12,13,14,15,16};

// Way 1

for(int i=0;i<6;i++)
cout<<arr[i]<<" ";

cout<<endl;

// Way 2

cout<<"By Other Method:"<<endl;

for(int i=0;i<6;i++)

cout<<i[arr]<<" ";

cout<<endl;

return 0;

// Contributed by Akshay Pawar ( Username - akshaypawar4)

Output
11 12 13 14 15 16
By Other Method:
11 12 13 14 15 16
Array vs Pointers
Arrays and pointers are two different things (we can check by applying sizeof). The
confusion happens because array name indicates the address of first element and
arrays are always passed as pointers (even if we use square bracket). Please
see Difference between pointer and array in C? for more details.
What is vector in C++?
A vector in C++ is a class in STL that represents an array. The advantages of vector
over normal arrays are,
• We do not need pass size as an extra parameter when we declare a vector i.e,
Vectors support dynamic sizes (we do not have to initially specify size of a
vector). We can also resize a vector.
• Vectors have many in-built functions like, removing an element, etc.

Arrays in Java
• Difficulty Level : Easy
• Last Updated : 03 Dec, 2021

An array in Java is a group of like-typed variables referred to by a common name.


Arrays in Java work differently than they do in C/C++. Following are some
important points about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other variables with [] after the
data type.
• The variables in the array are ordered, and each has an index beginning from 0.
• Java array can be also be used as a static field, a local variable, or a method
parameter.
• The size of an array must be specified by int or short value and not long.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class depending on the definition of the array. In the case of primitive
data types, the actual values are stored in contiguous memory locations. In the case
of class objects, the actual objects are stored in a heap segment.
Creating, Initializing, and Accessing an Array

One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares the
element type of the array. The element type determines the data type of each
element that comprises the array. Like an array of integers, we can also create an
array of other primitive data types like char, float, double, etc., or user-defined data
types (objects of a class). Thus, the element type for the array determines what type
of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object


Collection[] ca; // array of Collection
// of unknown type
Although the first declaration establishes that intArray is an array variable, no
actual array exists. It merely tells the compiler that this variable (intArray) will
hold an array of the integer type. To link intArray with an actual, physical array of
integers, you must allocate one using new and assign it to intArray.

Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To create or give


memory to the array, you create an array like this: The general form of new as it
applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number of
elements in the array, and var-name is the name of the array variable that is linked
to the array. To use new to allocate an array, you must specify the type and
number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note :
1. The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference types).
Refer Default array values in Java
2. Obtaining an array is a two-step process. First, you must declare a variable of the
desired array type. Second, you must allocate the memory to hold the array,
using new, and assign it to the array variable. Thus, in Java, all arrays are
dynamically allocated.

Array Literal

In a situation where the size of the array and variables of the array are already
known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of Java.

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends
at (total array size)-1. All the elements of array can be accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
Implementation:
• Java

// Java program to illustrate creating an array

// of integers, puts some values in the array,

// and prints each value to standard output.

class GFG

public static void main (String[] args)

// declares an Array of integers.

int[] arr;
// allocating memory for 5 integers.

arr = new int[5];

// initialize the first elements of the array

arr[0] = 10;

// initialize the second elements of the array

arr[1] = 20;

//so on...

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

System.out.println("Element at index " + i +

" : "+ arr[i]);

}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
You can also access java arrays using foreach loops.

Arrays of Objects

An array of objects is created like an array of primitive type data items in the
following way.
Student[] arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of the size of student class in
which the address of seven Student objects can be stored. The Student objects have
to be instantiated using the constructor of the Student class, and their references
should be assigned to the array elements in the following way.
Student[] arr = new Student[5];

• Java
// Java program to illustrate creating

// an array of objects

class Student

public int roll_no;

public String name;

Student(int roll_no, String name)

this.roll_no = roll_no;

this.name = name;

// Elements of the array are objects of a class Student.

public class GFG

public static void main (String[] args)

{
// declares an Array of integers.

Student[] arr;

// allocating memory for 5 objects of type Student.

arr = new Student[5];

// initialize the first elements of the array

arr[0] = new Student(1,"aman");

// initialize the second elements of the array

arr[1] = new Student(2,"vaibhav");

// so on...

arr[2] = new Student(3,"shikar");

arr[3] = new Student(4,"dharmesh");

arr[4] = new Student(5,"mohit");

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)


System.out.println("Element at " + i + " : " +

arr[i].roll_no +" "+ arr[i].name);

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been


accessed with an illegal index. The index is either negative or greater than or equal
to the size of an array.
• Java

public class GFG

public static void main (String[] args)

int[] arr = new int[2];

arr[0] = 10;

arr[1] = 20;
for (int i = 0; i <= arr.length; i++)

System.out.println(arr[i]);

Runtime error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at GFG.main(File.java:12)
Output
10
20

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ([]) per
dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

• Java

public class multiDimensional

public static void main(String args[])

{
// declaring and initializing 2D array

int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

// printing 2D array

for (int i=0; i< 3 ; i++)

for (int j=0; j < 3 ; j++)

System.out.print(arr[i][j] + " ");

System.out.println();

Output
2 7 9
3 6 1
7 4 2
Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, the below program
passes the array to method sum to calculate the sum of the array’s values.
• Java

// Java program to demonstrate

// passing of array to method

public class Test

// Driver method

public static void main(String args[])

int arr[] = {3, 1, 2, 5, 4};


// passing array to method m1

sum(arr);

public static void sum(int[] arr)

// getting sum of array values

int sum = 0;

for (int i = 0; i < arr.length; i++)

sum+=arr[i];

System.out.println("sum of array values : " + sum);

Output
sum of array values : 15

Returning Arrays from Methods

As usual, a method can also return an array. For example, the below program
returns an array from method m1.
• Java

// Java program to demonstrate

// return of array from method

class Test

// Driver method

public static void main(String args[])

int arr[] = m1();

for (int i = 0; i < arr.length; i++)

System.out.print(arr[i]+" ");

public static int[] m1()

// returning array
return new int[]{1,2,3};

Output
1 2 3

Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the
same component type.

• Java

// Java program to demonstrate

// Class Objects for Arrays

class Test

public static void main(String args[])

int intArray[] = new int[3];

byte byteArray[] = new byte[3];

short shortsArray[] = new short[3];


// array of Strings

String[] strArray = new String[3];

System.out.println(intArray.getClass());

System.out.println(intArray.getClass().getSuperclass());

System.out.println(byteArray.getClass());

System.out.println(shortsArray.getClass());

System.out.println(strArray.getClass());

Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation:
1. The string “[I” is the run-time type signature for the class object “array with
component type int.”
2. The only direct superclass of an array type is java.lang.Object.
3. The string “[B” is the run-time type signature for the class object “array with
component type byte.”
4. The string “[S” is the run-time type signature for the class object “array with
component type short.”
5. The string “[L” is the run-time type signature for the class object “array with
component type of a Class.” The Class name is then followed.
Array Members

Now, as you know that arrays are objects of a class, and a direct superclass of arrays
is a class Object. The members of an array type are all of the following:
• The public final field length, which contains the number of components of the
array. Length may be positive or zero.
• All the members inherited from class Object; the only method of Object that is
not inherited is its clone method.
• The public method clone(), which overrides the clone method in class Object and
throws no checked exceptions.

Arrays Types and Their Allowed Element Types

Array Types Allowed Element Types

Any type which can be implicitly promoted to declared


Primitive Type Arrays type.

Object Type Arrays Either declared type objects or it’s child class objects.

Abstract Class Type


Arrays Its child-class objects are allowed.

Interface Type Arrays Its implementation class objects are allowed.

Cloning of arrays

When you clone a single-dimensional array, such as Object[], a “deep copy” is


performed with the new array containing copies of the original array’s elements as
opposed to references.

• Java
// Java program to demonstrate

// cloning of one-dimensional arrays

class Test

public static void main(String args[])

int intArray[] = {1,2,3};

int cloneArray[] = intArray.clone();

// will print false as deep copy is created

// for one-dimensional array

System.out.println(intArray == cloneArray);

for (int i = 0; i < cloneArray.length; i++) {

System.out.print(cloneArray[i]+" ");

}
}

Output
false
1 2 3

A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however,


which is to say that it creates only a single new array with each element array a
reference to an original element array, but subarrays are shared.

• Java

// Java program to demonstrate


// cloning of multi-dimensional arrays

class Test

public static void main(String args[])

int intArray[][] = {{1,2,3},{4,5}};

int cloneArray[][] = intArray.clone();

// will print false

System.out.println(intArray == cloneArray);

// will print true as shallow copy is created

// i.e. sub-arrays are shared

System.out.println(intArray[0] == cloneArray[0]);

System.out.println(intArray[1] == cloneArray[1]);

}
}

Output
false
true
true

11. Explian pillar of OOPS


Ans: The four pillars of object-oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

• 12. Do you know about data structure


Ans: Data Structure and Types
What are Data Structures?
Data structure is a storage that is used to store and organize data. It is a way
of arranging data on a computer so that it can be accessed and updated
efficiently.

Depending on your requirement and project, it is important to choose the right


data structure for your project. For example, if you want to store data
sequentially in the memory, then you can go for the Array data structure.

Array data
Structure Representation

Note: Data structure and data types are slightly different. Data structure is the
collection of data types arranged in a specific order.

Types of Data Structure


Basically, data structures are divided into two categories:

• Linear data structure

• Non-linear data structure

Let's learn about each type in detail.

Linear data structures


In linear data structures, the elements are arranged in sequence one after the
other. Since elements are arranged in particular order, they are easy to
implement.

However, when the complexity of the program increases, the linear data
structures might not be the best choice because of operational complexities.

Popular linear data structures are:


1. Array Data Structure

In an array, elements in memory are arranged in continuous memory. All the


elements of an array are of the same type. And, the type of elements that can
be stored in the form of arrays is determined by the programming language.

To learn more, visit Java Array.


An array with each element
represented by an index

2. Stack Data Structure

In stack data structure, elements are stored in the LIFO principle. That is, the
last element stored in a stack will be removed first.

It works just like a pile of plates where the last plate kept on the pile will be
removed first. To learn more, visit Stack Data Structure.

In a stack, operations can be perform only from one end (top


here).

3. Queue Data Structure

Unlike stack, the queue data structure works in the FIFO principle where first
element stored in the queue will be removed first.
It works just like a queue of people in the ticket counter where first person on
the queue will get the ticket first. To learn more, visit Queue Data Structure.

In a queue, addition and removal are


performed from separate ends.

4. Linked List Data Structure

In linked list data structure, data elements are connected through a series of
nodes. And, each node contains the data items and address to the next node.

To learn more, visit Linked List Data Structure.

A
linked list

Non linear data structures


Unlike linear data structures, elements in non-linear data structures are not in
any sequence. Instead they are arranged in a hierarchical manner where one
element will be connected to one or more elements.

Non-linear data structures are further divided into graph and tree based data
structures.

1. Graph Data Structure

In graph data structure, each node is called vertex and each vertex is
connected to other vertices through edges.

To learn more, visit Graph Data Structure.

Graph data structure example

Popular Graph Based Data Structures:


• Spanning Tree and Minimum Spanning Tree
• Strongly Connected Components
• Adjacency Matrix
• Adjacency List
2. Trees Data Structure

Similar to a graph, a tree is also a collection of vertices and edges. However,


in tree data structure, there can only be one edge between two vertices.
To learn more, visit Tree Data Structure.

Tree data structure example

Popular Tree based Data Structure


• Binary Tree
• Binary Search Tree
• AVL Tree
• B-Tree
• B+ Tree
• Red-Black Tree

Linear Vs Non-linear Data Structures


Now that we know about linear and non-linear data structures, let's see the
major differences between them.

Linear Data Structures Non Linear Data Structures


The data items are arranged in sequential order, one The data items are arranged in non-sequential order
after the other. (hierarchical manner).

All the items are present on the single layer. The data items are present at different layers.

It can be traversed on a single run. That is, if we start It requires multiple runs. That is, if we start from the
from the first element, we can traverse all the first element it might not be possible to traverse all
elements sequentially in a single pass. the elements in a single pass.

Different structures utilize memory in different


The memory utilization is not efficient.
efficient ways depending on the need.

The time complexity increase with the data size. Time complexity remains the same.

Example: Arrays, Stack, Queue Example: Tree, Graph, Map

Why Data Structure?

Knowledge about data structures help you understand the working of each
data structure. And, based on that you can select the right data structures for
your project.

This helps you write memory and time efficient code.


Why Learn Data Structures and
Algorithms?
In this article, we will learn why every programmer should learn data
structures and algorithms with the help of examples.

This article is for those who have just started learning algorithms and
wondered how impactful it will be to boost their career/programming skills. It is
also for those who wonder why big companies like Google, Facebook, and
Amazon hire programmers who are exceptionally good at optimizing
Algorithms.

What are Algorithms?


Informally, an algorithm is nothing but a mention of steps to solve a problem.
They are essentially a solution.

For example, an algorithm to solve the problem of factorials might look


something like this:

Problem: Find the factorial of n

Initialize fact = 1

For every value v in range 1 to n:

Multiply the fact by v

fact contains the factorial of n


Here, the algorithm is written in English. If it was written in a programming
language, we would call it to code instead. Here is a code for finding the
factorial of a number in C++.

int factorial(int n) {
int fact = 1;
for (int v = 1; v <= n; v++) {
fact = fact * v;
}
return fact;
}

Programming is all about data structures and algorithms. Data structures are
used to hold data while algorithms are used to solve the problem using that
data.

Data structures and algorithms (DSA) goes through solutions to standard


problems in detail and gives you an insight into how efficient it is to use each
one of them. It also teaches you the science of evaluating the efficiency of an
algorithm. This enables you to choose the best of various choices.

Use of Data Structures and Algorithms to Make Your


Code Scalable
Time is precious.
Suppose, Alice and Bob are trying to solve a simple problem of finding the
sum of the first 1011 natural numbers. While Bob was writing the algorithm,
Alice implemented it proving that it is as simple as criticizing Donald Trump.
Algorithm (by Bob)

Initialize sum = 0

for every natural number n in range 1 to 1011 (inclusive):

add n to sum

sum is your answer

Code (by Alice)

int findSum() {
int sum = 0;
for (int v = 1; v <= 100000000000; v++) {
sum += v;
}
return sum;
}

Alice and Bob are feeling euphoric of themselves that they could build
something of their own in almost no time. Let's sneak into their workspace and
listen to their conversation.

Alice: Let's run this code and find out the sum.
Bob: I ran this code a few minutes back but it's still not showing the output.
What's wrong with it?

Oops, something went wrong! A computer is the most deterministic machine.


Going back and trying to run it again won't help. So let's analyze what's wrong
with this simple code.
Two of the most valuable resources for a computer program
are time and memory.
The time taken by the computer to run code is:

Time to run code = number of instructions * time to execute each instruction

The number of instructions depends on the code you used, and the time taken
to execute each code depends on your machine and compiler.

In this case, the total number of instructions executed (let's say x) are x = 1 +

(1011 + 1) + (1011) + 1 , which is x = 2 * 1011 + 3

Let us assume that a computer can execute y = 108 instructions in one second
(it can vary subject to machine configuration). The time taken to run above
code is

Time taken to run code = x/y (greater than 16 minutes)

Is it possible to optimize the algorithm so that Alice and Bob do not have to
wait for 16 minutes every time they run this code?

I am sure that you already guessed the right method. The sum of
first N natural numbers is given by the formula:

Sum = N * (N + 1) / 2

Converting it into code will look something like this:

int sum(int N) {

return N * (N + 1) / 2;

}
This code executes in just one instruction and gets the task done no matter
what the value is. Let it be greater than the total number of atoms in the
universe. It will find the result in no time.

The time taken to solve the problem, in this case, is 1/y (which is 10
nanoseconds). By the way, the fusion reaction of a hydrogen bomb takes 40-
50 ns, which means your program will complete successfully even if someone
throws a hydrogen bomb on your computer at the same time you ran your
code. :)

Note: Computers take a few instructions (not 1) to compute multiplication and


division. I have said 1 just for the sake of simplicity.

More on Scalability

Scalability is scale plus ability, which means the quality of an algorithm/system


to handle the problem of larger size.

Consider the problem of setting up a classroom of 50 students. One of the


simplest solutions is to book a room, get a blackboard, a few chalks, and the
problem is solved.

But what if the size of the problem increases? What if the number of
students increased to 200?
The solution still holds but it needs more resources. In this case, you will
probably need a much larger room (probably a theater), a projector screen
and a digital pen.
What if the number of students increased to 1000?
The solution fails or uses a lot of resources when the size of the problem
increases. This means, your solution wasn't scalable.

What is a scalable solution then?


Consider a site like Khanacademy, millions of students can see videos, read
answers at the same time and no more resources are required. So, the
solution can solve the problems of larger size under resource crunch.
If you see our first solution to find the sum of first N natural numbers, it wasn't
scalable. It's because it required linear growth in time with the linear growth in
the size of the problem. Such algorithms are also known as linearly scalable
algorithms.
Our second solution was very scalable and didn't require the use of any more
time to solve a problem of larger size. These are known as constant-time
algorithms.

Memory is expensive

Memory is not always available in abundance. While dealing with code/system


which requires you to store or produce a lot of data, it is critical for your
algorithm to save the usage of memory wherever possible. For example:
While storing data about people , you can save memory by storing only their
date of birth, not their age. You can always calculate it on the fly using their
date of birth and current date.
Examples of an Algorithm's Efficiency
Here are some examples of what learning algorithms and data structures
enable you to do:

Example 1: Age Group Problem

Problems like finding the people of a certain age group can easily be solved
with a little modified version of the binary search algorithm (assuming that the
data is sorted).
The naive algorithm which goes through all the persons one by one, and
checks if it falls in the given age group is linearly scalable. Whereas, binary
search claims itself to be a logarithmically scalable algorithm. This means that
if the size of the problem is squared, the time taken to solve it is only doubled.

Suppose, it takes 1 second to find all the people at a certain age for a group of
1000. Then for a group of 1 million people,

• the binary search algorithm will take only 2 seconds to solve the problem

• the naive algorithm might take 1 million seconds, which is around 12 days

The same binary search algorithm is used to find the square root of a number.

Example 2: Rubik's Cube Problem

Imagine you are writing a program to find the solution of a Rubik's cube.

This cute looking puzzle has annoyingly 43,252,003,274,489,856,000


positions, and these are just positions! Imagine the number of paths one can
take to reach the wrong positions.
Fortunately, the way to solve this problem can be represented by the graph
data structure. There is a graph algorithm known as Dijkstra's algorithm which
allows you to solve this problem in linear time. Yes, you heard it right. It
means that it allows you to reach the solved position in a minimum number of
states.

Example 3: DNA Problem

DNA is a molecule that carries genetic information. They are made up of


smaller units which are represented by Roman characters A, C, T, and G.

Imagine yourself working in the field of bioinformatics. You are assigned the
work of finding out the occurrence of a particular pattern in a DNA strand.

It is a famous problem in computer science academia. And, the simplest


algorithm takes the time proportional to

(number of character in DNA strand) * (number of characters in pattern)

A typical DNA strand has millions of such units. Eh! worry not. KMP
algorithm can get this done in time which is proportional to

(number of character in DNA strand) + (number of characters in pattern)

The * operator replaced by + makes a lot of change.


Considering that the pattern was of 100 characters, your algorithm is now 100
times faster. If your pattern was of 1000 characters, the KMP algorithm would
be almost 1000 times faster. That is, if you were able to find the occurrence of
pattern in 1 second, it will now take you just 1 ms. We can also put this in
another way. Instead of matching 1 strand, you can match 1000 strands of
similar length at the same time.

And there are infinite such stories...

Final Words
Generally, software development involves learning new technologies on a
daily basis. You get to learn most of these technologies while using them in
one of your projects. However, it is not the case with algorithms.

If you don't know algorithms well, you won't be able to identify if you can
optimize the code you are writing right now. You are expected to know them in
advance and apply them wherever possible and critical.

We specifically talked about the scalability of algorithms. A software system


consists of many such algorithms. Optimizing any one of them leads to a
better system.

However, it's important to note that this is not the only way to make a system
scalable. For example, a technique known as distributed computing allows
independent parts of a program to run to multiple machines together making it
even more scalable.
• 13. Explain Stack and queue
Ans: Difference between Stack and Queue Data Structures
• Difficulty Level : Medium
• Last Updated : 07 Jul, 2020
Stack A stack is a linear data structure in which elements can be inserted and
deleted only from one side of the list, called the top. A stack follows the LIFO (Last
In First Out) principle, i.e., the element inserted at the last is the first element to
come out. The insertion of an element into stack is called push operation, and
deletion of an element from the stack is called pop operation. In stack we always
keep track of the last element present in the list with a pointer called top.
The diagrammatic representation of stack is given below:

Queue: A queue is a linear data structure in which elements can be inserted only
from one side of the list called rear, and the elements can be deleted only from the
other side called the front. The queue data structure follows the FIFO (First In First
Out) principle, i.e. the element inserted at first in the list, is the first element to be
removed from the list. The insertion of an element in a queue is called
an enqueue operation and the deletion of an element is called a dequeue operation.
In queue we always maintain two pointers, one pointing to the element which was
inserted at the first and still present in the list with the front pointer and the second
pointer pointing to the element inserted at the last with the rear pointer.
The diagrammatic representation of queue is given below:
Difference between Stack and Queue Data Structures
Stacks Queues

Stacks are based on the LIFO


principle, i.e., the element Queues are based on the FIFO principle, i.e., the
inserted at the last, is the first element inserted at the first, is the first element to
element to come out of the list. come out of the list.

Insertion and deletion in queues takes place from


Insertion and deletion in stacks the opposite ends of the list. The insertion takes
takes place only from one end of place at the rear of the list and the deletion takes
the list called the top. place from the front of the list.

Insert operation is called push


operation. Insert operation is called enqueue operation.

Delete operation is called pop


operation. Delete operation is called dequeue operation.
Stacks Queues

In stacks we maintain only one In queues we maintain two pointers to access the
pointer to access the list, called list. The front pointer always points to the first
the top, which always points to element inserted in the list and is still present, and
the last element present in the the rear pointer always points to the last inserted
list. element.

Stack is used in solving problems Queue is used in solving problems having


works on recursion. sequential processing.

Stack vs. Queue


First, we will look at what is stack and what is queue individually, and then we will
discuss the differences between stack and queue.

What is a Stack?
A Stack is a linear data structure. In case of an array, random access is possible, i.e., any
element of an array can be accessed at any time, whereas in a stack, the sequential access
is only possible. It is a container that follows the insertion and deletion rule. It follows the
principle LIFO (Last In First Out) in which the insertion and deletion take place from one
side known as a top. In stack, we can insert the elements of a similar data type, i.e., the
different data type elements cannot be inserted in the same stack. The two operations are
performed in LIFO, i.e., push and pop operation.
The following are the operations that can be performed on the stack:

o push(x): It is an operation in which the elements are inserted at the top of the stack. In
the push function, we need to pass an element which we want to insert in a stack.
o pop(): It is an operation in which the elements are deleted from the top of the stack. In
the pop() function, we do not have to pass any argument.
o peek()/top(): This function returns the value of the topmost element available in the stack.
Like pop(), it returns the value of the topmost element but does not remove that element
from the stack.
o isEmpty(): If the stack is empty, then this function will return a true value or else it will
return a false value.
o isFull(): If the stack is full, then this function will return a true value or else it will return a
false value.

In stack, the top is a pointer which is used to keep track of the last inserted element. To
implement the stack, we should know the size of the stack. We need to allocate the
memory to get the size of the stack. There are two ways to implement the stack:

Skip Ad

o Static: The static implementation of the stack can be done with the help of arrays.
o Dynamic: The dynamic implementation of the stack can be done with the help of a linked
list.

What is the Queue?


A Queue is a linear data structure. It is an ordered list that follows the principle FIFO (First
In -First Out). A Queue is a structure that follows some restrictions on insertion and
deletion. In the case of Queue, insertion is performed from one end, and that end is known
as a rear end. The deletion is performed from another end, and that end is known as a
front end. In Queue, the technical words for insertion and deletion
are enqueue() and dequeue(), respectively whereas, in the case of the stack, the
technical words for insertion and deletion are push() and pop(), respectively. Its structure
contains two pointers front pointer and rear pointer, where the front pointer is a pointer
that points to the element that was first added in the queue and the rear pointer that
points to the element inserted last in the queue.

Similarities between stack and queue.


There are two similarities between the stack and queue:

o Linear data structure


Both the stack and queue are the linear data structure, which means that the elements are
stored sequentially and accessed in a single run.
o Flexible in size
Both the stack and queue are flexible in size, which means they can grow and shrink
according to the requirements at the run-time.

Differences between stack and queue


Basis for Stack Queue
comparison

Principle It follows the principle LIFO (Last In- It follows the principle FIFO (First In -First
First Out), which implies that the Out), which implies that the element which is
element which is inserted last would added first would be the first element to be
be the first one to be deleted. removed from the list.

Structure It has only one end from which both It has two ends, i.e., front and rear end. The
the insertion and deletion take front end is used for the deletion while the
place, and that end is known as a rear end is used for the insertion.
top.

Number of It contains only one pointer known It contains two pointers front and rear
pointers used as a top pointer. The top pointer pointer. The front pointer holds the address
holds the address of the last of the first element, whereas the rear pointer
inserted or the topmost element of holds the address of the last element in a
the stack. queue.

Operations It performs two operations, push It performs mainly two operations, enqueue
performed and pop. The push operation inserts and dequeue. The enqueue operation
the element in a list while the pop performs the insertion of the elements in a
operation removes the element queue while the dequeue operation performs
from the list. the deletion of the elements from the queue.

Examination of the If top==-1, which means that the If front== -1 or front = rear+1, which means
empty condition stack is empty. that the queue is empty.

Examination of full If top== max-1, this condition If rear==max-1, this condition implies that
condition implies that the stack is full. the stack is full.

Variants It does not have any types. It is of three types like priority queue, circular
queue and double ended queue.

Implementation It has a simpler implementation. It has a comparatively complex


implementation than a stack.

Visualization A Stack is visualized as a vertical A Queue is visualized as a horizontal


collection. collection.
• 14. Data encapsulation
All C++ programs are composed of the following two fundamental elements −
• Program statements (code) − This is the part of a program that performs actions
and they are called functions.
• Program data − The data is the information of the program which gets affected
by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse. Data encapsulation led to the important OOP concept of data
hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use
them and data abstraction is a mechanism of exposing only the interfaces and hiding
the implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes. We already have studied that a class can
contain private, protected and public members. By default, all items defined in a class
are private. For example −
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you
must declare them after the public keyword. All variables or functions defined after the
public specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all
other classes as possible.

Data Encapsulation Example


Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction. Consider the following example −
Live Demo

#include <iostream>
using namespace std;

class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}

// interface to outside world


void addNum(int number) {
total += number;
}

// interface to outside world


int getTotal() {
return total;
};

private:
// hidden data from outside world
int total;
};

int main() {
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public
members addNum and getTotal are the interfaces to the outside world and a user
needs to know them to use the class. The private member total is something that is
hidden from the outside world, but is needed for the class to operate properly.
Designing Strategy
Most of us have learnt to make class members private by default unless we really need
to expose them. That's just good encapsulation.
This is applied most frequently to data members, but it applies equally to all members,
including virtual functions.

• 15.Data abstraction
Ans: Data abstraction refers to providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation
of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and
DVD players, BUT you do not know its internal details, that is, you do not know how it
receives signals over the air or through a cable, how it translates them, and finally
displays them on the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having any knowledge of its internals.
In C++, classes provides great level of data abstraction. They provide sufficient public
methods to the outside world to play with the functionality of the object and to manipulate
object data, i.e., state without actually knowing how class has been implemented
internally.
For example, your program can make a call to the sort() function without knowing what
algorithm the function actually uses to sort the given values. In fact, the underlying
implementation of the sorting functionality could change between releases of the library,
and as long as the interface stays the same, your function call will still work.
In C++, we use classes to define our own abstract data types (ADT). You can use
the cout object of class ostream to stream data to standard output like this −
Live Demo

#include <iostream>
using namespace std;

int main() {
cout << "Hello C++" <<endl;
return 0;
}

Here, you don't need to understand how cout displays the text on the user's screen. You
need to only know the public interface and the underlying implementation of ‘cout’ is free
to change.

Access Labels Enforce Abstraction


In C++, we use access labels to define the abstract interface to the class. A class may
contain zero or more access labels −
• Members defined with a public label are accessible to all parts of the program.
The data-abstraction view of a type is defined by its public members.
• Members defined with a private label are not accessible to code that uses the
class. The private sections hide the implementation from code that uses the type.
There are no restrictions on how often an access label may appear. Each access label
specifies the access level of the succeeding member definitions. The specified access
level remains in effect until the next access label is encountered or the closing right brace
of the class body is seen.

Benefits of Data Abstraction


Data abstraction provides two important advantages −
• Class internals are protected from inadvertent user-level errors, which might
corrupt the state of the object.
• The class implementation may evolve over time in response to changing
requirements or bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is free
to make changes in the data. If the implementation changes, only the class code needs
to be examined to see what affect the change may have. If data is public, then any
function that directly access the data members of the old representation might be broken.

Data Abstraction Example


Any C++ program where you implement a class with public and private members is an
example of data abstraction. Consider the following example −
Live Demo

#include <iostream>
using namespace std;

class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}

// interface to outside world


void addNum(int number) {
total += number;
}

// interface to outside world


int getTotal() {
return total;
};

private:
// hidden data from outside world
int total;
};

int main() {
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public members
- addNum and getTotal are the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that the user doesn't need
to know about, but is needed for the class to operate properly.

Designing Strategy
Abstraction separates code into interface and implementation. So while designing your
component, you must keep interface independent of the implementation so that if you
change underlying implementation then interface would remain intact.
In this case whatever programs are using these interfaces, they would not be impacted
and would just need a recompilation with the latest implementation.
• 16. Data Inheritance
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an opportunity
to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members
of an existing class. This existing class is called the base class, and the new class is
referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A
animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base and Derived Classes


A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation
list to specify the base class(es). A class derivation list names one or more base classes
and has the form −
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the
name of a previously defined class. If the access-specifier is not used, then it is private
by default.
Consider a base class Shape and its derived class Rectangle as follows −
Live Demo

#include <iostream>

using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Total area: 35

Access Control and Inheritance


A derived class can access all the non-private members of its base class. Thus base-
class members that should not be accessible to the member functions of derived classes
should be declared private in the base class.
We can summarize the different access types according to - who can access them in the
following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no


A derived class inherits all base class methods with the following exceptions −

• Constructors, destructors and copy constructors of the base class.


• Overloaded operators of the base class.
• The friend functions of the base class.

Type of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is specified by
the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied −
• Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the derived
class and protected members of the base class become protected members of
the derived class. A base class's private members are never accessible directly
from a derived class, but can be accessed through calls to
the public and protected members of the base class.
• Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
• Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.

Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended
syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base
class and they will be separated by comma as shown above. Let us try the following
example −
Live Demo

#include <iostream>

using namespace std;

// Base class Shape


class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost {
public:
int getCost(int area) {
return area * 70;
}
};

// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;
int area;

Rect.setWidth(5);
Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450

17. Polymorphism
The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function
to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two
classes −
Live Demo
#include <iostream>
using namespace std;

class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};

class Triangle: public Shape {


public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

// store the address of Triangle


shape = &tri;

// call triangle area.


shape->area();

return 0;
}

When the above code is compiled and executed, it produces the following result −
Parent class area :
Parent class area :
The reason for the incorrect output is that the call of the function area() is being set once
by the compiler as the version defined in the base class. This is called static
resolution of the function call, or static linkage - the function call is fixed before the
program is executed. This is also sometimes called early binding because the area()
function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of
area() in the Shape class with the keyword virtual so that it looks like this −
class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and executed,
it produces the following result −
Rectangle class area
Triangle class area
This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
since addresses of objects of tri and rec classes are stored in *shape the respective
area() function is called.
As you can see, each of the child classes has a separate implementation for the function
area(). This is how polymorphism is generally used. You have different classes with a
function of the same name, and even the same parameters, but with different
implementations.

Virtual Function
A virtual function is a function in a base class that is declared using the keyword virtual.
Defining in a base class a virtual function, with another version in a derived class, signals
to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called. This sort of operation is
referred to as dynamic linkage, or late binding.

Pure Virtual Functions


It is possible that you want to include a virtual function in a base class so that it may be
redefined in a derived class to suit the objects of that class, but that there is no
meaningful definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the following −
class Shape {
protected:
int width, height;

public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}

// pure virtual function


virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual function will be
called pure virtual function.

• 18.Explain some important differences between C & C++.


As we know both C and C++ are programming languages and used for application
development. The main difference between both these languages is C is a procedural
programming language and does not support classes and objects, while C++ is a
combination of both procedural and object-oriented programming languages.
The following are the important differences between C and C++.

Sr. Key C C++


No.

Introduction C was developed by Dennis Ritchie C++ was developed by Bjarne


1
in around 1969 at AT&T Bell Labs. Stroustrup in 1979.

Language As mentioned before C is On the other hand, C++ supports both


2 Type procedural programming. procedural and object-oriented
programming paradigms.

OOPs As C does not support the OOPs C++ has support for polymorphism,
feature concept so it has no support for encapsulation, and inheritance as it is
3
Support polymorphism, encapsulation, and being an object-oriented
inheritance. programming language

Data As C does not support On another hand in the case of C++


Security encapsulation so data behave as a encapsulation hides the data to
4
free entity and can be manipulated ensure that data structures and
by outside code. operators are used as intended.

Driven type C in general known as function- On the other hand, C++ is known as
5
driven language. object driven language.
Sr. Key C C++
No.

Feature C does not support function and On the other hand, C++ supports both
supported operator overloading also do not function and operator overloading
6
have namespace feature and also have namespace feature and
reference variable functionality. reference variable functionality.

• 19.Can we implement multiple inheritances in Java?


Whenever, you extend a class a copy of superclass’s members is available to the
subclass object and, when you can call the method of the superclass using the object of
the subclass.

Example
In the following example, we have a class named SuperClass with a method with name
demo(). We are extending this class with another class (SubClass).
Now, you create an object of the subclass and call the method demo().

Live Demo
class SuperClass{
public void demo() {
System.out.println("demo method");
}
}
public class SubClass extends SuperClass {
public static void main(String args[]) {
SubClass obj = new SubClass();
obj.demo();
}
}

Output
demo method
Multiple inheritance in java
For suppose, if we have two classes namely, SuperClass1 and SuperClass2 with the
same method say demo() (including parameters) as shown below −
class SuperClass1{
public void demo() {
System.out.println("demo method");
}
}
class SuperClass2{
public void demo() {
System.out.println("demo method");
}
}
Now, from another class, if extend both the classes as −
public class SubClass extends SuperClass1, SuperClass2 {
public static void main(String args[]) {
SubClass obj = new SubClass();
obj.demo();
}
}
According to the basic rule of inheritance, a copy of both demo() methods should be
created in the subclass object which leaves the subclass with two methods with the same
prototype. Then, if you call the demo() method using the object of the subclass compiler
faces an ambiguous situation not knowing which method to call.
Therefore, in Java multiple inheritance is not allowed and, you cannot extend more than
one other class. Still, if you try to do so, a compile-time error is generated.

Compile time error


On compiling, the above program generates the following error −
MultipleInheritanceExample.java:9: error: '{' expected
public class MultipleInheritanceExample extends MyInterface1,
MyInterface2{
^
1 error

Multiple inheritance using interfaces


In case of multiple interfaces with the same default method. In the concrete class
implementing both interfaces, you can implement the common method and call both
super methods. thus You can achieve multiple inheritance in Java using interfaces.

Example
Live Demo
interface MyInterface1{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface1");
}
}
interface MyInterface2{
public static int num = 1000;
public default void display() {
System.out.println("display method of MyInterface2");
}
}

public class InterfaceExample implements MyInterface1,


MyInterface2{
public void display() {
System.out.println("This is the implementation of the display
method");
}
public void show() {
MyInterface1.super.display();
MyInterface2.super.display();
}

public static void main(String args[]) {


InterfaceExample obj = new InterfaceExample();
obj.show();
}
}
Output
display method of MyInterface1
display method of MyInterface2

• 20. How method overloading is different from method


overriding?
The differences between Method Overloading and Method Overriding in Java
are:

S.NO Method Overloading Method Overriding

Method overloading is a compile- Method overriding is a run-time


1. time polymorphism. polymorphism.

It is used to grant the specific


implementation of the method which is
It helps to increase the readability of already provided by its parent class or
2. the program. superclass.

It is performed in two classes with


3. It occurs within the class. inheritance relationships.

Method overloading may or may not Method overriding always needs


4. require inheritance. inheritance.

In method overloading, methods In method overriding, methods must


must have the same name and have the same name and same
5. different signatures. signature.
S.NO Method Overloading Method Overriding

In method overloading, the return


type can or can not be the same, but
we just have to change the In method overriding, the return type
6. parameter. must be the same or co-variant.

Method Overloading:
Method Overloading is a Compile time polymorphism. In method overloading,
more than one method shares the same method name with a different signature
in the class. In method overloading, the return type can or can not be the same,
but we have to change the parameter because, in java, we can not achieve the
method overloading by changing only the return type of the method.
Example of Method Overloading:
• Java

import java.io.*;

class MethodOverloadingEx {

static int add(int a, int b)

return a + b;

static int add(int a, int b, int c)


{

return a + b + c;

public static void main(String args[])

System.out.println("add() with 2 parameters");

System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");

System.out.println(add(4, 6, 7));

Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, the
derived class provides the specific implementation of the method that is already
provided by the base class or parent class. In method overriding, the return type
must be the same or co-variant (return type may vary in the same direction as
the derived class).
Example of Method Overriding:
• Java

import java.io.*;

class Animal {

void eat()

System.out.println("eat() method of base class");

System.out.println("eating.");

class Dog extends Animal {

void eat()

System.out.println("eat() method of derived class");

System.out.println("Dog is eating.");

}
}

class MethodOverridingEx {

public static void main(String args[])

Dog d1 = new Dog();

Animal a1 = new Animal();

d1.eat();

a1.eat();

Animal animal = new Dog();

// eat() method of animal class is overridden by

// base class eat()

animal.eat();

Output
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Explanation:
Here, we can see that a method eat() has overridden in the derived class
name Dog that is already provided by the base class name Animal.
When we create the instance of class Dog and call the eat() method, we see
that only derived class eat() method run instead of base class method eat(), and
When we create the instance of class Animal and call the eat() method, we see
that only base class eat() method run instead of derived class method eat().
So, it’s clear that in method overriding, the method is bound to the instances on
the run time, which is decided by the JVM. That’s why it is called Run time
polymorphism.

21.Distinguish between classes and interfaces in Java.


Differences between a Class and an Interface:

Class Interface

The keyword used to create a class is The keyword used to create an interface is
“class” “interface”

A class can be instantiated i.e, objects of An Interface cannot be instantiated i.e,


a class can be created. objects cannot be created.

Classes does not support multiple


inheritance. Interface supports multiple inheritance.

It can be inherit another class. It cannot inherit a class.

It can be inherited by a class by using the


It can be inherited by another class using keyword ‘implements’ and it can be inherited
the keyword ‘extends’. by an interface using the keyword ‘extends’.
Class Interface

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be


declared using any access
specifier(public, private, default, All variables and methods in a interface are
protected) declared as public.

Variables in a class can be static, final or


neither. All variables are static and final.

22.Why indexing in SQL is useful


A SQL index is a quick lookup table for finding records users need
to search frequently. An index is small, fast, and optimized for
quick lookups. It is very useful for connecting the relational
tables and searching large tables. Notice that not only creating
a primary key creates a unique SQL index.
Indexes are special lookup tables that the database search engine can use to speed
up data retrieval. Simply put, an index is a pointer to data in a table. An index in a
database is very similar to an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic,
you first refer to the index, which lists all the topics alphabetically and are then referred
to one or more specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down
data input, with the UPDATE and the INSERT statements. Indexes can be created or
dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate
whether the index is in an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents
duplicate entries in the column or combination of columns on which there is an index.

The CREATE INDEX Command


The basic syntax of a CREATE INDEX is as follows.
CREATE INDEX index_name ON table_name;

Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is
as follows.
CREATE INDEX index_name
ON table_name (column_name);

Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any duplicate values to be inserted into the table. The basic syntax
is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);

Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as
follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration
the column(s) that you may use very frequently in a query's WHERE clause as filter
conditions.
Should there be only one column used, a single-column index should be the choice.
Should there be two or more columns that are frequently used in the WHERE clause as
filters, the composite index would be the best choice.

Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when
an object is created. Indexes are automatically created for primary key constraints and
unique constraints.
The DROP INDEX Command
An index can be dropped using SQL DROP command. Care should be taken when
dropping an index because the performance may either slow down or improve.
The basic syntax is as follows −
DROP INDEX index_name;
You can check the INDEX Constraint chapter to see some actual examples on Indexes.

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there are times
when they should be avoided.
The following guidelines indicate when the use of an index should be reconsidered.
• Indexes should not be used on small tables.
• Tables that have frequent, large batch updates or insert operations.
• Indexes should not be used on columns that contain a high number of NULL
values.
• Columns that are frequently manipulated should not be indexed.

. 23.What is the left outer join and the right outer join in SQL?
1. column
2.
3. WHERE [condition];
Diagrammatic Representation :
4. Right Outer Join:
Right Outer Join returns all the rows from the table on the right and columns
of the table on the left is null padded. Right Outer Join retrieves all the rows
from both the tables that satisfy the join condition along with the unmatched
rows of the right table.
Syntax:
SELECT [column1, column2, ....]
FROM table1

RIGHT OUTER JOIN table2 ON


table1.matching_column = table2.matching_column

WHERE [condition];
Or,
SELECT [column1, column2, ....]
FROM table1

RIGHT OUTER JOIN table2


ON table1.matching_column(+) = table2.matching_column

WHERE [condition];
Diagrammatic Representation :

5. Full Outer Join:


Full Outer Join returns all the rows from both the table. When no matching
rows exist for the row in the left table, the columns of the right table are null
padded. Similarly, when no matching rows exist for the row in the right table,
the columns of the left table are null padded. Full outer join is the union of
left outer join and right outer join.
Syntax:
SELECT [column1, column2, ....]
FROM table1

FULL OUTER JOIN table2


ON table1.matching_column = table2.matching_column

WHERE [condition];
Diagrammatic Representation :

Example:
Consider following employee table,
EMPID ENAME EMPDEPT SALARY
101 Amanda Development 50000

102 Diana HR 40000

103 Bruce Designing 30000

104 Steve Testing 35000

105 Roger Analyst 10000

Department Table :
DEPTID DEPTNAME LOCATION
10 Development New York

11 Designing New York

12 Testing Washington

13 HelpDesk Los Angeles

Now,
1. Left Outer Join query –
Select empid, ename, deptid, deptname
from employee
left outer join department
on employee.empdept = department.deptname;
Output:
EMPID ENAME DEPTID DEPTNAME
101 Amanda 10 Development

103 Bruce 11 Designing

104 Steve 12 Testing

102 Diana null null

105 Roger null null

2. Right Outer Join query –


Select empid, ename, deptid, deptname
from employee right outer join department
on employee.empdept = department.deptname;
EMPID ENAME DEPTID DEPTNAME
101 Amanda 10 Development

103 Bruce 11 Designing


104 Steve 12 Testing

null null 13 HelpDesk

3. Full Outer Join query –


Select empid, ename, deptid, deptname
from employee full outer join department
on employee.empdept = department.deptname;
EMPID ENAME DEPTID DEPTNAME
101 Amanda 10 Development

103 Bruce 11 Designing

104 Steve 12 Testing

102 Diana null null

105 Roger null null

null null 13 HelpDesk

Differences between Left Outer Join, Right Outer Join, Full Outer Join :
Left Outer Join Right Outer Join Full Outer Join
Fetches all the rows from the Fetches all the rows from the Fetches all the rows from
table on the left table on the right both the tables

Inner Join +
all the unmatched rows from
Inner Join + Inner Join + the left table +
all the unmatched rows from all the unmatched rows from all the unmatched rows from
the left table the right table the right table

Unmatched data of the right Unmatched data of the left


table is lost table is lost No data is lost
SELECT [column1, SELECT [column1, SELECT [column1,
column2, ….] column2, ….] column2, ….]
FROM table1 FROM table1 FROM table1
LEFT OUTER JOIN table2 RIGHT OUTER JOIN table2 FULL OUTER JOIN table2
ON ON ON
table1.matching_column = table1.matching_column = table1.matching_column =
table2.matching_column table2.matching_column table2.matching_column

. 24.Explain pointers in C++.


Pointers in C/C++ with Examples

Pointers are symbolic representation of addresses. They enable programs to


simulate call-by-reference as well as to create and manipulate dynamic data
structures. It’s general declaration in C/C++ has the format:
Syntax:
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data

How to use a pointer?


• Define a pointer variable
• Assigning the address of a variable to a pointer using unary operator (&) which
returns the address of that variable.
• Accessing the value stored in the address using unary operator (*) which returns
the value of the variable located at the address specified by its operand.
The reason we associate data type to a pointer is that it knows how many bytes
the data is stored in. When we increment a pointer, we increase the pointer by the
size of data type to which it points.

• C
• C++

// C++ program to illustrate Pointers in C++

#include <stdio.h>

void geeks()

int var = 20;


// declare pointer variable

int *ptr;

// note that data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

printf("Value at ptr = %p \n",ptr);

printf("Value at var = %d \n",var);

printf("Value at *ptr = %d \n", *ptr);

// Driver program

int main()

geeks();

Output:
Value at ptr = 0x7ffcb9e9ea4c
Value at var = 20
Value at *ptr = 20
References and Pointers
There are 3 ways to pass C++ arguments to a function:
• call-by-value
• call-by-reference with pointer argument
• call-by-reference with reference argument

// C++ program to illustrate call-by-methods in C++

#include <bits/stdc++.h>

using namespace std;

//Pass-by-Value

int square1(int n)

//Address of n in square1() is not the same as n1 in main()

cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function

n *= n;

return n;

//Pass-by-Reference with Pointer Arguments


void square2(int *n)

//Address of n in square2() is the same as n2 in main()

cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to

*n *= *n;

//Pass-by-Reference with Reference Arguments

void square3(int &n)

//Address of n in square3() is the same as n3 in main()

cout << "address of n3 in square3(): " << &n << "\n";

// Implicit de-referencing (without '*')

n *= n;

void geeks()

{
//Call-by-Value

int n1=8;

cout << "address of n1 in main(): " << &n1 << "\n";

cout << "Square of n1: " << square1(n1) << "\n";

cout << "No change in n1: " << n1 << "\n";

//Call-by-Reference with Pointer Arguments

int n2=8;

cout << "address of n2 in main(): " << &n2 << "\n";

square2(&n2);

cout << "Square of n2: " << n2 << "\n";

cout << "Change reflected in n2: " << n2 << "\n";

//Call-by-Reference with Reference Arguments

int n3=8;

cout << "address of n3 in main(): " << &n3 << "\n";

square3(n3);

cout << "Square of n3: " << n3 << "\n";

cout << "Change reflected in n3: " << n3 << "\n";


}

//Driver program

int main()

geeks();

Output:
address of n1 in main(): 0x7ffcdb2b4a44
address of n1 in square1(): 0x7ffcdb2b4a2c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7ffcdb2b4a48
address of n2 in square2(): 0x7ffcdb2b4a48
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7ffcdb2b4a4c
address of n3 in square3(): 0x7ffcdb2b4a4c
Square of n3: 64
Change reflected in n3: 64
In C++, by default arguments are passed by value and the changes made in the called
function will not reflect in the passed variable. The changes are made into a clone
made by the called function.
If wish to modify the original copy directly (especially in passing huge object or
array) and/or avoid the overhead of cloning, we use pass-by-reference. Pass-by-
Reference with Reference Arguments does not require any clumsy syntax for
referencing and dereferencing.
• Function pointers in C
• Pointer to a function
Array Name as Pointers
An array name contains the address of first element of the array which acts like
constant pointer. It means, the address stored in array name can’t be changed.
For example, if we have an array named val then val and &val[0] can be used
interchangeably.
• C
• C++

// C program to illustrate call-by-methods

#include <stdio.h>

void geeks()

//Declare an array

int val[3] = { 5, 10, 20 };

//declare pointer variable

int *ptr;

//Assign the address of val[0] to ptr

// We can use ptr=&val[0];(both are same)


ptr = val ;

printf("Elements of the array are: ");

printf("%d %d %d", ptr[0], ptr[1], ptr[2]);

//Driver program

int main()

geeks();

Output:
Elements of the array are: 5 10 20

If pointer ptr is sent to a function as an argument, the array val can be accessed in a
similar fashion.
Pointer vs Array
Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers which are:
• incremented ( ++ )
• decremented ( — )
• an integer may be added to a pointer ( + or += )
• an integer may be subtracted from a pointer ( – or -= )
• difference between two pointers (p1-p2)
(Note: Pointer arithmetic is meaningless unless performed on an array.)
// C++ program to illustrate Pointer Arithmetic in C++

#include <bits/stdc++.h>

using namespace std;

void geeks()

//Declare an array

int v[3] = {10, 100, 200};

//declare pointer variable

int *ptr;

//Assign the address of v[0] to ptr

ptr = v;

for (int i = 0; i < 3; i++)

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at *ptr = " << *ptr << "\n";


// Increment pointer ptr by 1

ptr++;

//Driver program

int main()

geeks();

Output:
Value at ptr = 0x7fff9a9e7920
Value at *ptr = 10
Value at ptr = 0x7fff9a9e7924
Value at *ptr = 100
Value at ptr = 0x7fff9a9e7928
Value at *ptr = 200

Advanced Pointer Notation


Consider pointer notation for the two-dimensional numeric arrays. consider the
following declaration
int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } };
In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)

Pointers and String literals


String literals are arrays containing null-terminated character sequences. String
literals are arrays of type character plus terminating null-character, with each of the
elements being of type const char (as characters of string can’t be modified).
const char * ptr = "geek";
This declares an array with the literal representation for “geek”, and then a pointer
to its first element is assigned to ptr. If we imagine that “geek” is stored at the
memory locations that start at address 1800, we can represent the previous
declaration as:

As pointers and arrays behave in the same way in expressions, ptr can be used to
access the characters of string literal. For example:
char x = *(ptr+3);
char y = ptr[3];
Here, both x and y contain k stored at 1803 (1800+3).
Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or other
pointer. The syntax simply requires the unary operator (*) for each level of
indirection while declaring the pointer.
char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;
Here b points to a char that stores ‘g’ and c points to the pointer b.
Void Pointers
This is a special type of pointer available in C++ which represents absence of type.
void pointers are pointers that point to a value that has no type (and thus also an
undetermined length and undetermined dereferencing properties).
This means that void pointers have great flexibility as it can point to any data type.
There is payoff for this flexibility. These pointers cannot be directly dereferenced.
They have to be first transformed into some other pointer type that points to a
concrete data type before being dereferenced.

// C++ program to illustrate Void Pointer in C++

#include <bits/stdc++.h>

using namespace std;

void increase(void *data,int ptrsize)

if(ptrsize == sizeof(char))

char *ptrchar;

//Typecast data to a char pointer

ptrchar = (char*)data;
//Increase the char stored at *ptrchar by 1

(*ptrchar)++;

cout << "*data points to a char"<<"\n";

else if(ptrsize == sizeof(int))

int *ptrint;

//Typecast data to a int pointer

ptrint = (int*)data;

//Increase the int stored at *ptrchar by 1

(*ptrint)++;

cout << "*data points to an int"<<"\n";

void geek()

// Declare a character
char c='x';

// Declare an integer

int i=10;

//Call increase function using a char and int address respectively

increase(&c,sizeof(c));

cout << "The new value of c is: " << c <<"\n";

increase(&i,sizeof(i));

cout << "The new value of i is: " << i <<"\n";

//Driver program

int main()

geek();

Output:
*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11
Invalid pointers
A pointer should point to a valid address but not necessarily to valid elements (like
for arrays). These are called invalid pointers. Uninitialized pointers are also invalid
pointers.
int *ptr1;
int arr[10];
int *ptr2 = arr+20;
Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds
of arr so it also becomes an invalid pointer.
(Note: invalid pointers do not necessarily raise compile errors)
NULL Pointers
Null pointer is a pointer which point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;

. 25.What are the differences between C++ and Java? Which one
do you think is better and why?

The major differences between C++ and Java have been summarised in the
following table:

COMPARISON
INDEX C++ JAVA
PARAMETER
C++ was developed by Bjarne
Developed / Stroustrup at Bell Labs in 1979. Java was developed by James Gosling at Sun
1
Founded by It was developed as an extension Microsystems. Now, it is owned by Oracle.
of the C language.
It has support for both
Java has support only for object oriented
2 Programming model procedural programming and
programming models.
object oriented programming.
C++ is platform dependent. It is
Platform Java is platform independent. It is based on
3 based on the concept of Write
dependence the concept of Write Once Run Anywhere.
Once Compile Anywhere.
C++ supports features like
Java does not support features like operator
operator overloading, Goto
4 Features supported overloading, Goto statements, structures,
statements, structures, pointers,
pointers, unions, etc.
unions, etc.
Compilation and C ++ is only compiled and
5 Java can be both compiled and interpreted.
Interpretation cannot be interpreted.
Java, on the other hand, has more diverse
C++ has very limited libraries
libraries with a lot of support for code
Library and Code with low level functionalities.
6 reusability. In Java, only calls through the
reusability support C++ allows direct calls to native
Java Native Interface and recently Java
system libraries.
Native Access are allowed.
Memory In C++, memory management is In Java, memory management is System
7
Management manual. controlled.
C++ is pretty consistent between In Java, semantics differs for primitive and
8 Type semantics
primitive and object types. object types.
In C++, both global and
9 Global Scope namespace scopes are Java has no support for global scope.
supported.
Access control and In C++, a flexible model with In Java, the model is cumbersome and
10
object protection constant protection is available. encourages weak encapsulation.

Conclusion

So, in conclusion,we would like to mention that both the languages are used by a
plethora of big Software Companies and therefore, learning both of them could
prove to be extremely useful.

For people looking forward to taking a job in the Software Industry, or already
have a Software Engineering Job, it is better to learn more about Java because
of the diversity and flexibility it provides. However, for people looking to work on
building operating systems, gaming engines, etc. where high performance is
needed, C++ can turn out to be a better programming language than Java as it is
way faster than Java.

. 26.Give examples of data structures in C++.


Data Structures in C++
As we know that the C++ programming language offers several exciting and
useful features and functionalities to its users. And it also does support object-
oriented programming. With this technique, you can perform some major
methods such as Encapsulation, Abstraction, Inheritance, Polymorphism etc.
In C++, data structures are a useful and inescapable part of programming.
With the help of data structures, we perform operations on data such as data
representation, storage, organization and many more.

What are Data Structures


With the help of data structures, you can organize data in a particular way so
that it can be used effectively. There are several ways to organize the data in
memory.

Let me tell you that it is not a programming language, it is a set of algorithms


which one can use to structure data into memory in any programming
language.

Below, we stored a list of items using the array data structure.


Data Types C++
It is just a group of similar data under a single name. Data types that are
similar share similar characteristics and behave in a similar way.

For example, if you want to store the address of a person or house then you
should use ‘string’ data type.

Data types are categorized into two broad categories:-

1. Primitive Data Type:- These are pre-defined data types. It is also known as
fundamental data types. Example:- int, float, double, char, string etc.
2. Non-Primitive Data Type:- These are user-defined data types. Example:-
array, structures, unions, structures, linked lists etc.
Types of Data Structures in C++
In C++, data structures are further categorized into 3 types.

1. Simple Data Structures


These data structures are built from primitive data types like int, float, double,
char etc.

Example:- An array is a data structure that holds the same data type and the
structure is also a data type that holds different data types.
2. Compound Data Structures
You can also build compound data structures by combining simple data
structures. Compound data structures are classified into:-

a. Linear Data Structure:– If the elements of a data structure are ordered in


sequence then it is a linear data structure. Example:- stacks, queues and
linked lists.
b. Non-Linear Data Structure:– These data structures are not linear. These
are multilevel data structures. Example:- trees, graphs etc.
3. Static and Dynamic Data Structures
Static data structures are constant in size and structure. It is associated with
specific memory locations fixed at compilation time.

You can expand or contract a data structure according to your needs during
the execution of the program. And these types of data structures are known as
Dynamic Data Structure.

Operations on Data Structures


Below are the basic operations which you can perform on the data structures
in C++:-

• Insertion: Adding a new data element into the data structure.


• Deletion: This operation is about deleting or removing an existing data
element from the data structure.
• Traversal: This operation is about processing and displaying all the data
elements in the data structure.
• Searching: Searching a specific data element in the data structure.
• Sorting: This operation is about arranging all the data elements in the data
structure either in ascending or descending order.
• Merging: This operation is about combining similar data elements from
two or more data structures.
C++ Arrays
Arrays are simply a collection of similar data types stored at contiguous
memory locations. It can store primitive types of data like int, char, float,
double etc. With the help of the arrays, a programmer can access the elements
very easily.

Suppose, you want to store marks of 20 students then you might try to declare
20 variables like student1_marks, student2_marks etc. But what if i tell you
that you can do all those with a single variable named array. With the help of a
few lines of code, you can access those elements.
6 9 8 5 3

0 1 2 3 4
Array of size 5
Syntax for declaring an array:-
dataType array_name[arraySize];

So, if you want to access the second element of the above array, then you
have to do:-
cout<<array[1]

Example:-
#include<iostream>

using namespace std;

int main()

int numbers[3] = {2, 3, 4};

cout<<"First number is: "<<numbers[0]<<endl;

cout<<"Last number is: "<<numbers[2];

Output:-
First number is: 2
Last number is: 4

C++ Linked List


A linked list can be defined as a collection of connected nodes. It is a linear
data structure. A linked list contains two parts such as:-

• Data Part:- Contains the data of the user.


• Pointer Part:- It points to the next member of the linked list.
In the above image, Head contains the address of the first node. And the last
node in the linked list points to NULL.
Nodes are stored at different locations.
There are three types of linked list such as Singly Linked List, Doubly Linked
List and Circular Linked List.

Below, we have created a singly linked list of three members.

// Node Initializing!

struct node *HEAD;

struct node *ONE = NULL;

struct node *TWO = NULL;

struct node *THREE = NULL;

// Allocating memory!

ONE = malloc(sizeof(struct node));

TWO = malloc(sizeof(struct node));

THREE = malloc(sizeof(struct node));

// Assigning the values of data!

ONE->data = 23;

TWO->data = 34;

THREE->data = 90;

// Connecting nodes with each other!

ONE->next = TWO;

TWO->next = THREE;
THREE->next = NULL;

// Saving the address of first node

HEAD = ONE;

Stack in C++
Stack is known as a linear data structure. It follows the Last-In-First-Out rule.
So, if you push something to the stack then the last value which you pushed,
will be the first to pop out. The insertion and deletion operation on the stack
will only take place from one end which is the top of the stack.

In 2 ways, you can implement a stack in C++:-

1. Statically:- You can implement a stack using an array. It allows static


memory allocation of its data elements. In this, the stack inherits all the
features of the array.
2. Dynamically:- You can also implement a stack using a linked list. It allows
dynamic memory allocation of its data elements. In this, the stack takes over
the characteristics of the linked list.
Queue in C++
Queue is known as a linear data structure. It follows the First-In-First-Out
rule. So, if you push something to the stack then the first value of the stack will
pop out. In the queue, the insertion operation is possible from the rear
end(back) and the deletion is from the front.

In 2 ways, you can implement the queue:-

1. Statically:- You can implement a queue using an array. It allows static


memory allocation of its data elements. In this, the queue inherits all the
features of the array.
2. Dynamically:- You can also implement a queue using a linked list. It allows
dynamic memory allocation of its data elements. In this, the queue takes over
the characteristics of the linked list.
C++ Trees
It is a bit of a complex and complicated data structure.

A tree is known as a finite and non-empty set of elements in mathematical


terms. Trees are hierarchical data structures. A tree includes multiple nodes.
This data structure follows the parent-child relationship. It is not a linear data
structure like array, structure, linked lists etc. It is a non-linear data structure.
C++ Structure
The structure is a user-defined data type. It works similarly like arrays.
Structures help you in grouping items of different types in a single group. It
stores the collection of different data types. Each element of structure is a
member.

Defining a structure in C++:-


Before creating variables of structure, you have to define it first. You can use
the struct keyword to define structures.
Syntax:-
struct name_of_the_structure

data_type member1;
data_type member2;

...

data_type memberN;

};

Example:-
struct bill

float amount;

int id;

char address[100];

};

In the above example, we have defined a structure named bill. And the
members of this structure are amount, id and address.
Accessing members of structures in C++:-
Before using the structure variables, you will have to access the members of
the structure. There are 2 ways to access the member of the structure:-

Use . operator

• Use -> operator (structure pointer operator)
Suppose, you want to access the amount member of the p1 variable from the
above example then you can use . operator like below:-

p1.amount;

Example:- Accessing members of structures


#include <iostream>

using namespace std;

struct Tech{

int a = 0;

int b = 1;
};

int main()

struct Tech t1;

cout << "a: " << t1.a << " and b: " << t1.b<<endl;

t1.a = 5;

t1.b = 10;

cout << "a: " << t1.a << " and b: " << t1.b;

return 0;

Output:-
a: 0 and b: 1
a: 5 and b: 10

Structure as function arguments


You can also pass a function to structures. It helps you in making your coding
better and efficient.

Example:- passing function to structures


#include <iostream>

#include <string.h>

using namespace std;

struct info {

char student_name[50];

char favorite_subject[20];

int id;

};

void display( struct info each_student );

int main() {
struct info s1;

strcpy( s1.student_name, "Tom Sawer");

strcpy( s1.favorite_subject, "English");

s1.id = 20;

// printing first student details!

display(s1);

return 0;

void display( struct info each_student ) {

cout<<"Name of first student: "<< each_student.student_name<<endl;

cout<<"Favourite subject of first student: "<<each_student.favorite_subject<<endl;

cout<<"ID of first student: "<<each_student.id<<endl;

Output:-
Name of first student: Tom Sawer
Favourite subject of first student: English
ID of first student: 20

. 27. Tell me one disadvantage of using C++.


Advantages of C++:
• C++ is an object-oriented programming language. It may be a collection of
commands, which tell the pc to try to do “something.” This collection of
commands is typically called C++ ASCII text files.
• C++ could also be a problem-oriented language that’s much easier to use
than the other low-level languages like binary coding. It takes much more
space than low-level languages but it’s much easier to understand and learn.
• C++ program has many advantages when it involves programming, All C++
program stand-alone files must use the foremost function to allow the
program to start out up and motivate its functions.
• C++ program can support unions and structures that are a mix of stand-
alone and put-together files, It uses the standard C++ application mentioned
as “.cpp”, C++ uses the reserved library word mentioned as “goto” that’s the
same as Java’s continue, or break commands.
• The global data and global functions are used within C++ that aren’t utilized
in many other high-level languages within the pc sciences and it is an
advantage to the programming languages.
• As C++ doesn’t use the objects, it’s difficult to make the programs that have
inheritance data and thus the reformed the programs to contribute to the
other data and therefore the programs, it is possible to undertake to the
present, however, but is difficult, These inheritance data and programs are
mentioned because of the inheritance trees.
• C++ doesn’t support class methods that are faithful away, but class methods
are basically functions, and sometimes they’re referred to as functions.
• C++ program uses multi-paradigm programming, Paradigm means the
planning of programming, paradigm concerned about the logic, the structure,
and procedure of program, C++ program is multi-paradigm means it follows
three paradigms Generic, Imperative, Object-Oriented.
• C++ program is useful for low-level programming language and really
efficient for general purposes, It offers performance and memory efficiently,
It offers high-level abstraction, within the language of the matter domain
• C++ may be a system programming and features a relatively clear and
mature standard,
• C++ program supports inline function, C++ supports exception handling, it’s
pointer and references, C++ uses cin and cout.
Disadvantages of C++:
• One major problem in C++ is when the info points to an equivalent thing from
two different starting points, this causes a serious problem, the C++ program
will still have involved problems within the coding.
• Java’s uni-code to the ASCII rules is 16-bit, while C++ program is 8-bit only,
So, C++ may be a less impressive programming language but saves the
memory.
• C++ program is complex during a very large high-level program, C++ is
employed for platform-specific application commonly, For the actual OS or
platform, the library set is typically chosen.
• C++ program can’t support garbage pickup, It doesn’t support Dynamic
Memory Allocation, it’s not secure because it’s a pointer, friend function, and
global variable and it’s no support for threads built-in.
• C++ programs are often heavy if it’s not careful, C++ program allows classes
and thus the functions with an equivalent name and overloaded
functions thus the symbol mangling system must be used, It can easily be
wrapped in C functions though.
• C++ program has no notion of being fast and it’s not used for platform-
dependent apps any longer than C or anything is. Actually, given the
character of the toolchain, it’s probably less dependent than others. Complex
in a very large high-level program.
• It is used for platform-specific applications commonly.
• For a specific OS or platform, the library set is typically chosen that locks.

. 28.How is polymorphism implemented in Java?


Java implements polymorphism in two ways: 1. Static or compile-time
polymorphism is done by method overloading (more then one methods
sharing the same name but different number/types/order of parameters) 2.
Dynamic or runtime polymorphism is done by method overriding (defining a
method in the child.

Types of Polymorphism

There are two different types of Polymorphism in Java. They are:

• Compile-Time Polymorphism

• Run-Time Polymorphism

Compile-Time Polymorphism

A typical Java program encounters Compile-Time Polymorphism during the compilation


stage. Here, the overloading method resolution takes place in the compilation stage.
There are two occurrences of Compile-Time Polymorphism, which are:
Method Overloading

Method Overloading is the process in which the class has two or more methods with the
same name. Nevertheless, the implementation of a specific method occurs according to
the number of parameters in the method call.

Example:

//Method Overloading.

package polymorphism;

public class Addition {

public int add(int x, int y) {

return (x + y);

public double add(double d, double e, double f, double g) {

return (d + e + f + g);

public double add(double a, double b) {

return (a + b);

public static void main(String args[]) {

Addition a = new Addition();

System.out.println(a.add(25, 30));

System.out.println(a.add(10.0, 15.0, 20.0, 25.0));


System.out.println(a.add(127.5, 123.5));

//Output:

5555

70.070.0

251.0251.0

Operator Overloading

Method Overloading is a process where a class has two or more methods with the
same name. Still, the implementation of the specific method takes place according to
the number of parameters in the method definition.

Java does not support Operator Overloading to avoid ambiguities.

Run-Time Polymorphism

Run-Time Polymorphism is a procedure where the program execution takes place


during Run-Time. Here, the resolution of an overriding happens in the execution stage.
There are two occurrences of Run-Time Polymorphism.

Method Overriding

Method Overriding is a procedure in which the compiler can allow a child class to
implement a specific method already provided in the parent class.

Example:

//Method Overriding.

package polymorphism;

class CargoPilot {
public void FlyPlane() {

System.out.println("This is the Cargo Pilot, Ready to Take off");

class CivilianPilot extends CargoPilot {

public void FlyPlane() {

System.out.println("This is the Civilian Pilot, Ready to Takeoff");

public class Takeoff {

public static void main(String args[]) {

CargoPilot CPObj = new CargoPilot();

CPObj.FlyPlane();

//CivilianPilot CivilianObj = new CivilianPilot();

//CivilianObj.FlyPlane();

//Output:

This is the Cargo Pilot, Ready to Takeoff


Operator Overriding

Operator Overriding a procedure where you can define an operator in both parent and
child classes with the same signature, but with different operational capability.

Java does not allow Operator Overriding to avoid ambiguities.

Let’s draw up the differences between Compile-Time and Run-Time Polymorphism to


get a better understanding.

Compile-Time Polymorphism vs. Run-Time Polymorphism

Compile-Time Polymorphism Run-Time Polymorphism

• The compiler cannot control the


• The method call is handled by the compiler
method call in run-time

• Run-Time Polymorphism
• Compile-Time Polymorphism is less flexible, as it needs exhibits higher flexibility as the
to handle all method calls in compile-time method calls get handled at run-
time

• The execution period for the Compile-Time Polymorphism • The execution period for the
is less Run-Time Polymorphism is more

• Combining the correct method


• Integrating the right method call with the proper method is
call with the right method is done
done in compile-time
in run-time
• Occurs during Method Overloading and Operator • Occurs during Method
Overloading Overriding

With this, we have understood the differences between the types of Polymorphism in
Java and the working terminology of Run-Time Polymorphism and Compile-Time
Polymorphism.

Since the process of polymorphism deals with extending the methods and members of
the parent class, we need to know how to extend the members and methods,
particularly from the parent class.

In the next part, we will learn about a reference keyword that is used to refer to the
parent class objects. Unlike “this” keyword, the “super” keyword is what we will be
exploring.

Super Keyword

The term "super" is a keyword in Java that refers to the program's immediate parent
class object or method. In this procedure, whenever you create an instance of a
subclass, automatically, the compiler will create an instance of the parent class
implicitly. The super reference variable will be referring to the parent class’ instance.

Example:

//Super Keyword

package polymorphism;

public class SuperKeyWord {

public static void main(String[] args) {

triangle two = new triangle();

two.countsides();
}

class square {

int sides = 4;

class triangle extends square {

int sides = 3;

public void countsides() {

System.out.println("Number of sides in the square : " + sides);

System.out.println("Number of sides in the triangle : " + super.sides);

//Output:

Number of sides in the square: 3

Number of sides in the triangle: 4

Advantages of Polymorphism
• Programmers code can be reused via Polymorphism

• Supports a single variable name for multiple data types

• Reduces coupling between different functionalities

Do you wish to become a Java Developer? Check out the Java Certification Training
Course and get certified today.
Disadvantages of Polymorphism

• Polymorphism ends up raising performance issues in real-time

• Polymorphism reduces the readability of the code

• Programmers find Polymorphism a little challenging to implement


. 29.Write a program to check if a number is prime.
A positive integer which is only divisible by 1 and itself is known as prime
number.

For example: 13 is a prime number because it is only divisible by 1 and 13


but, 15 is not prime number because it is divisible by 1, 3, 5 and 15.

Note: 0 and 1 are not prime numbers.

Example: Check Prime Number

#include <iostream>
using namespace std;

int main() {

int i, n;
bool is_prime = true;

cout << "Enter a positive integer: ";


cin >> n;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
is_prime = false;
}

// loop to check if n is prime


for (i = 2; i <= n/2; ++i) {
if (n % i == 0) {
is_prime = false;
break;
}
}

if (is_prime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";

return 0;
}

Output

Enter a positive integer: 29


29 is a prime number.

This program takes a positive integer from the user and stores it in the
variable n .
Notice that the boolean variable is_prime is initialized to true at the beginning
of the program.
Since 0 and 1 are not prime numbers, we first check if the input number is one
of those numbers or not. If the input number is either 0 or 1, then the value
of is_prime is set to false .

Else, the initial value of is_prime is left unchanged. Then, the for loop is
executed, which checks whether the number entered by the user is perfectly
divisible by i or not.

for (i = 2; i <= n/2; ++i) {


if (n % i == 0) {
is_prime = false;
break;
}
}

The for loop runs from i == 2 to i <= n/2 and increases the value
of i by 1 with each iteration.
The loop terminates at i == n/2 because we cannot find any factor
for n beyond the number n/2 . So, any iteration beyond n/2 is redundant.
If the number entered by the user is perfectly divisible by i , then is_prime is
set to false and the number will not be a prime number.
But if the input number is not perfectly divisible by i throughout the entirety of
the loop, then it means that the input number is only divisible by 1 and that
number itself.
So, the given number is a prime number.

In the cases of n == 2 and n == 3 , the for loop fails to run and the value
of is_prime remains true .

• Heap binary tree


Binary Heap
A Binary Heap is a Binary Tree with following properties.
1) It’s a complete tree (All levels are completely filled except possibly the last level
and the last level has all keys as left as possible). This property of Binary Heap
makes them suitable to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at
root must be minimum among all keys present in Binary Heap. The same property
must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to
MinHeap.
Examples of Min Heap:
10 10
/ \ / \
20 100 15 30
/ / \ / \
30 40 50 100 40
How is Binary Heap represented?
A Binary Heap is a Complete Binary Tree. A binary heap is typically represented as
an array.
• The root element will be at Arr[0].
• Below table shows indexes of other nodes for the ith node, i.e., Arr[i]:
Arr[(i-1)/2] Returns the parent node

Arr[(2*i)+1] Returns the left child node

Arr[(2*i)+2] Returns the right child node

• The traversal method use to achieve Array representation is Level Order

• Please refer Array Representation Of Binary Heap for details.


• Applications of Heaps:
1) Heap Sort: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.
• 2) Priority Queue: Priority queues can be efficiently implemented using Binary
Heap because it supports insert(), delete() and extractmax(), decreaseKey()
operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of
Binary Heap. These variations perform union also efficiently.
• 3) Graph Algorithms: The priority queues are especially used in Graph
Algorithms like Dijkstra’s Shortest Path and Prim’s Minimum Spanning Tree.
• 4) Many problems can be efficiently solved using Heaps. See following for
example.
a) K’th Largest Element in an array.
b) Sort an almost sorted array/
c) Merge K Sorted Arrays.
• Operations on Min Heap:
1) getMini(): It returns the root element of Min Heap. Time Complexity of this
operation is O(1).
• 2) extractMin(): Removes the minimum element from MinHeap. Time
Complexity of this Operation is O(Logn) as this operation needs to maintain the
heap property (by calling heapify()) after removing root.
• 3) decreaseKey(): Decreases value of key. The time complexity of this operation
is O(Logn). If the decreases key value of a node is greater than the parent of the
node, then we don’t need to do anything. Otherwise, we need to traverse up to fix
the violated heap property.
• 4) insert(): Inserting a new key takes O(Logn) time. We add a new key at the end
of the tree. IF new key is greater than its parent, then we don’t need to do
anything. Otherwise, we need to traverse up to fix the violated heap property.
• 5) delete(): Deleting a key also takes O(Logn) time. We replace the key to be
deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the
minus infinite value must reach root, so we call extractMin() to remove the key.
• Below is the implementation of basic heap operations.

• C++
• Python
• C#

// A C++ program to demonstrate common Binary Heap Operations

#include<iostream>

#include<climits>

using namespace std;

// Prototype of a utility function to swap two integers

void swap(int *x, int *y);


// A class for Min Heap

class MinHeap

int *harr; // pointer to array of elements in heap

int capacity; // maximum possible size of min heap

int heap_size; // Current number of elements in min heap

public:

// Constructor

MinHeap(int capacity);

// to heapify a subtree with the root at given index

void MinHeapify(int );

int parent(int i) { return (i-1)/2; }

// to get index of left child of node at index i

int left(int i) { return (2*i + 1); }


// to get index of right child of node at index i

int right(int i) { return (2*i + 2); }

// to extract the root which is the minimum element

int extractMin();

// Decreases key value of key at index i to new_val

void decreaseKey(int i, int new_val);

// Returns the minimum key (key at root) from min heap

int getMin() { return harr[0]; }

// Deletes a key stored at index i

void deleteKey(int i);

// Inserts a new key 'k'

void insertKey(int k);

};
// Constructor: Builds a heap from a given array a[] of given size

MinHeap::MinHeap(int cap)

heap_size = 0;

capacity = cap;

harr = new int[cap];

// Inserts a new key 'k'

void MinHeap::insertKey(int k)

if (heap_size == capacity)

cout << "\nOverflow: Could not insertKey\n";

return;

// First insert the new key at the end

heap_size++;
int i = heap_size - 1;

harr[i] = k;

// Fix the min heap property if it is violated

while (i != 0 && harr[parent(i)] > harr[i])

swap(&harr[i], &harr[parent(i)]);

i = parent(i);

// Decreases value of key at index 'i' to new_val. It is assumed that

// new_val is smaller than harr[i].

void MinHeap::decreaseKey(int i, int new_val)

harr[i] = new_val;

while (i != 0 && harr[parent(i)] > harr[i])

swap(&harr[i], &harr[parent(i)]);
i = parent(i);

// Method to remove minimum element (or root) from min heap

int MinHeap::extractMin()

if (heap_size <= 0)

return INT_MAX;

if (heap_size == 1)

heap_size--;

return harr[0];

// Store the minimum value, and remove it from heap

int root = harr[0];

harr[0] = harr[heap_size-1];

heap_size--;
MinHeapify(0);

return root;

// This function deletes key at index i. It first reduced value to minus

// infinite, then calls extractMin()

void MinHeap::deleteKey(int i)

decreaseKey(i, INT_MIN);

extractMin();

// A recursive method to heapify a subtree with the root at given index

// This method assumes that the subtrees are already heapified

void MinHeap::MinHeapify(int i)

int l = left(i);
int r = right(i);

int smallest = i;

if (l < heap_size && harr[l] < harr[i])

smallest = l;

if (r < heap_size && harr[r] < harr[smallest])

smallest = r;

if (smallest != i)

swap(&harr[i], &harr[smallest]);

MinHeapify(smallest);

// A utility function to swap two elements

void swap(int *x, int *y)

int temp = *x;

*x = *y;

*y = temp;

}
// Driver program to test above functions

int main()

MinHeap h(11);

h.insertKey(3);

h.insertKey(2);

h.deleteKey(1);

h.insertKey(15);

h.insertKey(5);

h.insertKey(4);

h.insertKey(45);

cout << h.extractMin() << " ";

cout << h.getMin() << " ";

h.decreaseKey(2, 1);

cout << h.getMin();

return 0;


Output:
• 2 4 1
• 30.differences between the linked list and array.

Array vs Linked List


Array and Linked list are the two ways of organizing the data in the memory. Before
understanding the differences between the Array and the Linked List, we first look at an
array and a linked list.

What is an array?
An array is a data structure that contains the elements of the same type. A data structure
is a way of organizing the data; an array is a data structure because it sequentially
organizes the data. An array is a big chunk of memory in which memory is divided into
small-small blocks, and each block is capable of storing some value.

Suppose we have created an array that consists of 10 values, then each block will store
the value of an integer type. If we try to store the value in an array of different types, then
it is not a correct array and will throw a compile-time error.

Declaration of array
An array can be declared as:

1. data_type name of the array[no of elements]

To declare an array, we first need to specify the type of the array and then the array's
name. Inside the square brackets, we need to specify the number of elements that our
array should contain.

Let's understand through an example.

1. int a[5];

In the above case, we have declared an array of 5 elements with 'a' name of
an integer data type.

What is Linked list?


A linked list is the collection of nodes that are randomly stored. Each node consists of two
fields, i.e., data and link. Here, data is the value stored at that particular node, and the
link is the pointer that holds the address of the next node.

Differences between Array and Linked list

We cannot say which data structure is better, i.e., array or linked list. There can be a
possibility that one data structure is better for one kind of requirement, while the other
data structure is better for another kind of requirement. There are various factors like what
are the frequent operations performed on the data structure or the size of the data, and
other factors also on which basis the data structure is selected. Now we will see some
differences between the array and the linked list based on some parameters.

1. Cost of accessing an element


In case of an array, irrespective of the size of an array, an array takes a constant time for
accessing an element. In an array, the elements are stored in a contiguous manner, so if
we know the base address of the element, then we can easily get the address of any
element in an array. We need to perform a simple calculation to obtain the address of any
element in an array. So, accessing the element in an array is O(1) in terms of time
complexity.
In the linked list, the elements are not stored in a contiguous manner. It consists of
multiple blocks, and each block is represented as a node. Each node has two fields, i.e.,
one is for the data field, and another one stores the address of the next node. To find any
node in the linked list, we first need to determine the first node known as the head node.
If we have to find the second node in the list, then we need to traverse from the first node,
and in the worst case, to find the last node, we will be traversing all the nodes. The average
case for accessing the element is O(n).

We conclude that the cost of accessing an element in array is less than the linked list.
Therefore, if we have any requirement for accessing the elements, then array is a better
choice.

2. Cost of inserting an element


There can be three scenarios in the insertion:

o Inserting the element at the beginning: To insert the new element at the beginning, we
first need to shift the element towards the right to create a space in the first position. So,
the time complexity will be proportional to the size of the list. If n is the size of the array,
the time complexity would be O(n).
In the case of a linked list, to insert an element at the starting of the linked list, we will
create a new node, and the address of the first node is added to the new node. In this
way, the new node becomes the first node. So, the time complexity is not proportional to
the size of the list. The time complexity would be constant, i.e., O(1).

o Inserting an element at the end

If the array is not full, then we can directly add the new element through the index. In this
case, the time complexity would be constant, i.e., O(1). If the array is full, we first need to
copy the array into another array and add a new element. In this case, the time complexity
would be O(n).

To insert an element at the end of the linked list, we have to traverse the whole list. If the
linked list consists of n elements, then the time complexity would be O(n).

o Inserting an element at the mid


Suppose we want to insert the element at the ith position of the array; we need to shift the
n/2 elements towards the right. Therefore, the time complexity is proportional to the
number of the elements. The time complexity would be O(n) for the average case.

In the case of linked list, we have to traverse to that position where we have to insert the
new element. Even though, we do not have to perform any kind of shifting, but we have
to traverse to n/2 position. The time taken is proportional to the n number of elements,
and the time complexity for the average case would be O(n).

The resultant linked list is:


o Ease of use

The implementation of an array is easy as compared to the linked list. While creating a
program using a linked list, the program is more prone to errors like segmentation fault
or memory leak. So, lots of care need to be taken while creating a program in the linked
list.

o Dynamic in size

The linked list is dynamic in size whereas the array is static. Here, static doesn't mean that
we cannot decide the size at the run time, but we cannot change it once the size is
decided.

3. Memory requirements
As the elements in an array store in one contiguous block of memory, so array is of fixed
size. Suppose we have an array of size 7, and the array consists of 4 elements then the
rest of the space is unused. The memory occupied by the 7 elements:

Memory space = 7*4 = 28 bytes


Where 7 is the number of elements in an array and 4 is the number of bytes of an integer
type.

In case of linked list, there is no unused memory but the extra memory is occupied by the
pointer variables. If the data is of integer type, then total memory occupied by one node
is 8 bytes, i.e., 4 bytes for data and 4 bytes for pointer variable. If the linked list consists
of 4 elements, then the memory space occupied by the linked list would be:

Memory space = 8*4 = 32 bytes

The linked list would be a better choice if the data part is larger in size. Suppose the data
is of 16 bytes. The memory space occupied by the array would be 16*7=112 bytes while
the linked list occupies 20*4=80, here we have specified 20 bytes as 16 bytes for the size
of the data plus 4 bytes for the pointer variable. If we are choosing the larger size of data,
then the linked list would consume a less memory; otherwise, it depends on the factors
that we are adopting to determine the size.

Let's look at the differences between the array and linked list in a tabular form.

Array Linked list

An array is a collection of elements of a similar A linked list is a collection of objects known as a


data type. node where node consists of two parts, i.e., data
and address.

Array elements store in a contiguous memory Linked list elements can be stored anywhere in the
location. memory or randomly stored.

Array works with a static memory. Here static The Linked list works with dynamic memory. Here,
memory means that the memory size is fixed and dynamic memory means that the memory size can
cannot be changed at the run time. be changed at the run time according to our
requirements.

Array elements are independent of each other. Linked list elements are dependent on each other.
As each node contains the address of the next
node so to access the next node, we need to
access its previous node.
Array takes more time while performing any Linked list takes less time while performing any
operation like insertion, deletion, etc. operation like insertion, deletion, etc.

Accessing any element in an array is faster as the Accessing an element in a linked list is slower as it
element in an array can be directly accessed starts traversing from the first element of the
through the index. linked list.

In the case of an array, memory is allocated at In the case of a linked list, memory is allocated at
compile-time. run time.

Memory utilization is inefficient in the array. For Memory utilization is efficient in the case of a
example, if the size of the array is 6, and array linked list as the memory can be allocated or
consists of 3 elements only then the rest of the deallocated at the run time according to our
space will be unused. requirement.

. 31.Explain the concept of inheritance.various types of


inheritance.

Different Types of Inheritance


Inheritance is the process of creating a new Class, called the Derived
Class , from the existing class, called the Base Class . The Inheritance
has many advantages, the most important of them being the reusability of
code. Rather than developing new Objects from scratch, new code can be
based on the work of other developers, adding only the new features that
are needed. The reuse of existing classes saves time and effort.

However, inheritance may be implemented in different combinations


in Object-Oriented Programming languages as illustrated in figure and
they include:

 Single Inheritance
 Multi Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
 Multipath inheritance
 Multiple Inheritance

Single Inheritance

When a Derived Class to inherit properties and behavior from a


single Base Class , it is called as single inheritance.

Multi Level Inheritance


A derived class is created from another derived class is called Multi
Level Inheritance .

Hierarchical Inheritance

More than one derived classes are created from a single base class, is
called Hierarchical Inheritance .

Hybrid Inheritance
Any combination of above three inheritance (single, hierarchical and
multi level) is called as hybrid inheritance .

Multipath inheritance

Multiple inheritance is a method of inheritance in which one derived


class can inherit properties of base class in different paths. This
inheritance is not supported in .NET Languages such as C#.

Multiple Inheritance
Multiple inheritances allows programmers to create classes that combine
aspects of multiple classes and their corresponding hierarchies. In .Net
Framework, the classes are only allowed to inherit from a single parent
class, which is called single inheritance. More about.... Why in .NET
multiple inheritance is not allowed

Different types of inheritance in C#


 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance (Through Interface)
 Hybrid Inheritance (Through Interface)

Multiple inheritance and Hybrid Inheritance are not supported in C#


through class.

Different types of inheritance in c++


In C++ programming language , inheritance is a process in which one
object acquires all the properties and behaviours of its parent object
automatically. It allows user to create a Child Class (Derived Class) from
an existing Parent Class (Base Class). To inherit from a class, C++ use
the : symbol. C++ supports five types of inheritance:

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Different types of inheritance in Java


Object-Oriented Programming or better known as OOPs is one of
the major pillars of Java that has leveraged its power and ease of usage.
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality. Java supports five types of inheritance:

 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance (Through Interface)
 Hybrid Inheritance (Through Interface)

Multiple inheritance and Hybrid Inheritance are not supported in Java


through class.

Different types of inheritance in Python


Python Inheritance allows you to define a class that inherits all the
methods and properties from another class. Like C++, a class can
be derived from more than one base classes in Python. This is called
multiple inheritance. Python supports five types of inheritance:

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
32. How is exception handling done in C++ and Java?
There are key differences in Exception Handling in C++ vs Java

Exception handling in java Exception handling in C++

Only throwable objects can be thrown as All types can be thrown as exception
objects.

In java, finally is a block that is executed after try In C++ there is no existence of finally block
catch block for cleaning up.

A new keyword throws is used to list exceptions Throw keyword is used to list exceptions
thrown by a function. thrown by a function.

Both checked and unchecked exceptions are Only unchecked exceptions are present.
present.

. 33. What is the difference between Array and ArrayList?

Array vs ArrayList in Java


Array is a fixed length data structure whereas ArrayList is a variable length Collection class.
We cannot change length of array once created in Java but ArrayList can be changed.

We cannot store primitives in ArrayList, it can only store objects. But array can contain
both primitives and objects in Java. Since Java 5, primitives are automatically converted in
objects which is known as auto-boxing.

The following table describes the key differences between array and ArrayList:
Basis Array ArrayList

Definition An array is a dynamically-created object. It serves The ArrayList is a class of


as a container that holds the constant number of Java Collections framework. It contains
values of the same type. It has a contiguous popular classes like Vector, HashTable,
memory location. and HashMap.

Static/ Array is static in size. ArrayList is dynamic in size.


Dynamic

Resizable An array is a fixed-length data structure. ArrayList is a variable-length data


structure. It can be resized itself when
needed.

Initialization It is mandatory to provide the size of an array while We can create an instance of ArrayList
initializing it directly or indirectly. without specifying its size. Java creates
ArrayList of default size.

Performance It performs fast in comparison to ArrayList ArrayList is internally backed by the


because of fixed size. array in Java. The resize operation in
ArrayList slows down the performance.

Primitive/ An array can store We cannot store primitive type in


Generic type both objects and primitives type. ArrayList. It automatically converts
primitive type to object.

Iterating We use for loop or for each loop to iterate over We use an iterator to iterate over
Values an array. ArrayList.

Type-Safety We cannot use generics along with array because ArrayList allows us to store
it is not a convertible type of array. only generic/ type, that's why it is
type-safe.

Length Array provides a length variable which denotes ArrayList provides the size() method to
the length of an array. determine the size of ArrayList.

Adding We can add elements in an array by using Java provides the add() method to add
Elements the assignment operator. elements in the ArrayList.

Single/ Multi- Array can be multi-dimensional. ArrayList is always single-dimensional.


Dimensional
34.write a program to swap two numbers?

C++ Program to Swap Two Numbers


This example contains two different techniques to swap numbers in C
programming. The first program uses temporary variable to swap numbers,
whereas the second program doesn't use temporary variables.

Example 1: Swap Numbers (Using Temporary


Variable)

#include <iostream>
using namespace std;

int main()
{
int a = 5, b = 10, temp;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

temp = a;
a = b;
b = temp;

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

return 0;
}

Output

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5

To perform swapping in above example, three variables are used.

The contents of the first variable is copied into the temp variable. Then, the
contents of second variable is copied to the first variable.

Finally, the contents of the temp variable is copied back to the second variable
which completes the swapping process.

You can also perform swapping using only two variables as below.

Example 2: Swap Numbers Without Using Temporary


Variables

#include <iostream>
using namespace std;

int main()
{

int a = 5, b = 10;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

a = a + b;
b = a - b;
a = a - b;

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

return 0;
}

The output of this program is the same as the first program above.

Let us see how this program works:

1. Initially, a = 5 and b = 10 .

2. Then, we add a and b and store it in a with the code a = a + b. This means a =

5 + 10 . So, a = 15 now.
3. Then we use the code b = a - b. This means b = 15 - 10 . So, b = 5 now.
4. Again, we use the code a = a - b. This means a = 15 - 5 . So finally, a = 10 .

Hence, the numbers have been swapped.

Note: We can use multiplication and division instead of addition and


subtraction. However, this won't work if one of the numbers is 0.

int a = 5, b = 10;

// using multiplication and division for swapping


a = a * b; // a = 50
b = a / b; // b = 5
a = a / b; // a = 10

35. What are the different types of loops in Java?

Java Loops – A Complete


Guide for Beginners!
Have you ever forgot to do your homework and as a punishment you were
asked to write “I will do my homework on time.” for at least 40-50 times? It was
boring as well as time-consuming, right? Well, Java Loops works exactly the
same.
Loops in programming allow a set of instructions to be executed repeatedly
until a certain condition is fulfilled. Loops are also known as iterating
statements or looping statements. In this article, we will learn about the
various loops in Java.

Need for Loops in Java


While programming, sometimes, there occurs a situation when we need to
execute a block of code several numbers of times. In general, these statements
execute in a sequential manner: The first statement in a function executes
first, followed by the second, and so on.

But this makes the process very complicated as well as lengthy and therefore
time-consuming. Therefore, programming languages provide various control
structures that allow for such complex execution statements.

Before moving towards the types of loops, we will first discuss the general
syntax of a loop with the help of elements that control a loop.

Java Loops
In Java, there are three kinds of loops which are – the for loop, the while loop,
and the do-while loop. All these three loop constructs of Java executes a set of
repeated statements as long as a specified condition remains true.
This particular condition is generally known as loop control. For all three loop
statements, a true condition is the one that returns a boolean true value and
the false condition is the one that returns the boolean false value.

Elements in a Java Loop


Every loop has its elements or variables that govern its execution. Generally, a
loop has four elements that have different purposes which are:
• Initialization Expression(s)
• Test Expression(Condition)
• Update Expression(s)
• Body of the loop
We will discuss each of the above elements for a better understanding of the
working of the loops.

1. Initialization Expression(s)
Before entering into a loop, we must initialize its control variable. The
initialization of the control variable takes place under initialization expression.
It initializes the loop variable(s) with their first value. The initialization
expression gets executed only once at the beginning of the loop.

2. Test Expression
The test expression is an expression whose truth (boolean) value decides
whether the loop body will be executed or not. The execution or termination of
the loop depends on the test expression which is also called the exit condition
or test condition.

If the test expression evaluates to true that is, 1, the loop body is executed,
otherwise, the loop is terminated.

In an entry-controlled loop, the test expression is evaluated before entering


into a loop whereas, in the exit-controlled loop, the test expression is
evaluated before exiting from the loop. In Java, the for loop and while loop
are entry-controlled loops, and do-while loop is an exit-controlled loop.
3. Update Expression(s)
The update expression(s) changes the values of the loop variables. The update
expression is executed at the end of the loop after the loop body gets executed.
For example, an update expression may be increment or decrement
statements.
4. The Body of the Loop
The statements which execute repeatedly (as long as the test expression is non
zero) form the body of the loop. The code inside the loop body will be executed
or not, depends on the value of the test expression.

If the value evaluates to be true then the loop body gets repeatedly executed,
otherwise, it gets terminated.

Following diagram explains an Iteration or a loop construct:

Types of Loops in Java


1. The for Loop
The for loop in Java is an entry controlled loop that allows a user to execute a
block of a statement(s) repeatedly with a fixed number of times on the basis of
the test expression or test-condition. This is the easiest to understand Java
loops.
All its loop-control elements are gathered at one place, on the top of the loop
within the round brackets(), while in the other loop constructions of Java, the
loop elements are scattered about the program.

The syntax or general form of for loop is:


for(initialization expression(s) ; test-expression ; update-expression(s))

body of the loop ;

For Example:
int x = 0;

for( x = 1 ; x <= 10 ; x++ )

System.out.println(Value of x: “ +x);

Code Snippet to illustrate the use of for statement/loop:


package com.TechVidvan.loopsDemo;

public class ForLoopDemo

public static void main(String args[])

int i;

for(i = 10; i >= 1; i--)

System.out.println("The value of i is: "+i);

}
}

Output:
The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2
The value of i is: 1

The following figure outlines the working of a for loop:


Now that you are familiar with the working of a for loop, let us take another
example where there are multiple statements in the loop body:
Code:
package com.TechVidvan.loopsDemo;

public class ForLoopDemo

public static void main(String args[])

int i,sum;
for(i = 1 , sum = 0; i <= 10; ++i)

System.out.println("The value of i is: "+i) ;

sum = sum + i;

System.out.println("The sum of first 10 numbers is: " +sum) ;

Output:
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
The value of i is: 6
The value of i is: 7
The value of i is: 8
The value of i is: 9
The value of i is: 10
The sum of first 10 numbers is: 55

In the above program, there are 2 initialization expressions: i = 1 and sum = 0


separated by comma. The initialization part may contain as many expressions
but these should be separated by commas. The initialization part must be
followed by a semicolon(;). Both the variables i and sum get their first values 1
and 0 respectively.
Tip: Use for loop when you have to repeat a block of statements a specific
number of times.
The for loop Variations
Java offers several variations in the loop that increases the flexibility and
applicability of for loop. The different variations of for loop are discussed
below:
1.1. Multiple Initializations and Update Expressions
A for loop may contain multiple initializations and/or update expressions.
These multiple expressions must be separated by commas. We have already
seen an example of multiple initialization expressions in the previous
program.

The for loop of that program can be alternatively written as follows:

for( i = 1, sum = 0 ; i <= 10 ; sum +=i, ++i )

System.out.println(i);

The above code contains two initialization expressions i = 1 and sum = 0 and
two update expressions sum += i and ++i. These multiple expressions are
executed in sequence.
Tip: The comma operator in a for loop is essential whenever we need more
than one index.
1.2. Optional Expressions
In a for loop, initialization expressions, test expressions and, update
expressions are optional that is, you can skip any or all of these expressions.

Say, for example, you have already initialized the loop variables and you want
to scrape off the initialization expression then you can write for loop as
follows:

for( ; test-expression ; update-expression(s))


loop-body

See, even if you skip the initialization expression, the semicolon (;) must be
following it.

Following code fragment illustrates the above concept:

package com.TechVidvan.loopsDemo;

public class ForLoopDemo

public static void main(String args[])


{

int i = 1, sum = 0 ;

for( ; i <= 10 ; sum +=i, ++i )

System.out.println(i);

System.out.println("The sum of first 10 numbers is: " +sum) ;

Output:
1
2
3
4
5
6
7
8
9
10
The sum of first 10 numbers is: 55

Similarly, we can also skip or omit the test expressions and update
expressions.

For example,
for( j = 0 ; j != 224 ; )

j += 11 ;

If the variable j has already been initialized, then we can write the above loop
as,

for( ; j != 224 ; )

j += 11;

Tip: The loop-control expressions in a for loop statement are optional, but
semicolons must be written.
1.3. Infinite Loop
An infinite loop can be created by skipping the test-expression as shown
below:

package com.TechVidvan.loopsDemo;

public class ForLoopDemo

public static void main(String args[])

int x;

for( x = 25 ; ; x-- )

System.out.println(“This is an infinite loop”);

Output:
This is an infinite loop…

Similarly, we can also skip all three expressions to create an infinite loop:

for( ; ; ; )

loop body

1.4. Empty Loop


When there is no statement in the loop-body of the loop, then it is called an
empty loop. In such cases, a Java loop contains an empty statement that is, a
null statement. Following for loop is an example of an empty loop:

for( j = 20 ; j >=0 ; j– ) ; //See,the loop body contains a null statement


An empty for loop has its applications in the time delay loop where you need
to increment or decrement the value of some variable without doing anything
else, just for introducing some delay.

1.5. Declaration of variables inside loops


When we declare any variable inside for loop, we can not access the variable
after the loop statement is over. The reason is that as the variable is declared
within a block of statement its scope becomes the body of the loop. Therefore,
we can’t access it outside the loop body.

Following code explains this concept:

package com.TechVidvan.loopsDemo;

public class ForLoopDemo

public static void main(String args[])

for(int x = 25 ; x>=0; x -= 5)

System.out.println("Inside the loop");

System.out.println(x); //Accessing x after the loop body gives an error

Output:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
x cannot be resolved to a variable
at project1/com.TechVidvan.loopsDemo.ForLoopDemo.main(ForLoopDemo.java:11)

In the above program, the statement System.out.println(x); is invalid as the scope of


x is over. A variable is not accessible outside its scope, that’s why there is an error.
2. The while Loop
The next loop available in Java is the while loop. The while loop is an entry-
controlled loop.

The syntax or general form of while loop is:


while(test-expression)
loop-body

In a while loop, the loop-body may contain a single, compound or an empty


statement. The loop repeats while the test expression or condition evaluates to
true. When the expression becomes false, the program control passes to the
line just after the end of the loop-body code.

In a while loop, a loop variable must be initialized before the loop begins. And
the loop variable should be updated inside the while loop’s body.

Following code shows the working of a while loop:

Code Snippet to illustrate while loop:


//program to calculate the factorial of a number

package com.TechVidvan.loopsDemo;

public class WhileLoopDemo

public static void main(String args[])

long i = 0, fact = 1, num = 5 ;

i = num ;

while(num != 0)

fact = fact * num;

--num;

System.out.println("The factorial of " + i + " is: " +fact);

Output:
The factorial of 5 is: 120
In the above code, as long as the value of num is non-zero, the loop body gets
iterated that is, the variable. Each time the value of fact gets updated when it is
multiplied with num, then the next operation is the decrement in value of
num.

And after that, again the test-expression (num) is executed. If it is false, the
loop is terminated otherwise repeated.

The following figure outlines the working of a while loop:

The while loop Variations


A while loop also has several variations. We will discuss each of these
variations:

2.1. Empty while Loop


An empty while loop does not contain any statement in its body. It just
contains a null statement which is denoted by a semicolon after the while
statement:
:

long wait = 0;

while( ++wait < 10000)

; //null statement

The above code is a time delay loop. The time delay loop is useful for pausing
the program for some time. For instance, if an important message flashes on
the screen and before you can read it, it goes off.

So, here you can introduce a time delay loop so that you get sufficient time to
read the message.

2.2. Infinite while Loop


A while loop can be an infinite loop if you skip writing the update statement
inside its body. For example, the following code is an example of an infinite
while loop:

package loopsDemo;

public class WhileLoopDemo

public static void main(String args[])

int j = 0;

while(j <= 10)

System.out.println( j * j);

j++;

//writing the update expression outside the loop body makes an infinite loop

}
}

Output:
0
0 …

The above loop is an infinite loop as the increment statement j++ is not
included inside the loop’s body. The value of j remains the same (that is, 0)
and the loop can never terminate.

We can also write boolean value true inside the while statement to make an
infinite while loop. As condition will always be true, the loop body will get
executed infinitely. It is shown below:

while(true)

System.out.println(“This is an infinite loop”);

3. The do-while Loop


Unlike the for and while loops, the do-while loop is an exit-controlled loop
which means a do-while loop evaluates its test-expression or test-condition at
the bottom of the loop after executing the statements in the loop-body.

This means the do-while loop always executes at least once !!

Need for do-while loop:


In the for and while loops, the condition is evaluated before executing the
loop-body. The loop body never executes if the test expression evaluates to
false for the first time itself.
But in some situations, we want the loop-body to execute at least once, no
matter what is the initial state of the test-expression. In such cases, the do-
while loop is the best option.
The syntax or general form of do-while loop is:
do

statement(s);
} while(test-expression) ;

The braces { } are not necessary when the loop-body contains a single
statement.
Following code shows the working of a do-while loop:

Code Snippet to illustrate the do-while loop:


//program to print all upper case letters

package com.TechVidvan.loopsDemo;

public class DoWhileLoopDemo

public static void main(String args[])

char ch = 'A' ;

do

System.out.println( ch + " " );

ch++;

} while(ch <= 'Z');

Output:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The above code print characters from ‘A’ onwards until the condition ch<= ‘Z’
becomes false.

The following figure outlines the working of a do-while loop:


The do-while loop is most commonly used in the menu selection systems, in
which the user can see the menu at least once. Then according to the user’s
response, it is either repeated or terminated.

Nested Loops in Java


When a loop contains another loop in its body than it is called a nested loop.
But in a nested loop, the inner loop must terminate before the outer loop. The
following is an example of “nested” for loop:

Code to illustrate nested for loop:


package com.TechVidvan.loopsDemo;

public class NestedLoopDemo

public static void main(String args[])

{
int i, j;

for( i = 1 ; i <= 5 ; ++i)

{ //outer loop

System.out.println();

for( j = 1 ; j <= i ; ++j) //inner loop

System.out.println( "* " );

Output:
*
* *
* * *
* * * *
* * * * *

Summary
The Loops in Java helps a programmer to save time and effort. Repetition of
statements causes a delay in time. So, loops help us to do the tasks in an easy
and efficient manner. In this article, we discussed the three types of loops: for,
while and do-while loop.

• What is DBMS?

What is Database
The database is a collection of inter-related data which is used to retrieve, insert and
delete the data efficiently. It is also used to organize the data in the form of a table,
schema, views, and reports, etc.

For example: The college Database organizes the data about the admin, staff, students
and faculty etc.
Using the database, you can easily retrieve, insert, and delete the information.

Database Management System


o Database management system is a software which is used to manage the database. For
example: MySQL, Oracle, etc are a very popular commercial database which is used in
different applications.
o DBMS provides an interface to perform various operations like database creation, storing
data in it, updating data, creating a table in the database and a lot more.
o It provides protection and security to the database. In the case of multiple users, it also
maintains data consistency.

DBMS allows users the following tasks:

o Data Definition: It is used for creation, modification, and removal of definition that
defines the organization of data in the database.
o Data Updation: It is used for the insertion, modification, and deletion of the actual data
in the database.
o Data Retrieval: It is used to retrieve the data from the database which can be used by
applications for various purposes.
o User Administration: It is used for registering and monitoring users, maintain data
integrity, enforcing data security, dealing with concurrency control, monitoring
performance and recovering information corrupted by unexpected failure.

Characteristics of DBMS
o It uses a digital repository established on a server to store and manage the information.
o It can provide a clear and logical view of the process that manipulates data.
o DBMS contains automatic backup and recovery procedures.
o It contains ACID properties which maintain data in a healthy state in case of failure.
o It can reduce the complex relationship between data.
o It is used to support manipulation and processing of data.
o It is used to provide security of data.
o It can view the database from different viewpoints according to the requirements of the
user.

Advantages of DBMS
o Controls database redundancy: It can control data redundancy because it stores all the
data in one single database file and that recorded data is placed in the database.
o Data sharing: In DBMS, the authorized users of an organization can share the data among
multiple users.
o Easily Maintenance: It can be easily maintainable due to the centralized nature of the
database system.
o Reduce time: It reduces development time and maintenance need.
o Backup: It provides backup and recovery subsystems which create automatic backup of
data from hardware and software failures and restores the data if required.
o multiple user interface: It provides different types of user interfaces like graphical user
interfaces, application program interfaces

Disadvantages of DBMS
o Cost of Hardware and Software: It requires a high speed of data processor and large
memory size to run DBMS software.
o Size: It occupies a large space of disks and large memory to run them efficiently.
o Complexity: Database system creates additional complexity and requirements.
o Higher impact of failure: Failure is highly impacted the database because in most of the
organization, all the data stored in a single database and if the database is damaged due
to electric failure or database corruption then the data may be lost forever.

36.What is RDBMS?

What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for
SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle,
MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by E. F. Codd.

What is a table?
The data in an RDBMS is stored in database objects which are called as tables. This
table is basically a collection of related data entries and it consists of numerous columns
and rows.
Remember, a table is the most common and simplest form of data storage in a relational
database. The following program is an example of a CUSTOMERS table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

What is a field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS
table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every
record in the table.

What is a Record or a Row?


A record is also called as a row of data is each individual entry that exists in a table. For
example, there are 7 records in the above CUSTOMERS table. Following is a single row
of data or record in the CUSTOMERS table −
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

A record is a horizontal entity in a table.


What is a column?
A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents
location description and would be as shown below −
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+

What is a NULL value?


A NULL value in a table is a value in a field that appears to be blank, which means a
field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a
field that contains spaces. A field with a NULL value is the one that has been left blank
during a record creation.

SQL Constraints
Constraints are the rules enforced on data columns on a table. These are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the database.
Constraints can either be column level or table level. Column level constraints are
applied only to one column whereas, table level constraints are applied to the entire
table.
Following are some of the most commonly used constraints available in SQL −
• NOT NULL Constraint − Ensures that a column cannot have a NULL value.
• DEFAULT Constraint − Provides a default value for a column when none is
specified.
• UNIQUE Constraint − Ensures that all the values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database table.
• FOREIGN Key − Uniquely identifies a row/record in any another database table.
• CHECK Constraint − The CHECK constraint ensures that all values in a column
satisfy certain conditions.
• INDEX − Used to create and retrieve data from the database very quickly.

Data Integrity
The following categories of data integrity exist with each RDBMS −
• Entity Integrity − There are no duplicate rows in a table.
• Domain Integrity − Enforces valid entries for a given column by restricting the
type, the format, or the range of values.
• Referential integrity − Rows cannot be deleted, which are used by other records.
• User-Defined Integrity − Enforces some specific business rules that do not fall
into entity, domain or referential integrity.

Database Normalization
Database normalization is the process of efficiently organizing data in a database. There
are two reasons of this normalization process −
• Eliminating redundant data, for example, storing the same data in more than one
table.
• Ensuring data dependencies make sense.
Both these reasons are worthy goals as they reduce the amount of space a database
consumes and ensures that data is logically stored. Normalization consists of a series of
guidelines that help guide you in creating a good database structure.
Normalization guidelines are divided into normal forms; think of a form as the format or
the way a database structure is laid out. The aim of normal forms is to organize the
database structure, so that it complies with the rules of first normal form, then second
normal form and finally the third normal form.
It is your choice to take it further and go to the fourth normal form, fifth normal form and
so on, but in general, the third normal form is more than enough.

• First Normal Form (1NF)


• Second Normal Form (2NF)
• Third Normal Form (3NF)
• Difference between DBMS and RDBMS?
The main differences between DBMS and RDBMS are given below:

No. DBMS RDBMS

1) DBMS applications store data as file. RDBMS applications store data in a tabular form.

2) In DBMS, data is generally stored in In RDBMS, the tables have an identifier called primary key
either a hierarchical form or a and the data values are stored in the form of tables.
navigational form.

3) Normalization is not present in DBMS. Normalization is present in RDBMS.

4) DBMS does not apply any RDBMS defines the integrity constraint for the purpose
security with regards to data of ACID (Atomocity, Consistency, Isolation and Durability)
manipulation. property.

5) DBMS uses file system to store data, so in RDBMS, data values are stored in the form of tables, so
there will be no relation between the a relationship between these data values will be stored in
tables. the form of a table as well.

6) DBMS has to provide some uniform RDBMS system supports a tabular structure of the data and
methods to access the stored a relationship between them to access the stored
information. information.

7) DBMS does not support distributed RDBMS supports distributed database.


database.

8) DBMS is meant to be for small RDBMS is designed to handle large amount of data. it
organization and deal with small data. supports multiple users.
it supports single user.

9) Examples of DBMS are file Example of RDBMS are mysql, postgre, sql
systems, xml etc. server, oracle etc.

After observing the differences between DBMS and RDBMS, you can say that RDBMS is
an extension of DBMS. There are many software products in the market today who are
compatible for both DBMS and RDBMS. Means today a RDBMS application is DBMS
application and vice-versa.

You might also like