IT Interview Questions
IT Interview Questions
IT Interview Questions
What is OOP?
1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction
1. Polymorphism
Polymorphism is the ability to exit in many forms.
2. Inheritance
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.
4. Abstraction
class person
char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
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.
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.
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.
There are some basic concepts that act as the building blocks of OOPs.
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• 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
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.
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.
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.
Advantages of OOPs
• 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.
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.
• 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.
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.
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.
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.
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.
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.
• 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.
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.
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.
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.
• 5.What is BigData
Ans: https://www.oracle.com/in/big-data/what-is-big-data/
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"
the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);
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
#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
}
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) {
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 () {
return 0;
}
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 −
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.
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
int main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, 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];
}
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>
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;
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;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
}
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
while( i < 5 ):
if( max < set[i] ):
max = set[i]
i = i + 1
return max
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.
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.
Let's look at the situations where we need to use the null pointer.
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.
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.
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
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
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;
if(i == j)
if(ii == jj)
return 0;
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()
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;
• C++
• C
#include <iostream>
using namespace std;
int main()
int arr[10];
// to 5.
arr[0] = 5;
// as 5.
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'};
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.
int arr1[10];
int n = 10;
int arr2[n];
// elements
#include <stdio.h>
int main()
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3] = arr[0];
printf("%d %d %d %d", arr[0],
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++
// is not checked in C.
#include <stdio.h>
int main()
int arr[2];
printf("%d ", arr[3]);
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()
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]'”.
// contiguous locations
#include <stdio.h>
int main()
// an array of 10 integers.
// If arr[0] is stored at
// stored at x + sizeof(int)
// arr[2] is stored at x +
// sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;
sizeof(int));
// 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>
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
for(int i=0;i<6;i++)
cout<<i[arr]<<" ";
cout<<endl;
return 0;
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
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[];
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.
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
class GFG
int[] arr;
// allocating memory for 5 integers.
arr[0] = 10;
arr[1] = 20;
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
}
}
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
this.roll_no = roll_no;
this.name = name;
{
// declares an Array of integers.
Student[] arr;
// so on...
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
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
{
// declaring and initializing 2D array
// printing 2D array
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
// Driver method
sum(arr);
int sum = 0;
sum+=arr[i];
Output
sum of array values : 15
As usual, a method can also return an array. For example, the below program
returns an array from method m1.
• Java
class Test
// Driver method
System.out.print(arr[i]+" ");
// returning array
return new int[]{1,2,3};
Output
1 2 3
Every array has an associated Class object, shared with all other arrays with the
same component type.
• Java
class Test
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.
Object Type Arrays Either declared type objects or it’s child class objects.
Cloning of arrays
• Java
// Java program to demonstrate
class Test
System.out.println(intArray == cloneArray);
System.out.print(cloneArray[i]+" ");
}
}
Output
false
1 2 3
• Java
class Test
System.out.println(intArray == cloneArray);
System.out.println(intArray[0] == cloneArray[0]);
System.out.println(intArray[1] == cloneArray[1]);
}
}
Output
false
true
true
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.
However, when the complexity of the program increases, the linear data
structures might not be the best choice because of operational complexities.
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.
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 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.
A
linked list
Non-linear data structures are further divided into graph and tree based data
structures.
In graph data structure, each node is called vertex and each vertex is
connected to other vertices through edges.
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.
The time complexity increase with the data size. Time complexity remains the same.
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 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.
Initialize fact = 1
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.
Initialize sum = 0
add n to sum
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?
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 +
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
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
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. :)
More on Scalability
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.
Memory is expensive
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.
Imagine you are writing a program to find the solution of a Rubik's cube.
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.
A typical DNA strand has millions of such units. Eh! worry not. KMP
algorithm can get this done in time which is proportional to
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.
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
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.
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.
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.
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.
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
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.
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
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.
#include <iostream>
// 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);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
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>
protected:
int width;
int height;
};
// 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();
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);
}
};
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
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.
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
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
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.
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.
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");
}
}
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 {
return a + b;
return a + b + c;
System.out.println(add(4, 6));
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("eating.");
void eat()
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
d1.eat();
a1.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.
Class Interface
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
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.
. 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
WHERE [condition];
Or,
SELECT [column1, column2, ....]
FROM table1
WHERE [condition];
Diagrammatic Representation :
WHERE [condition];
Diagrammatic Representation :
Example:
Consider following employee table,
EMPID ENAME EMPDEPT SALARY
101 Amanda Development 50000
Department Table :
DEPTID DEPTNAME LOCATION
10 Development New York
12 Testing Washington
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
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
• C
• C++
#include <stdio.h>
void geeks()
int *ptr;
ptr = &var;
// 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
#include <bits/stdc++.h>
//Pass-by-Value
int square1(int n)
n *= n;
return n;
*n *= *n;
n *= n;
void geeks()
{
//Call-by-Value
int n1=8;
int n2=8;
square2(&n2);
int n3=8;
square3(n3);
//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++
#include <stdio.h>
void geeks()
//Declare an array
int *ptr;
//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>
void geeks()
//Declare an array
int *ptr;
ptr = v;
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
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.
#include <bits/stdc++.h>
if(ptrsize == sizeof(char))
char *ptrchar;
ptrchar = (char*)data;
//Increase the char stored at *ptrchar by 1
(*ptrchar)++;
int *ptrint;
ptrint = (int*)data;
(*ptrint)++;
void geek()
// Declare a character
char c='x';
// Declare an integer
int i=10;
increase(&c,sizeof(c));
increase(&i,sizeof(i));
//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.
For example, if you want to store the address of a person or house then you
should use ‘string’ data type.
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.
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:-
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.
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>
int main()
Output:-
First number is: 2
Last number is: 4
// Node Initializing!
// Allocating memory!
ONE->data = 23;
TWO->data = 34;
THREE->data = 90;
ONE->next = TWO;
TWO->next = THREE;
THREE->next = NULL;
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.
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;
struct Tech{
int a = 0;
int b = 1;
};
int main()
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
#include <string.h>
struct info {
char student_name[50];
char favorite_subject[20];
int id;
};
int main() {
struct info s1;
s1.id = 20;
display(s1);
return 0;
Output:-
Name of first student: Tom Sawer
Favourite subject of first student: English
ID of first student: 20
Types of Polymorphism
• Compile-Time Polymorphism
• Run-Time Polymorphism
Compile-Time Polymorphism
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;
return (x + y);
return (d + e + f + g);
return (a + b);
System.out.println(a.add(25, 30));
//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.
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() {
CPObj.FlyPlane();
//CivilianObj.FlyPlane();
//Output:
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.
• 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
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;
two.countsides();
}
class square {
int sides = 4;
int sides = 3;
//Output:
Advantages of Polymorphism
• Programmers code can be reused via Polymorphism
Do you wish to become a Java Developer? Check out the Java Certification Training
Course and get certified today.
Disadvantages of Polymorphism
#include <iostream>
using namespace std;
int main() {
int i, n;
bool is_prime = true;
if (is_prime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";
return 0;
}
Output
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.
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 .
• C++
• Python
• C#
#include<iostream>
#include<climits>
class MinHeap
public:
// Constructor
MinHeap(int capacity);
void MinHeapify(int );
int extractMin();
};
// Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(int cap)
heap_size = 0;
capacity = cap;
void MinHeap::insertKey(int k)
if (heap_size == capacity)
return;
heap_size++;
int i = heap_size - 1;
harr[i] = k;
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
harr[i] = new_val;
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
int MinHeap::extractMin()
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
heap_size--;
return harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
void MinHeap::deleteKey(int i)
decreaseKey(i, INT_MIN);
extractMin();
void MinHeap::MinHeapify(int i)
int l = left(i);
int r = right(i);
int smallest = i;
smallest = l;
smallest = r;
if (smallest != i)
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
*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);
h.decreaseKey(2, 1);
return 0;
•
Output:
• 2 4 1
• 30.differences between the linked list and array.
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:
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.
1. int a[5];
In the above case, we have declared an array of 5 elements with 'a' name of
an integer data type.
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.
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.
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).
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).
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 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:
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:
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 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.
Single Inheritance
Multi Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multipath inheritance
Multiple Inheritance
Single 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
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
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance (Through Interface)
Hybrid Inheritance (Through Interface)
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
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.
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
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.
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.
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
return 0;
}
Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
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.
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
a = a + b;
b = a - b;
a = a - b;
return 0;
}
The output of this program is the same as the first program above.
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 .
int a = 5, b = 10;
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.
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.
If the value evaluates to be true then the loop body gets repeatedly executed,
otherwise, it gets terminated.
For Example:
int x = 0;
System.out.println(Value of x: “ +x);
int 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
int i,sum;
for(i = 1 , sum = 0; i <= 10; ++i)
sum = sum + i;
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
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:
See, even if you skip the initialization expression, the semicolon (;) must be
following it.
package com.TechVidvan.loopsDemo;
int i = 1, sum = 0 ;
System.out.println(i);
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;
int x;
for( x = 25 ; ; x-- )
Output:
This is an infinite loop…
Similarly, we can also skip all three expressions to create an infinite loop:
for( ; ; ; )
loop body
package com.TechVidvan.loopsDemo;
for(int x = 25 ; x>=0; x -= 5)
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 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.
package com.TechVidvan.loopsDemo;
i = num ;
while(num != 0)
--num;
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.
long wait = 0;
; //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.
package loopsDemo;
int j = 0;
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)
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:
package com.TechVidvan.loopsDemo;
char ch = 'A' ;
do
ch++;
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.
{
int i, j;
{ //outer 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.
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.
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.
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.
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.
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.