BCA Unit 1
BCA Unit 1
-->Data Structure: Data structures refer to data and representation of data objects within a program, that is, the
implementation of structured relationships. A data structure is a collection of atomic and composite data types into a set
with defined relationships.
A data structure is
1. a combination of elements, each of which is either as a data type or another data structure
->Abstract Data Type: An ADT is the one in which the set of operations is defined at a formal, logical level, without being
restricted by the operational details. An ADT is a data declaration packaged together with the operations that are
meaningful for the data type. We encapsulate the data and the operations on this data and hide them from the user.
An ADT includes declaration of data, implementation of operations, and encapsulation of data and operations.
Consider the concept of a queue. At least three data structures will support a queue. We can use an array, a linked list, or a
file. If we place our queue in an ADT, users should not be aware of the structure we use. We are aware of the importance of
hiding the implementation. The user need not know the data structure to be able to use an ADT. Allowing the application
program to directly reference the data structure is a common fault in many applications that prevent the ADT from being
fully portable to other applications.
We want a data specification method that has the following features:
Abstract It should help the programmer organize data by focusing on its logical properties rather than on the
implementation details, which in turn allows the user to hide the complexity of a task.
Safe It should control the manipulation of the representation of data so that malfunctioning can be avoided.
Modifiable It should make it relatively easy to modify the representation.
Reusable The data structure should be such that it is a reusable product for others.
These two sets form a mathematical construct that may be implemented using a particular programming language. The
data structure is independent of their implementation. The various types of data structures are as follows.
1. Primitive and non-primitive
2. Linear and non-linear
3. Static and dynamic
4. Persistent and ephemeral
5. Sequential and direct access
1. Primitive and non-primitive:
Primitive data structures define a set of primitive elements that do not involve any other elements as its subparts
Ex: Data structures defined for integers and characters. These are generally primary or built-in data types in programming
languages.
Non-primitive data structures are those that define a set of derived elements such as arrays. Arrays in C++ consist of a set of
similar type of elements. Class and structure are other examples of non-primitive data structures, which consist of a set of
elements that may be of different data types and functions to operate on.
3. Static and Dynamic: A data structure is referred to as a static data structure if it is created before program
execution begins (also called during compilation time). The variables of static data structure have user-specified
names. An array is a static data structure.
In many applications, it is desirable to be able to start a program with the smallest amount of memory necessary and then
allocate extra memory as the need arises. This facility is provided by many programming languages and in C++, through the
operator new. These functions allow programmers to allocate memory during execution.
A data structure that is created at run-time is called dynamic data structure. The vari-ables of this type are not always
referenced by a user-defined name. These are accessed indirectly using their addresses through pointers.
A linked list is a dynamic data structure when realized using dynamic memory management and pointers, whereas an array
is a static data structure. Non-linear data structures are generally implemented in the same way as linked lists. Hence, trees
and graphs can be implemented as dynamic data structures.
4. Persistent and Ephemeral: Data structures comprise a set of operations and a set of data to operate on. The
operations that process the data may modify the data. This may create two versions of a data structure namely the
recently modified (also called as updated) data structure and the previous version, which can be saved before
performing any operation on it
A data structure that supports operations on the most recent version as well as the previous version is termed as a
persistent data structure. A persistent data structure is partially persistent if any version can be accessed but only the most
recent one can be updated; it is fully persistent if any version can be both accessed and updated.
An ephemeral data structure is one that supports operations only on the most recent version.
The distinction between ephemeral and persistent data structure is essentially the distinction between functional (also
called effect free) and conventional imperative (also called effect full) programming paradigms.
The functional data structures are persistent and the imperative data structures are ephemeral.
5. Sequential Access and Direct Access: This classification is with respect to the access operations associated with
data structures. Sequential access means that to access the nth element, we must access the preceding (n - 1) data
elements.
Ex: A linked list
Direct access means that any element can be accessed without accessing its predecessor or successor; we can directly
access the nth element.
Ex: An array
1 Data Element In linear data structure, data elements are In non-linear data structure, data elements are
Arrangement sequentially hierarchically
connected and each element is traversable connected and are present at various levels.
through a single run.
2 Levels In linear data structure, all data elements In non-linear data structure, data elements are
are present at a single level. present at multiple levels.
3 Implementation Linear data structures are easier to Non-linear data structures are difficult to
Complexity implement. understand and
implement as compared to linear data
structures.
4 Traversal Linear data structures can be traversed Non-linear data structures are not easy to
completely in a single run. traverse and needs multiple runs to be
traversed completely.
5 Memory Linear data structures are not very Non-linear data structures uses memory very
utilization memory friendly and are not utilizing efficiently.
memory efficiently.
#include<iostream>
using namespace std;
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
2. Private: The class members declared as private can be accessed only by the member functions inside the class. They are
not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend
functions/ friend class are allowed to access the private data members of the class.
#include<iostream>
using namespace std;
class Circle
{
private:
double radius;
public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
obj.radius = 1.5; // trying to access private data member directly outside the class - Error
cout << "Area is:" << obj.compute_area();
return 0;
}
3. Protected: The protected access modifier is similar to the private access modifier in the sense that it can’t be accessed
outside of its class unless with the help of a friend class. The difference is that the class members declared as Protected can
be accessed by any subclass (derived class) of that class as well.
Note: This access through inheritance can alter the access modifier of the elements of base class in derived class depending
on the mode of Inheritance.
Example:
CPP
#include <bits/stdc++.h>
using namespace std;
class Parent // base class
{
protected:
int id_protected;
};
class Child : public Parent // sub class or derived class from public base class
{
public:
void setId(int id)
{
id_protected = id; // Child class can access the inherited protected data members of base class
void displayId()
{
cout << "id_protected is: " << id_protected << endl;
}};
int main()
{
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
}
public:
Triangle(double a_in, double b_in, double c_in);
void scale(double s) {
this->a *= s;
this->b *= s;
this->c *= s;
}
};
The class has member variables for the length of each side, defining the data representation. We defer discussion of the
public: and Triangle(...) lines for now. Below those lines are member functions for computing the perimeter of a triangle and
scaling it by a factor.
The following is an example of creating and using a Triangle object:
int main()
{
Triangle t1(3, 4, 5);
t1.scale(2);
cout << t1.perimeter() << endl;
}
void accelerate( )
{
speed += 10;
}
void brake( )
{
speed -= 5;
}
};
int main()
{
Car myCar; // Create an object of Car
myCar.color = “red”;
myCar.accelerate( );
myCar.accelerate( );
myCar.brake( );
cout << “My Car is “ << myCar.color << “and is going “ << myCar.speed << “mph.” << "\n";
return 0;
}
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory
location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables
but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that
numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of
the required size.
The diagram above shows that it arranged all the elements row-wise in a single dimension, one after the other.
Now, take an example of a one-dimensional array.
In this example, you are printing the elements 1,7,9,4,5 using for loop, and depicted below is the output of this example.
Two-Dimensional Array:
In this type of array, two indexes describe each element, the first index represents a row, and the second index represents a
column.
In this example, you are printing a two-dimensional array of three rows and three columns; you need to use two for loops.
The first loop, i.e., i loop, runs for the row from 0 to 3, and the second loop, i.e., j loop, runs for the column from 0 to 3.
And below is the output of this example.
Multidimensional Array:
The simplest example of a multidimensional array is a 2-d array; a two-dimensional array also falls under the category of a
multidimensional array. This array can have any number of dimensions.
The syntax for declaring a multidimensional array is:
Syntax:
Datatype array_name [size 1][size 2] . . . . . [size n];
Here size1 size2 up to so on size n describes the number of dimensions; in the case of a 2-d array, there are only two
dimensions, a multidimensional array can have any number of dimensions.
Example:
int array[5][10][4];
C++ Strings
A string is a collection of characters. There are two types of strings commonly used in C++ :
Strings that are objects of string class (The Standard C++ Library String Class)
C-strings (C-style Strings)
C-strings
In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming.
Hence, it's called C-strings.
C-strings are arrays of type char terminated with a null character, that is, \0 (ASCII value of null character is 0).
int main()
{
char str[100];
return 0;
}
Run Code
Output
Enter a string: C++
You entered: C++
String Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects have no fixed length and can be extended as per your requirement.
int main()
{
string str1;
char str[100];
display(str1);
display(str);
return 0;
}
void display(string s)
{
cout << "Entered string is: " << s << endl;
}
Run Code
Output
Enter a string: Programming is fun.
Enter another string: Really?
Entered string is: Programming is fun.
Entered char array is: Really?
In the above program, two strings are asked to enter. These are stored in str and str1 respectively, where str is a char array
and str1 is a string object.
Then, we have two functions display() that outputs the string onto the string.
The only difference between the two functions is the parameter.
The first display() function takes the char array as a parameter, while the second takes the string as a parameter.
This process is known as function overloading. Learn more about Function Overloading.
strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
5
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
6
Returns a pointer to the first occurrence of string s2 in string s1.
Example
Following example makes use of few of the above-mentioned functions −
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
resize() This function is used to resize the length of the string up to the given number of characters.
push_back() This function is used to push the character at the end of the string
pop_back() This function is used to pop the last character from the string
clear() This function is used to remove all the elements of the string.
This function is used to search for a certain substring inside a string and returns the position of
find()
the first character of the substring.
This function is used to replace each element in the range [first, last) that is equal to old value
replace()
with new value.
compare() This function is used to compare two strings and returns the result in the form of an integer.
Length of a String
The length of a string is the number of characters present in the string. Hence, the string "apple" has a length of 5
characters and the string "hello son" has a length of 9 characters (including empty spaces). This can be accessed using the
length() method in <string> header file.
Syntax
The syntax is explained as follows −
int len = string_1.length();
Example: String Length
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x="hey boy";
cout<<x.length()<<endl;
return 0;
}
Output
7
String Concatenation
String concatenation is a way to add two strings together. This can be done using two ways −
Addition Operator
The addition operator is used to add two elements. In case of strings, the addition operator concatenates the two strings.
This is clearly explained in the following example −
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x = "10";
string y = "20";
cout<<x+y<<endl;
return 0;
}
Output
1020
Using string append() method
C++ is an object oriented programming language, and hence a string is actually an object, which contain functions that can
perform certain operations on strings. We can use string append() method to append one string to another.
The syntax of this operation is as follows −
Syntax
string_1.append(string_2);
The usage of this method is depicted clearly in the following example −
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string x="hey boy";
string y=" now";
x.append(y);
cout<<x<<endl;
return 0;
}
Output
hey boy now