0% found this document useful (0 votes)
20 views

C++ 123

The document discusses the key differences between object-oriented programming (OOP) and procedural programming (POP). It then lists the main principles of OOP including inheritance, polymorphism, abstraction and encapsulation. The document also discusses access specifiers in C++ and provides examples of public, private and protected access specifiers. Finally, it defines what a data type is and explains basic and user-defined data types in C++.

Uploaded by

Priya Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

C++ 123

The document discusses the key differences between object-oriented programming (OOP) and procedural programming (POP). It then lists the main principles of OOP including inheritance, polymorphism, abstraction and encapsulation. The document also discusses access specifiers in C++ and provides examples of public, private and protected access specifiers. Finally, it defines what a data type is and explains basic and user-defined data types in C++.

Uploaded by

Priya Shinde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

ASSIGNMENT 1

1. Differentiate between OOP and POP?


FAEDDAEMIVOE

OOP POP
1 Object oriented programming Procedural oriented programming
2 Follows bottom-up approach Follows top to down approach
3 Emphasis on Objects Emphasis on Functions
4 Programs are divided into Programs are divided into objects
objects functions
5 It deals with data It deals with algorithm
6 It has access specifiers like Most functions use global data
public, private, protected.
7 It is possible to hide data by using There is no data hiding mechanism so it
encapsulation so provides more is less secure
security
8 Modifications are easier and Modifications are difficult as they can
objects are independent affect the entire program
9 Inheritance property is used Inheritance property is not allowed
10 Concept of virtual function No virtual function
11 Overloading is possible in the Overloading is not possible
form of function overloading
and operator overloading
12 C++, Python, Java, .NET C, Pascal, Fortran

1. List the main principles of Object-Oriented Programming?

 INHERITANCE:
 Mechanism to reuse an existing class to build a new class
 The new class inherits all the behavior of the original class
 The class whose properties are inherited by another class is called as super class or
parent class
 The class that inherits properties from parent class is call as sub class or child class
 Powerful feature in OOP.
 class <derived_class_name> : <access-specifier> <base_class_name>

//body

 POLYMORPHISM

 An OOP concept that refers to the ability of a variable, function or object to take on
multiple forms.
 Ability to redefine methods for derived classes.
 Types:
a. Compile time polymorphism Ex. Method overloading.
b. Run time polymorphism Ex. Method overriding.
 Helps programmers to reuse the code once written, tested & implemented.

 ABSTRACTION

 Abstraction is the process of hiding internal data and implementation from the end
user
 Key feature in OOP
 Types:
a. Data abstraction
b. Process abstraction

ADVANTAGES:

 It reduces the complexity of viewing the things.


 Helps to increase security of an application or program as only important details
are provided to the user.
 Avoids code duplication and increases reusability.
 Can change internal implementation of class independently without affecting the
user.
 ENCAPSULATION
 Encapsulation is a means of binding data variables and methods together in a
class.
 Only objects of the class can then be allowed to access these entities.
 This is known as data hiding and helps in the insulation of data.

2. What are the access specifiers in C++? Give Examples.

 C++ has three different types of access modifiers –


Public, Private, Protected
 If you don’t specify any keyword then, by default in C++ the class members will take
private behaviour.

A] PUBLIC ACCESS SPECIFIER

If any class member (data members/member functions) is declared under public then –

 Are accessible to everyone.


 The public keyword is used to create public members (data and functions).

B] PRIVATE ACCESS SPECIFIER

If any class member is declared under private then-

 accessed by functions declared inside the class


 Not accessible to the outside classes
 Only the member functions or the friend functions are allowed to access the private
data members of a class

C] PROTECTED ACCESS SPECIFIER


If any class members are declared under protected then-
 It is the same as private accessibility
 But, derived [subclasses/child] classes can also access the protected class members.
 These protected members are inaccessible outside. But are accessible in the derived
class as protected data members

class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
protected // protected access specifier
int z; // Protected attribute
};

EXAMPLES:

1]PUBLIC:

// private access specifier.cpp


#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};
class derive: private base {

public:
void showdata()
{
cout << "x is not accessible"<< endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};

int main()
{
derive a; //object of derived class
a.showdata();
return 0;
}

Output
Enter your age: 20
Age = 20

2] PRIVATE:

#include <iostream>
using namespace std;
// define a class
class Example {
// private elements
private:
int age;
// public elements
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare an object
Example obj1;
cout << "Enter your age: ";
cin >> ageInput;
// call function and pass ageInput as argument
obj1.displayAge(ageInput);
return 0;
}

Output
Enter your age: 20
Age = 20

3] PROTECTED

#include <iostream>
using namespace std;
// declare parent class
class Example {
// protected elements
protected:
int age;
};
// declare child class
class ExampleChild : public Example {
public:
void displayAge(int a) {
age = a;
cout << "Age = " << age << endl;
}
};
int main() {
int ageInput;
// declare object of child class
ExampleChild child;
cout << "Enter your age: ";
cin >> ageInput;
// call child class function
// pass ageInput as argument
child.displayAge(ageInput);
return 0;
}

Output
Enter your age: 20
Age = 20
3. What is data type? Explain basic and user defined data types in C+
+?

A data type specifies the type of data that a variable can store such as integer, floating,
character etc.

BASIC DATA TYPES:

1. Integer:
o Represents whole numbers without the fractional or decimal part.
o Ex. Int x = 5;
2. Character
o Represents individual character from a character set like ASCII or Unicode.
o Ex. Char x = ‘A’;
3. Boolean
o Represents binary values used for true (1) or false (0) for conditions.
o Bool keyword is used for Boolean data type.
o Ex. Bool isTrue = true;
4. Floating Point
o Represents numbers with a fractional part.
o Ex. Float x = 3.14567;
5. Double Floating Point
o Represents numbers with higher range and precision than float.
o Ex. Double x = 3.147875465;
6. Valueless or Void
o Indicates that a function does not return any value.
o Ex. void function () { // code }
7. Wide Character
o Wide char is similar to char data type, except that wide char takes up twice the space
and can take on much larger values as a result.
o Ex. wchar_t X = L 'A';

USER-DEFINED DATA TYPES:

1. Class
o Class is a user-defined data type that represents a blueprint for creating objects
o It encapsulates data (attributes) and function (methods) that operate on that
data.
o Class class-name () {};
2. Structure
o User-defined data type that stores different data type in separate memory
locations.
o struct Point {
int x;
char y;
};
3. Union
o User-defined data type that stores different data types in the same memory
location.
o union GFG {
int x;
char y;
};

4. Enum (Enumeration)
o Consists of a set of named integer constants.
5. Typedef
o Allows you to create aliases for existing data types.

4. DESCRIBE TOKEN IN C++?

A token is a smallest element of a C++ program that is meaningful to the compiler.


There are 6 types of tokens in C++
[KICSSO]
1. Keyword
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
A token is the smallest element of a C++ program that is meaningful to the compiler.
1. Keywords:
o In C++, keywords are reserved words that have a specific meaning in the language
and cannot be used as identifiers.

2. Identifiers
o In C++, an identifier is a name given to a variable, function, or another object in the
code.

3. Constants
o In C++, a constant is a value that cannot be changed during the execution of the
program.

4. String:
o In C++, a string is a sequence of characters that represents text.

5. Special symbols:
o Special symbols are the characters having specific meaning within the syntax.
o Ex. semicolon (;)

6. Operators:
o In C++, operators are special symbols that are used to perform operations on one or
more operands.
o Ex. Increment operator (++)

5. Write a note on

1. Array
 An array is a collection of items of same data type stored at continuous memory
locations.
 Individual array elements are accessed by their index.
 Index numbering starts from 0.
 int x [6];

2. Type Conversion
 Conversion of one data type to another data type
 There are 2 types
a. Implicit conversion
i. Automatically done by the compiler.
b. Explicit conversion (type casting)
ii. Conversion is done manually.
3. Operators [ARLBA]
 In C++, operators are special symbols that are used to perform operations on one or
more operands.
1) Arithmetic operator
 Used to perform arithmetic operations on variables and data.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
2) Logical operator
 Used to check whether an expression is true or false.
 If it is true, it returns 1 and returns 0 for false.

Logical AND.
&& expression1 && expression2
True only if all the operands are true.
Logical OR.
|| expression1 || expression2
True if at least one of the operands is true.
Logical NOT.
! ! expression
True only if the operand is false.

3) Relational operator
 Used to check relation between two operands
== Is Equal To 3 == 5 gives us false
!= Not Equal To 3! = 5 gives us true
> Greater Than 3 > 5 gives us false
< Less Than 3 < 5 gives us true
>= Greater Than or Equal To 3 >= 5 give us false
<= Less Than or Equal To 3 <= 5 gives us true

4) Bitwise operator
 Used to perform operations on individual bits
& Binary AND
| Binary OR
^ Binary XOR
~ Binary One's Complement
<< Binary Shift Left
>> Binary Shift Right

5) Assignment operator
 Used to assign values to variables
 Symbol: example: equivalent to
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

4. Identifiers

 In C++, an identifier is a name given to a variable, function, or another object in the


code.
 Can contain letter, digit and underscore.
 Name must begin with a letter or an underscore (_)
 They are case sensitive.
 Whitespaces and special characters (#, !, %) are not allowed.
 Keywords cannot be used as identifiers.

5. Variable

 Variables in C++ is a name given to a memory location.


 Value stored in a variable can be changed during program execution.
 In C++ all variables must be declared before use.
 Ex. Type variable_name;

6. Constants

 In C++, a constant is a value that cannot be changed during the execution of the
program.
 const int PI = 3.14;

6. Write a program to take input 10 numbers and display it by using


one dimensional array in C++.

# include <iostream>
using namespace std;

int main(){
int size = 10;
int num[size];

// input
cout << "enter 10 numbers: "<< endl;
for(int i = 0; i < size; ++i){
cout << "eneter number " << (i + 1) << ":" << endl;
cin >> num[i];
}
// display
for(int i = 0; i < size; ++i){
cout << num[i] << " ";
}
cout << endl;
return 0;
}
Theory Assignment II

Function Declarations (first)


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 );

int max(int num1, int num2);

int max(int, int);

Calling a Function (mid)


To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example −

int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}

Defining a Function (last)

// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
};
Example:

#include <iostream>
using namespace std;

// function declaration
int max(int num1,int mun2);

int main(){
//calling of the function
int a=5;
int b=6;
int result;
result=max(a,b);
cout<<"max no. is:"<<result<<endl;
return 0;
}
//fun definition
int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
};

1) Define Function? Differentiate between call by value and call by


reference method?

A function is a group of statements that together performs a task.

No. Call by value Call by reference

1 Function is called by directly passing Function is called by passing address


value of variables as arguments. of the variables as arguments
2 Changes made inside the function are Changes made inside the function are
not reflected on other functions reflected outside the function also

3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

4 Does not require pointer concept Requires pointer concept

Call by value

In call by value method of parameter passing, the values of actual parameters are copied to the
function’s formal parameters.

#include <iostream>
using namespace std;

// function declaration
void swapx(int x,int y);

int main(){
//calling of the function
int a=5;
int b=6;
swapx(a,b);
cout<<"\n"<<"int_main"<<"\n";
cout<<"a="<< a << "b="<< b;
return 0;

}
//fun definition
void swapx(int x, int y) {
// local variable declaration
int t;
t=x;
x=y;
y=t;
cout<< "def"<<"\n";
cout<<"x="<< x << "y="<< y;

Call by reference:

In call by reference method of parameter passing, the address of the actual parameters is passed to
the function as the formal parameters.
#include <iostream>
using namespace std;

// function declaration
void swapx(int&,int&);

int main(){
//calling of the function
int a=5, b=6;
swapx(a,b);

cout<<"\n"<<"int_main"<<"\n";
cout<<"a="<< a << "b="<< b;
return 0;
}
//fun definition
void swapx(int& x, int& y) {
// local variable declaration
int t;
t=x;
x=y;
y=t;
cout<< "def"<<"\n";
cout<<"x="<< x << "y="<< y;

2) Explain simple C++ program with class and access modifiers?

// private access specifier.cpp


#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;
public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};

class derive: private base {

public:
void showdata()
{
cout << "x is not accessible"<< endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};

int main()
{
derive a; //object of derived class
a.showdata();
return 0;
}

3) Which are the access specifiers in C++? Give Examples.


class Base {
public:
// public members go here
protected:

// protected members go here


private:
// private members go here

};

4) What is Constructor? Describe types of Constructors with


example?
o Constructor in C++ is a special method that is invoked automatically when object of
that class is created.
o Constructor is a member function of a class, whose name is same as the class name.
o Used to initialize the data members for an object of a class automatically.
o Constructor do not return value; hence they do not have a return type.

A. Default Constructors:
o which doesn’t take any arguments & has no parameters.
o also called a zero-argument constructor.

B. Parameterized Constructors:

o Possible to pass argument’s

C. Copy constructor

o Member function that initializes an object using another object of the same class.

1. Default Constructors:
#include <iostream>
using namespace std;

class construct{
public:
int x, y;

construct() {
x=1;
y=2;
};

};

int main() {
construct c;
cout<<c.x<<c.y;
return 0;
}
output
12
2. Parameterized Constructors:
#include <iostream>
using namespace std;

class pc{
private:
int x, y;
public:
pc(int x1, int y1) {
x=x1;
y=y1;
};
int getx(){return x;}
int gety(){return y;}
};

int main() {
pc p1(1,2);
cout<<p1.getx()<<endl;
cout<<p1.gety();
return 0;
}
output:
1
2

3. Copy Constructor:
#include <iostream>
using namespace std;

class pc{
private:
int x;
public:
pc(int x1) {
x=x1;
};
int getx(){return x;}
};

int main() {
pc p1;
cout<<p1.getx()<<endl;

pc p2(p1);
cout<<"copy constructor"<<endl;
cout<<p2.getx();
return 0;
}
o/p:
1
copy constructor
1

Public access specifier:


#include <iostream>
using namespace std;

class student{
int x, y, z;

public:
student() {
x=1;
y=2;
z=3;
};

void display() {
cout<<x<<y<<z;
};
};
int main() {
student a;
a.display();
return 0;
}

1. Write a note on
1. Function Overloading

o Process of having two or more function with the same name but with different
parameters.
o Same name is used for two or more functions
o void add(int a, int b);
o void add(double a, double b);

#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum_int = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum_double = " << (a + b);
}

// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}

sum_int = 12
sum_double = 11.5

2. Default Arguments

o A default argument is a value provided in a function declaration that is automatically


assigned by the compiler, if the calling function doesn’t provide a value for the
arguments.
o In case any value is passed the default value is overridden.
o int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z & w as 0.

// CPP Program to demonstrate Default Arguments


#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}

// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;

// Statement 2
cout << sum(10, 15, 25) << endl;

// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
25
50
80

3. Destructor
o Like constructor, destructor is a member function whose name is same as the class
name but is preceded by a tilde (~)
o Special member function that is used to destroy objects that have been created by a
destructor.
o Destructor never takes any arguments, nor does it return any value.
o Ex. ~Name () {}

4. Static data member


o Static data members are class member that are declared using static keyword.
o Only one copy of that member is created and is shared among all the objects of that
class.
o It is initialized before any objects of this class are created, even before the main starts.
o It is visible only within the class but its lifetime is the entire program.
o Static data-type data-member;

5. Static Member Functions


o Can access only other static members of the class.
o Ex. class-name :: function-name;
o Can call only other static functions.

6. Array of Objects
o Collection of objects of the same class type that are stored in continuous memory
locations.
class className {
//variables and functions
};
className objectName[number of obj];

Theory Assignment 3
1. What is Operator Overloading? Explain unary operator
overloading with example.
o Operator overloading is a compile-time polymorphism, in which the operator is
overloaded to provide a special meaning to the user-defined data type.
o Used to perform operations on user defined data types.
o Return-type class-name :: operator symbol(arguments) {//body}
o Operators that cannot be overloaded are
i. Scope operator (::)
ii. Sizeof
iii. Member selector (.)
iv. Member pointer selector (*)
v. Ternary operator (:?)

UNARY OPERATOR OVERLOADING:


o Allows us to modify the behaviour of a unary operator.
o Ex. void operator ++() { num = ++num; }

#include <iostream>
using namespace std;

class NUM
{
private:
int num;

public:
void getNum(int x) { num = x; }

void print() { cout << num; }


void operator ++() { num = ++num; }
};

int main(){
NUM num;

num.getNum(6);

cout << "Before increment: ";


num.print();

++num;
cout << endl << "After increment: ";
num.print();

return 0;
}

Output:
Before increment: 6
After increment: 7

2. List out the rules of Operator Overloading?


o Only built-in operators can be overloaded.
o The overloaded operator should contain at least one operand of the user-defined data
type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators
o We cannot change the basic meaning of an operator.
o Arity (number of operands) cannot be changed. Unary op remains unary and binary
op remains binary.
o Precedence of an operator cannot be changed

3. Illustrate binary Operator Overloading with example?


o Allows us to modify the behaviour of a BINARY operator.
using namespace std;

class NUM {
private:
int n;

public:
void getNum (int x) {n = x;}
void print () {cout << n;}
NUM operator + (NUM & obj) {
NUM x;
x.n = n + obj.n;
return x;
}
};
int main () {
NUM a, b, sum;
a.getNum(3);
b.getNum(2);
sum = a + b;
sum.print();

return 0;
}

4. What is Inheritance? Describe the types of inheritance in C++.

In C++, inheritance is a process in which one object acquires all the properties and
behaviours of its parent object automatically.

In such way, you can reuse, extend or modify the attributes and behaviours which are defined
in other class.

o Parent class: The class from which the child class inherits its properties is called the
parent class or base class.
o Child class: The class that inherits the characteristics of another class is known as the
child class or derived class

1) Single inheritance

o In single inheritance a class derives from only one base class.


o There is only one subclass that is derived from one superclass.
o Class subclass: access specifier superclass {//code};

2) Multiple inheritance

o Multiple inheritance is a type of inheritance in which a class derives from more than
one class.
3) Hierarchical inheritance

o Hierarchical inheritance more that one class inherits from a single base class.
o This gives it a structure of a hierarchy.

4) Multilevel inheritance

o In multilevel inheritance a class is derived from another derived class.


o It can have many levels of implementation.

5) Hybrid inheritance

o Hybrid inheritance is a combination of more than one type of inheritance.


o Here we have multiple inheritance (BCD) and multilevel inheritance (ABD) to get a
hybrid inheritance.
5. Write a program to implement the concept of Single inheritance.
#include <iostream>
using namespace std;

class base{
public:
void display(){
cout << "this is inside the base class" << endl;
}
};
class derived : public base{
public:
void show(){
cout << "this is inside derived class";
}
};

int main() {
base a;
a.display();
derived b;
b.display();
b.show();
return 0;
}
Output:
this is inside the base class
this is inside the base class
this is inside derived class

6. Write a short note on

1) Base Class and Derived Class


A. BASE CLASS:
a. The class from which the child class inherits all its properties (parent
class)
b. class base-class {
};

B. DERIVED CLASS:
a. The class that inherits the properties of another class. (child class)
b. class derived-class: access-specifier base-class {
};

2) Friend Function

o A friend function in is the one who can access private, protected and public members
of the class.
o A friend function is declared using friend keyword inside the body of a class.
o Class class-name {
friend return-type function-name(arguments); };
o Friend keyword is only placed in the declaration and not in the function definition.
o Cannot be called using objects of that class.

3) Virtual Function

o Virtual function is a member function in a base class and is re-defined (overridden) by


a derived class
o Functions are declared using virtual keyword in base class.
o Mainly used to achieve runtime polymorphism.
o Class class-name {
Virtual return-type function-name(arguments); };

4) Hybrid Inheritance

o Hybrid inheritance is a combination of more than one type of inheritance.


o Here we have multiple inheritance (BCD) and multilevel inheritance (ABD) to get a
hybrid inheritance.
5) Abstract Class

o Has at least one pure virtual function (function that has no definition)
o The classes inheriting the abstract class must provide a definition for the pure virtual
function, otherwise the subclass would become an abstract class itself.
o We cannot create object of the abstract classes.
class Shape {
public:

// creating a pure virtual function


virtual void calculateArea() = 0;
};
// shape is a abstract class

Class and object

#include <iostream>
using namespace std;
class Student {
public:
int rollno;
char name[50];
float marks;
void display() {
cout<<"Roll Number: "<< rollno <<endl;
cout<<"Name: "<< name <<endl;
cout<<"Marks: "<< marks <<endl;
}
};
int main() {
Student stu1 = {1, "Harry", 91.5};
stu1.display();
return 0;
}
Assignment 4

Unit 4: Searching and Sorting Basics of Data Structure

Theory Assignment 4

Q1. Differentiate between linear search and Binary Search.

Linear search Binary search

Commonly known as sequential search commonly known as half-interval search

Elements are searched in a sequential Elements are searched using divide-and-


manner. conquer approach.

The elements in the array can be in random the elements in the array need to be in the
order sorted order.

Slow process Comparatively faster


preferred for small lists Preferred for large lists

can be used on multidimensional array Can only be used on single dimensional


array

Time complexity is O(N) Time complexity is O(log2N)

CMOTPDT

Q2. What is sorting? Describe Selection Sort in detail.


o Sorting is a process of arranging data into a meaningful order.
Selection sort
o Selection sort is a sorting algorithm that selects the smallest element from an unsorted
list in each iteration and places that element at the beginning of the unsorted list.
o Find the smallest number, swap it with the value in the first location of the array.
o Find the second smallest number, swap it with the value in the second location of the
array.
o Repeats the process until the array is completely sorted.

//selection sort in C++


#include <iostream>
using namespace std;

//swap
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
//print
void print(int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
//selection sort
void selectionSort(int a[], int n){
for(int i = 0; i < n - 1; i++){
int minIdx = i;
for(int j = i + 1; j < n; j++){
if(a[j] < a[minIdx]){
minIdx = j;
}
}
swap(a[minIdx], a[i]);
}
}
int main(){
int n = 5;
int a[n] = {1, 5, 6, 0, 7};

print(a, n);
selectionSort(a, n);
cout << endl << "After selection sort: ";
print(a, n);

return 0;
}

OUTPUT:
15607
After selection sort: 0 1 5 6 7

Q3. Describe Insertion Sort in detail.


o Sorting algorithm that places an unsorted element at its correct position in each
iteration.
o The first element of the array is assumed to be a sorted subarray.
o More efficient than the bubble sort.
o Starts from the second element, compares it with the second element, then put it in a
proper place.
o We perform this procedure on the next subsequent elements.
#include <iostream>
using namespace std;

// print
void print (int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
// insertion sort
void insertionSort(int a[], int n){
for(int i = 1; i < n; i++){
int current = a[i];
int j = i - 1;
while(current < a[j] && j >= 0){
a[j + 1] = a[j];
--j;
}
a[j + 1] = current;
}
}

int main(){
int n = 5;
int a[] = {5, 3, 8, 6, 1};
print(a, n);
cout << endl << "After insertion sort: ";
insertionSort(a, n);
print(a, n);

return 0;
}
Output:
53861
After insertion sort: 1 3 5 6 8

Q4. Describe bubble sort in detail.


o Bubble sort is a sorting algorithm that compares two adjacent elements and swaps
them until they are in the intended order.
o Repeatedly passes through the array.
o Slower than insertion sort.
o Simplest algorithm but generally not recommended.

General Algorithm

Step 1: For i = 0 to N-1 repeat Step 2


Step 2: For J = i + 1 to N – I repeat
Step 3: if A[J] > A[i]
Swap A[J] and A[i]
[End of Inner for loop]
[End if Outer for loop]
Step 4: Exit

#include <iostream>
using namespace std;
// swap
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
// print
void print(int a[], int n){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
// bubble sort
void bubbleSort(int a[], int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n - 1; j++){
if(a[j] > a[j + 1]){
swap(a[j], a[j + 1]);
}
}
}
}
int main(){
int n = 5;
int a[] = {5, 3, 8, 4, 1};

print(a, n);
bubbleSort(a, n);
cout << endl << "After bubble sort: ";
print(a, n);

return 0;
}
53841
After bubble sort: 1 3 4 5 8

Q5. Define data structure? Explain implementation of data structure


o Data structures are formats used to organize, store & manage data.
o Data structures can be used to access & modify data efficiently.
o Linear data structure
Elements are arranged sequentially. (arrays, linked list, stacks, queues)
o Non-linear data structure
Elements are not arranged sequentially. But are stored within different levels
(graphs, trees)
Implementation…

Static data structure


 the size of the structure is fixed.
 The content of the data structure can be modified but without changing the memory
space allocated to it.
 Arrays, Stacks, Queues, Trees (with fixed size)

Dynamic data structure

 size of the structure is not fixed and can be modified during the operations performed on
it.
 Lists, Trees (with variable size), Hash tables

Q6. Describe array as data structure.


1. Array is a linear data structure that contains elements of the same data type stored
at continuous and adjacent memory location.
2. Array’s work on an index system starting from o to n-1 where n is the size of the
array.
3. Operations that can be performed on array’s are searching, sorting, deletion,
insertion and traversal.
4. Data-type array-name [array-size];
5. 1 D array: int arr[n];
2D array: int arr[m][n];
3D array: int arr[m][n][o];
6. You can randomly access elements in the array using an index number.

nn

ASSIGNMENT 5
Q1. What is Linked List? Explain its types in detail.

o A linked list is a collection of nodes connected together via links.


o These nodes consist of data to be stored and a pointer to the address of the next node
within the linked list.
o There is no size limit.
o Any amount of data can be stored and can be deleted from it.

 Singly Linked List:


1. the nodes only point to the address of the next node in the list.
 Doubly Linked List:
1. The nodes point to the addresses of both previous and next node.
 Circular Linked list:
1. The last node in the list will point to the first node in the list.
2. It can either be singly or doubly linked list

Q2. Describe implementation of stack in C++.

o Stack is a linear data structure that follows LIFO (Last in First out) principle.
o It is a container in which insertion and deletion can be done from one end known as
top.
o Stack is an abstract data type with pre-defined capacity; hence it can store limited
elements.

OPERATIONS:

o Push (): insert an element in a stack. If the stack is full then the overflow condition
occurs.
o Pop (): delete an element from the stack. If the stack is empty, this state is known as
an underflow state.
o Peek (): It returns the element at the given position.
o isEmpty (): It determines whether the stack is empty or not.
o isFull (): It determines whether the stack is full or not.
o Count (): It returns the total number of elements available in a stack.
o Change (): It changes the element at the given position.
o Display (): It prints all the elements available in the stack.

Q3. Illustrate implementation of Queue in detail.


o Linear data structure that is open at both end and the operations are performed in
FIFO (Fist in First out) order.
o Insertion operation is performed at the rear end.
o Deletion operation is performed at the front end.
o For example, people waiting in line for a rail ticket form a queue.

TYPES:

o Simple Queue or Linear Queue


o Circular Queue
o Priority Queue
o Double Ended Queue (or Deque)

OPERATIONS:

o Enqueue: Insert an element at the end of the queue.


o Dequeue: Simply remove an element from the front of the queue.
o IsEmpty: Used to check if the queue is completely empty.
o IsFull: Used to check if the queue is completely full.
o Peek: Without removing it, obtain the value from the front of the queue.

Q4. Differentiate between stack and Queue.


Q5. What is Queue? Write different types of queues in C++.

Q6. What is BST? Explain types of tree traversal in data structure.

Q7. Describe Infix, Prefix and Postfix expression in data structure

Q8. Write note on

a) AVL Tree b) B Tree c) Binary Tree

You might also like