Sie sind auf Seite 1von 82

Version 1.

0
Prepared by LE Arshia Arif

NATIONAL UNIVERSITY OF SCIENCES AND


TECHNOLOGY

PRACTICAL HANDOUTS
EC-204 DATA STRUCTURES
&
OBJECT ORIENTED PROGRAMMING

DEPARTMENT OF MECHATRONICS ENGINEERING


COLLEGE OF ELECTRICAL AND MECHANICAL
ENGINEERING
Safety Instructions for CAD/CAM Lab

 It is the responsibility of the student to logout, Shutdown after using the computer.
 Do not change internet IP Address, it can cause conflict on the network.
 Please do not save your data on C: Drive.
 Do not plug in external devices without scanning them.
 Avoid stepping on electrical wires or any other computer cables.
 Do not remove any device from the lab without permission.
 Try not to type continuously for extremely long period, look away from the screen for a
while to give your eyes a rest.
 In case of any hazard immediately switch off main supply and inform the lab staff.
 Smoke detector and Alarming systems are installed in the lab.
 In case of fire shout loudly fire, fire and use emergency doors for evacuation.
 Never eat, drink or smoke while working in the laboratory.
 If a piece of equipment fails while being used, report it immediately to your lab staff or
tutor.
 Never try to fix the problem yourself because you could harm yourself and others.
CONTENTS

Lab 1: Introduction to MinGW and Compiling a C++ program

Lab 2: Standard output, input, and Handling IO exceptions

Lab 3: Recursion and Dynamic Memory Allocation

Lab 4: Linked List using pointers and structures

Lab 5: Introduction to Classes and Data Encapsulation Example in C++

Lab 6: Linked List: Node insertion and Deletion

Lab 7: Stacks and Queues implementation using Linked List

Lab 8: Inheritance and polymorphism

Lab 9: Operator Overloading

Lab 10: Templates

Lab 11: Abstract classes and Interfaces

Lab 12: Introduction to QT IDE for console applications

Lab 13: Introduction to GUI Application Using QT

Lab 14: Tree: Node Insertion and Searching

Lab 15: Trees: Deletion

Lab 16: Hackathon Project Guidelines

Annex: Coding Guidelines

Ref: https://www.tutorialspoint.com/cplusplus
Lab Number 01
Introduction to MinGW
&
Compiling a C++ program

Objective
Objective of this lab is to learn about:
 MinGW
 Compiling a C++ Program

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

What is MINGW?
Learn about MinGW using the following link. You will also know how to install it. It is very easy, just
follow the steps.
1 - http://www.mingw.org/wiki/Getting_Started
2 - http://www.mingw.org/wiki/HOWTO

MINGW is a GCC compiler for Windows. MSYS is a collection of GNU utilities such as bash, make, gawk
and grep to allow building of applications and programs which depend on traditionally UNIX tools to be
present. It is intended to supplement MinGW and the deficiencies of the cmd shell. While, MinGW
("Minimalistic GNU for Windows") is a collection of freely available and freely distributable Windows
specific header files and import libraries combined with GNU toolsets that allow one to produce native
Windows programs that do not rely on any 3rd-party C runtime DLLs.

MINGW Installation
An automated GUI installer assistant called mingw-get-setup.exe is the preferred method for first time
installation. This will guide you through the setup of the mingw-get installer proper; you will then use
this to perform further package installations, and to manage your installation.
Regardless of how you installed MinGW and/or MSYS, if you did choose to install MSYS, you should
check its configuration. You need to ensure that MSYS knows where MinGW is located, so:
1. Open a Windows Explorer window and locate your installation directory (i.e. C:\MinGW, or
any alternative you nominated during installation).
2. Below your installation directory, you should find a directory named "msys", (normally in
lower case letters, but mixed case, or all upper case is okay too); open this then find and open
the additional subdirectories, "1.0" and "etc".
3. Within the "etc" directory, there should be a file named "fstab"; (if not, create one, as a new
text file). Open this with a text editor; (you should be able to do this by right clicking on it, and
in the popup menu select "Open" or "Open With", although you may find that you need to
select a suitable editor application to do so).
4. Edit the file and ensure that it contains one line, (there may be others), which reads:

C:\MinGW /mingw

(substituting the FULL ABSOLUTE path of any alternative to C:\MinGW, which you nominated
during installation); ensure that you follow this path name entry with at least one space, or tab,
before typing the "/mingw" entry.

5. Before you save the file, ensure that there is at least one blank line at the bottom, below all of
the entries that may exist, then save and close the file.

6. Additionally, if you have installed MSYS, you are advised to create a start menu "MinGW
Shell" shortcut in your "Start\Programs\MinGW" folder, (which you may also need to create);
this should invoke the C:\MinGW\msys\1.0\msys.bat script, which is installed as a component
of MSYS; (if you installed to an alternative directory, you should adjust the C:\MinGW prefix
accordingly). Double clicking this shortcut will then open a command window with the correct
environment set up for you, including the correct path references, allowing you to run any of
the MinGW or MSYS applications within that command window.

7. Your MinGW and MSYS installations should now be ready for use.

How to compile your first Program using MINGW:


First you must make sure you have installed MinGW and set the PATH environment variable include
the location of MinGW. This is explained Here.
Now, assuming your directory for MinGW is the default "C:\MinGW", and your PATH environment
variable is set to include "C:\MinGW\bin", it is easy to start compiling an executable:
Open a command prompt window, and set the current directory to wherever your *.c or *.cpp file is.
Writing a C++ program in Notepad ++
Open a notepad ++ software and write your c++ program
Example Program:
// C program for insertion sort
#include <stdio.h>
#include <math.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}

Example:
For the file helloworld.cpp in the folder C:\sources\hello enter the commands
cd c:\sources\hello

Now type the compile command


g++ helloworld.cpp -o helloworld.exe

the -o switch specifies the name of the output file, without it the output file would be given a default
name of "a.exe".
If there are any errors in the source file the command line will notify you and direct you to the line
where the error is say you had forgotten to add an extra line at the end of your source file (an easy
mistake when moving from an environment such as Microsoft Visual C++) and you missed the ; at the
end of the last statement. You will get a message similar to this:
helloworld.cpp: In function 'int main()':

helloworld.cpp:4: error: expected ';' before '}' token

helloworld.cpp:5:2: warning: no new line at end of file


which describes both the positions of errors/warnings and the problem. I.e, for the missing ";" the
error is on line 4, so check your source file at line 4 for the error.
When compiling more than one cpp file, list the names of files after the g++ command and before the
-o switch.
g++ helloworld.cpp foo.cpp -o helloworld.exe

note: if your source is in C, rather than C++, your source files will be "helloworld.c", "foo.c", etc., and
you would use the "gcc" command, rather than the "g++" command; otherwise the procedure is
similar to the above.
Whilst still in the command prompt (and dircectory is still at the .exe's location) you can run your
program by typing the name of the executable file:
helloworld.exe

This will run your executable in the command prompt window.


For complete instructions on how to use the MinGW compiler, refer to the GCC manual.

Practice Tasks will now be displayed!


Lab Number 02
Standard Input, Output
&
Handling IO Exceptions

Objective:
Objective of this lab is to learn about:
 Standard Input, Output
 Handling IO Exceptions

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Standard Input/ Output in C++:


C++ comes with libraries which provide us many ways for performing input and output.
Streams:
In C++ input and output is performed in the form of sequence of bytes or more commonly known
as streams.
Streams are the C++ ways of interacting with files, keyboard, screen, and also strings. They typically
divide into streams you read (keyboard, files, strings) and streams you write (screen, files, strings). In all
cases, they are basically a sequence of characters that you are extracting from (read) or inserting into
(write). They are a fairly clean abstraction of reading and writing “items” one by one
The standard streams you’ll be interacting with are the following. They require you to #include different
header files, also listed here:
 Input Stream: If the direction of flow of bytes is from device (for example: Keyboard) to the
main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device
(display screen) then this process is called output.

Header files available in C++ for Input – Output operation are:


 iostream: iostream stands for standard input output stream. This header file contains definitions
to objects like cin, cout, cerr etc.
 iomanip: iomanip stands for input output manipulators. The methods declared in this files are
used for manipulating streams. This file contains definitions of setw, setprecision etc.
 fstream: This header file mainly describes the file stream. This header file is used to handle the
data being read from a file as input or data being written into the file as output.
We will mainly discuss about the objects defined in the header file iostream like cin and cout.

 Standard output stream (cout): Usually the standard output device is the display screen. cout is
the instance of the ostream class. cout is used to produce output on the standard output device
which is usually the display screen. The data needed to be displayed on the screen is inserted in
the standard output stream (cout) using the insertion operator (<<).

Example:
#include <iostream>

using namespace std;

int main( ) {
char sample[] = "Course";

cout << sample << " – Data Structures and Object Oriented
Programming";

return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

 Standard input stream (cin): Usually the input device is the keyboard. cin is the instance of the
class istream and is used to read input from the standard input device which is usually
keyboard.
The extraction operator (>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.

Example:
#include<iostream>
using namespace std;

int main()
{
int age;

cout << "Enter your age:";


cin >> age;
cout << "\nYour age is: "<<age;

return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

 Un-buffered standard error stream (cerr): cerr is the standard error stream which is used to
output the errors. This is also an instance of the ostream class. As cerr is un-buffered so it is
used when we need to display the error message immediately. It does not have any buffer to
store the error message and display later.
Example:
#include <iostream>

using namespace std;

int main( )
{
cerr << "An error occured";

return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
_______________________________________________________________________

File Handling:
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data.
To read and write from a file requires another standard C++ library called fstream, which defines two
stream classes:
• ofstream: Stream class to create files and to write information to files
• ifstream: Stream class to read information from files
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++
source file.

Opening a File:
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may
be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Syntax:
class_object.open(“file_name”);
Example:
ofstream myfile;
myfile.open ("example.txt");
Here myfile is the object of class ofstream. Now you can use the open() function through the object to
open a file.
Closing a File:
When a C++ program terminates it automatically flushes all the streams, release all the allocated
memory and close all the opened files. But it is always a good practice that a programmer should close
all the opened files before program termination.
Syntax:
class_object.close();
Example:
Myfile.close();
Here myfile is the object of any class and it has been used to call close() function to close the file.

Writing to a File:
While doing C++ programming, you write information to a file from your program using the stream
insertion operator (<<) just as you use that operator to output information to the screen. The only
difference is that you use an ofstream or fstream object instead of the cout object.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Run this code and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Reading from a File:


You read information from a file into your program using the stream extraction operator (>>) just as you
use that operator to input information from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.
Example:
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main()
{
string name;
ifstream rec;
rec.open("ex.txt");
rec >> name;
//cout << name;
while (!rec.eof())
{
cout << name <<" ";
rec >> name;
}
system("pause");
return 0;
}
Run this code and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_____________________

Exception Handling:
In this topic we learn that how can we control run time error using exception handing in C++. Exception
provides a method to control exceptional conditions (like run time error) or to control any crashed
program by transferring control to some special functions called handler.

We can use following the keywords or functions to control runtime error in C++:

1. try {}
2. catch {}
3. throw()

These functions are used to control any run time error.

Try{} block:
This block captures series of errors in any program at runtime and throws them to the catch block
where user can customize the error message. It represents a block of code that can throw an exception.

Syntax:
try
{
//define program;
throw(variable);
}
catch {} Block:

This block catches the error thrown by try block. This block contains method to customize error. It
represents a block of code that is executed when a particular exception is thrown.

Syntax:
catch
{
//defines method to control error;
}
throw function

This function is used to transfer the error from try block to catch block. This function plays major role to
save program from crashing.

Syntax:

throw(variable);

Multiple Catch Blocks:


We can use multiple catch block in a single program using single try block. Following example explain
that how can we uses multiple catch block in a single program.

Example 1:
#include<iostream>
using namespace std;
int main()
{
try
{
throw(55); //Here we input integer value;
}
catch(int e) //This catch takes int value;
{

cout<<"Input is Integer value "<<e<<endl;


}
catch(double e) //This catch takes double value;
{
cout<<"Input is Double value "<<e<<endl;
}
catch(char e) //This catch takes character value;
{
cout<<"Input is Character "<<e<<endl;
}

return 0;
}
Try to run this code with throw(55.5) and throw (‘I’) too. Write down your outputs with your
observations:
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_______________________________________________________________________________________________________

Catch All Block:


There is a special catch block called ‘catch all’ catch(…) that can be used to catch all types of exceptions.
Example:
In the following program, an int is thrown as an exception, but there is no catch block for int, so catch(…)
block will be executed.
#include <iostream>
using namespace std;

int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}

Run this code and write down your output:


_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________

Practice Tasks will now be displayed!


Lab Number 03
Recursion
&
Dynamic Memory Allocation

Objective
Objective of this lab is to learn about:
 Recursion

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Recursion:
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
Syntax:
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function; otherwise it will go into
an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.

Example (Factorial)
#include <stdio.h>
#include <iostream>
using namespace std;

int factorial(unsigned int i)


{
if (i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
cout<<"Factorial :” << factorial(i)<<endl;
return 0;
}
Run this Code and write down the output along with your observations:
_________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________

Dynamic Memory Allocation:


A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++
programmer. Memory in your C++ program is divided into two parts −
 The stack − All variables declared inside the function will take up memory from the stack.
 The heap − this is unused memory of the program and can be used to allocate the memory
dynamically when program runs.
1) Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run time.
2) You can allocate memory at run time within the heap for the variable of a given type using a special
operator in C++ which returns the address of the space allocated. This operator is called new
operator.

3) We can dynamically allocate storage space while the program is running, but we cannot create new
variable names "on the fly"
 For this reason, dynamic allocation requires two steps:
 1. Creating the dynamic space.
 2. Storing its address in a pointer (so that the space can be accesed)
 To dynamically allocate memory in C++, we use the new operator.
 Allocation is done by keyword new
int* ptr = new int;
int* ptr = new int[];

4) De-allocation:
 Deallocation is the "clean-up" of space being used for variables or other data storage
 Compile time variables are automatically deallocated based on their known extent (this is the
same as scope for "automatic" variables)
 It is the programmer's job to deallocate dynamically created space
 To de-allocate dynamic memory, we use the delete operator

Example 1(DMA)
#include <iostream>
using namespace std;
int main()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
Run this Code and write down the output along with your observations:
_________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________

Example 2(DMA)
//dynamic allocation
#include<iostream>
using namespace std;

int main()
{
int* ptr = new int;
*ptr = 2;
*ptr = *ptr * 4;
cout << "Data at memory is " << *ptr << endl;
delete ptr;
ptr = NULL;
return 0;
}
Run this Code and write down the output along with your observations:
_________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________

Practice Tasks will now be displayed!


Lab Number 04
Linked List using
Pointers & Structures

Objective
Objective of this lab is to learn about:
 Pointers
 Structures (Self Referential)
 Linked List

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Address of a memory location:


Every variable has a memory location and every memory location has its address defined which can be
accessed using ampersand (&) operator which denotes an address in memory.
Example:

Run this code and write down its output with your observations:
__________________________________________________________
__________________________________________________________
_______________________________________________________

Pointers:
 A pointer is a variable whose value is the address of another variable.
 Like any variable or constant, you must declare a pointer before you can work with it.
 The general form of a pointer variable declaration is –
Data_type *variable_name;
Here, Data_type is the pointer's base type; it must be a valid C++ type and variable_name is the
name of the pointer variable.
“*” is used before variable name to declare a pointer.

Examples:
 int * ip; // pointer to an integer
 char *cp; // pointer to a character
 double*dp; //pointer to a double type variable

Initializing a pointer:
We initialize a pointer by address of some type of variable.

Example:
int a=24;
int *ptr=&a;
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.

Example:
Int *ptr=NULL;

Dereferencing:
Dereferencing is to access the value at the address available in the pointer variable. This is done by using
unary operator * that returns the value of the variable located at the address specified by its operand.
Example:
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << var << endl;
cout << ip << endl;
cout << *ip << endl;
return 0;
}
Run this code. Write down its output with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Pointers and Arrays:


• Arrays and pointers may be used interchangeably, but you can change what pointers point at,
whereas arrays will always "point" to the same thing.

• Incrementing a Pointer:
Example:
int arr[3]={1,2,3};
int*ptr=arr; // pointing to first index of the array
ptr++; // pointing to the 2nd index of the array ptr++=ptr+1

Examples:
Code 1:
#include<iostream>
using namespace std;

int main()
{
int arr[5] = { 1,2,3,4,5 };
//int*ptr;
//ptr = arr;

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


{
cout << "Value of arr[" << i << "] = ";
cout <<arr[i] << endl;
}
system("pause");
return 0;

}
Code 2:
#include<iostream>
using namespace std;

int main()
{
int arr[5] = { 1,2,3,4,5 };
int*ptr;
ptr = arr;
for (int i = 0; i < 5; i++)
{
cout << "Value of arr[" << i << "] = ";
cout << *(ptr+i) << endl;
}
system("pause");
return 0;

}
Run Code 1 and code 2 and compare the outputs of both. Write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Structures:
A number of data items of different types grouped together.
They store related information, not necessarily of the same data-type.
Example: Students
 All the students have related information, such as their student ids, the courses taken and their
ages.
 Even though all this information is related to one student, the data-types are different.

How to make one:


//define it before main
struct Student
{
string name;
unsigned int roll_no;
unsigned int grade;
char syndicate;
bool gender;
};

How to use:
In your main, you can use them as variables
Student a, b;
a.name = "Usama";
b.name = "Ammar Ali";
cout << a.name << endl << b.name << endl;

Structure Variables:
Structure variables are declared like variables of other types. The following declarations
struct student data; // or student data
struct student body[ 52 ]; // or student body[52]
struct student *sPtr; // or student * sPtr;
declare data to be a structure variable of type student, body to be an array with 52 elements of type
student and sPtr to be a pointer to a Student structure

Example:
struct Date
{
int day;
int month;
int year;
};
int main()
{
Date d;
d.day = 12;
d.month = 9;
d.year = 2007;
}

Run this code and write down your output:


______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
_____________________

Self-Referential structures:
A structured data type which can point same data type.
Example:
struct node
{
Int data; //Data at this node
Node *next; //Pointer to next
};

Example:
int main()
{
node *p, *q ;//pointers to node
p = new node;//dynamic allocation
q = new node;
//linking two variables to form list
p -> data = 52;
p -> next = q;
q -> data = 26;
q -> next = NULL;
cout << p->data; //52
cout << p->next->data; //26
return 0;
}
Run this code and write down your output:
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

Linked List:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.

Arrays Vs Linked List:


Arrays can be used to store linear data of similar types, but arrays have following limitations:
1. The size of the arrays is fixed: So we must know the upper limit on the number of elements in
advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the
usage.
2. Inserting a new element in an array of elements is expensive, because room has to be created
for the new elements and to create room existing elements have to shifted.

Advantages of Linked List:


Following are the advantages of Linked List:
1. Dynamic size
2. Ease of insertion/deletion

Drawbacks of Linked List:


Following are some flaws of Linked List:
1. Random access is not allowed. We have to access elements sequentially starting from the first
node. So we cannot do binary search with linked lists.
2. Extra memory space for a pointer is required with each element of the list.

Representation of a Linked List:


A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If
the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1. Data
2. Pointer (Or Reference) to the next node

In C++, we can represent a node using structures. Below is an example of a linked list node with an
integer data.

Example:
struct node
{
int val;
node *ptr;

};

Creation of a Linked List:


The Pseudo codes for the insertion functions are given below:
 Insertion at Start:
Hea
d
2

Val 1
N
1. Point the new node’s pointer to the already present 1st node of the linked list.
2. Point the head to the new node being inserted.
3. Insert the value as data in the new node.

 Insertion at end:

HEA
D

1. Create a new node


2. Make its pointer equal to NULL.
3. Create a temporary node and traverse it from head to the last node of the linked list.
4. After reaching the last node, point its pointer to the new node.
5. Insert the value in the new node too.

 Insertion at a specific Position:


HEA
D
2 N 1

Val
1. Get the value and position as input arguments of the function.
2. Create a temporary node type pointer and traverse it till the position of insertion.
3. Create a new node “N” which is to be inserted.
4. Now point its pointer to the next node at (position+1) location.
5. Update the pointer of previous node and point it to the new node.
6. Insert the value in the new node too.

Practice Tasks will now be displayed!


Lab Number 05
Introduction to Classes
&
Data Encapsulation
Objective
Objective of this lab is to learn about:
 Classes
 Data Encapsulation

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Class:
A class is an expanded concept of C structure: instead of holding only data, it can hold both data and
functions. (now C structs can have functions too but everything is “public” in structs)

The fundamental idea is to combine into a single unit both data and functions that operate on the data.

 Such a unit is called an “Object”.


An object is an instantiation of a class. In terms of variables, a class would be the type, and an
object would be the variable
 The definition of this unit is called a “Class”.
 An object’s functions are called “member functions” (behaviors) in C++.
 And its data are called “data members” (attributes).

An object is an instantiation of a class. In terms of variables, a class would be the type, and an object
would be the variable

Syntax:
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
};
Access Specifiers:
An access specifier is one of the following three keywords:
 Private
 Public
 Protected
These specifiers modify the access rights that the members following them acquire

Main Parts of a Class:


 Data Members
 Constructor
 Member Functions
 Destructor

Example:

Private: visible to class members and member functions only!


Public: visible to the entire program!
Data Member: length
Member Functions: setdata() and showdata()
 Setdata()
Set hidden variable length equal to external variable l
 Showdata()
Display value of hidden variable length

Constructor:

 Initializes an object automatically as soon as the object is created


 Less prone to error
 Must have the same name as that of the class
 Constructors have No return type
 Constructors are called at the point an object is created
 If a class has a constructor, each object of that type is initialized with the constructor prior to
use in a program
 Eliminates the need to add the setdata() function
Syntax:
Two methods of writing the constructor:
 Counter(){count=0;}
OR
 Counter():count(0){};//initializerlist

Destructor:
 Destructor functions are the inverse of constructor functions.
 As constructors, destructor functions are also called automatically when an object is destroyed
 Same name as the class, preceded by tilde(~)
 No return values and No arguments
 The most common use of destructors is to de-allocate memory that was allocated for the object.
 Should be used before object goes out of scope

Example:

Objects:
 To use a class in a C++ program, its objects must be instantiated
 Similar to declaring a variable

Example:

Data Encapsulation:
All C++ programs are composed of the following two fundamental elements −
 Program statements (code) − This is the part of a program that performs actions and they are
called functions.
 Program data − The data is the information of the program which gets affected by the program
functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions
that manipulate the data, and that keeps both safe from outside interference and misuse. Data
encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data
abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from
the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined
types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private.
Example:
#include <iostream>
using namespace std;

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

// interface to outside world


void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};

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

int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
Run this code and write down the output along with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
The private member total is something that is hidden from the outside world, but is needed for the class
to operate properly.

Practice Tasks will now be displayed!


Lab Number 6
Linked List using Classes

Objective:
Objective of this lab is to learn about:
 Linked List
 Node Insertion
 Node Deletion

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from
another block
 Spaghetti code and confusing code is not acceptable

Linked List:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.

Arrays Vs Linked List


Arrays can be used to store linear data of similar types, but arrays have following limitations:
1. The size of the arrays is fixed: So we must know the upper limit on the number of elements in
advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the
usage.
2. Inserting a new element in an array of elements is expensive; because room has to be created
for the new elements and to create room existing elements have to shift.

Advantages of Linked List:


Following are the advantages of Linked List:
1. Dynamic size
2. Ease of insertion/deletion
Drawbacks of Linked List:
Following are some flaws of Linked List:
1. Random access is not allowed. We have to access elements sequentially starting from the first
node. So we cannot do binary search with linked lists.
2. Extra memory space for a pointer is required with each element of the list.

Representation of a Linked List:


A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If
the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
3. Data
4. Pointer (Or Reference) to the next node

In C++, we can represent a node using structures. Below is an example of a linked list node with an
integer data.

Example:
struct node
{
int val;
node *ptr;

};

Creating a Linked List:


Follow these steps to create a singly linked list:
1. Create a class named “Linkedlist” with a node type pointer, “head”.
2. In the constructor of class “Linkedlist”, initialize the head as NULL.
3. Create the function in the class to insert a node at the start of the linked list.
4. Create a new function in the class to insert a node at the end of the linked list.
5. Create a new function in the class to insert a node at a specific position of the linked list.
6. Create the function in the class to delete a node from the start of the linked list.
7. Create a new function in the class to delete a node from the end of the linked list.
8. Create a new function in the class to delete a node from a specific position of the linked list.
9. Create a function in the class to traverse through the complete list.
10. In the main function create an object of class “Linkedlist” and create a linked list by inserting
new nodes ( by using the functions of the class).
11. You can also traverse through the list to see the linked list data.

The Pseudo codes for the above mentioned functions are given below:
 Insertion at Start:
Head

2
N
Val 1
1. Point the new node’s pointer to the already present 1st node of the linked list.
2. Point the head to the new node being inserted.
3. Insert the value as data in the new node.

 Insertion at end:

HEA
D

1. Create a new node


2. Make its pointer equal to NULL.
3. Create a temporary node and traverse it from head to the last node of the linked list.
4. After reaching the last node, point its pointer to the new node.
5. Insert the value in the new node too.

 Insertion at a specific Position:


HEA
D
2 N 1
Val

1. Get the value and position as input arguments of the function.


2. Create a temporary node type pointer and traverse it till the position of insertion.
3. Create a new node “N” which is to be inserted.
4. Now point its pointer to the next node at (position+1) location.
5. Update the pointer of previous node and point it to the new node.
6. Insert the value in the new node too.

 Deletion from start:

2
HEAD
1

TEMP

1. Create a new temporary node type pointer.


2. Point it to the 2nd node.
3. Delete the first node and update the head.
4. Make the head point to the 2nd node.
 Deletion from end:
Previous Current
HEA
D

1. Create two new node type pointers, “Current” and “Previous”.


2. Traverse “Current” till last node and “Previous” till 2nd Last node.
3. Delete the Last node
4. Make the pointer of “Previous” node equal to NULL.

 Deletion from a specific Position:


Previous Current
HEAD
2

1
1. Create two new node type pointers, “Current” and “Previous”.
2. Traverse “Current” till specified Position and “Previous” till (Position-1) location.
3. Update the pointer of “Previous” and point it to the node next to “Current”.
4. Delete the “Current” node.

 Traversal:

HEAD

1. Create a temporary node type pointer.


2. Traverse it through the whole list until it becomes equal to NULL.
3. Keep displaying the data along with traversal.

Practice Task will now be displayed!


Lab Number 07
Stacks and Queues implementation
Using Linked List

Objective:
Objective of this lab is to learn about:
 Stacks
 Queues

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Stacks:
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order should be LIFO(Last In First Out)
Mainly the following three basic operations are performed in the stack:
 Push(data): Adds an item in the stack. If the stack is full, then it is said to be an Overflow
condition.
 Pop(): Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be an Underflow condition.
 GetPeek() or GetTop(): Returns top element of stack.
 isEmpty(): Returns true if stack is empty, else false.

Example:
There are many real life examples of stack. Consider the simple example of plates stacked over one
another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has
been placed at the bottommost position remains in the stack for the longest period of time. So, it can be
simply seen to follow LIFO order.
Implementation:
There are two ways to implement a stack:
 Using array
 Using linked list

Array Based Implementation:


Pros: Easy to implement. Memory is saved as pointers are not involved.
Cons: It is not dynamic. It doesn’t grow and shrink depending on needs at runtime.

Linked List Based Implementation:


Pros: The linked list implementation of stack can grow and shrink according to the needs at runtime.
Cons: Requires extra memory due to involvement of pointers.

What we have done so far is nothing different from stacks. We have done insertion of the data in the list
from one side only and removal of the data from the same side too. This exactly is the stack. We use
"Push" for inserting an element and "Pop" for removing an element but in case of stacks the "popped"
element is usually useful so we do return this to main.

Class Definition for Stack:

QUEUES:
Queue is an abstract data structure used for storing homogeneous data in an order. Unlike stacks, a
queue is open at both ends. One end is always used to insert data called Rear and the other is used to
remove or access data called Front of the queue. It follows First-In-First-Out (FIFO) methodology i.e.
the data item inserted first will be accessed first.

Queue Representation
The following diagram given below tries to explain queue representation as data structure
Like stacks a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures.

Basic Operations
Queue operations involve initializing or defining the queue, utilizing it, and then completely erasing it
from the memory. Given below are the basic functions associated with queues
 enqueue()
 dequeue()
 GetFront()
 isfull()
 isempty()
 Size()
 Create ()
 Destroy()

Enqueue: This function is used to insert a data element in the queue. As queue has both ends open so
they maintain two data pointers front and rear. Add data element to the queue location, where the rear
is pointing.

Dequeue: Accessing data from the queue is a process of two tasks − access the data where front is
pointing and remove the data after access

In queue, we always dequeue or access data by using front pointer whereas rear pointer is used to
enqueue (or store) data.
GetFront: This function is used to get the data value present at the front of queue.
Isfull: It checks if the queue is full. It is useful when single dimension array is used to implement queue.
Here we just check for the rear pointer to reach at maximum size to determine that the queue is full.
Isempty: It checks if the queue is empty or not. If the value of front is less than MIN or 0, it tells that the
queue is not yet initialized, hence empty.
Size: This function returns the size of queue
Create: It creates a new queue by initializing variables and allocating space.
Destroy: It deletes the present queue.
Write down two applications of
 Stacks
 Queues
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Practice Tasks will now be displayed!


Lab Number 08
Inheritance
Objective:
Objective of this lab is to learn about:
 Inheritance:
1. Private
2. Public
3. Protected
 Polymorphism

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Inheritance:
 A form of software reuse in which you create a class that absorbs an existing class’s data and
behavior and enhances them with new capabilities.

 In inheritance, a class derives the behavior and structure of another (existing) class.
 Example: Inheritance Hierarchy for University Community Member

Community Member
Single
Employee Student Alumnus Inheritance

Single
Faculty Staff Inheritance

Single
Teacher Administrator Inheritance

Multiple
Administrator Teacher Inheritance
Practical Meaning of Inheritance:
 Data members in the parent are part of the child
 Behavior defined in the parent are part of the child
 Note that private aspects of the parent are part of the child, but are not (directly)
accessible within the child class

Base and Derived classes:


A derived class inherits the members of its base class.

Syntax:
class DerivedClass : kind BaseClass
where,
kind is one of public, private or protected.

Advantages of Inheritance:
 Saves time
 Reuse of proven, debugged, high quality software

Kinds of Inheritance:
 Public (Commonly used)
Public and protected members of the base class remain, respectively, public and protected
members of the derived class.

 Protected
Public and protected members (described later) of the base class are inherited as protected
members of the derived class.

 Private
Public and protected members of the base class are inherited as private members of the
derived class.
In all cases, private members of a base class remain private to the base class and cannot be
accessed directly by a derived class.

Access Specifiers:

The Effects of Inheritance:


 Recall that the constructors of member objects (in composition) are executed before the
constructor of the class containing them. The same can be said about the constructor of the
base class
 Also recall that the destructors of member objects are executed after the destructor of the class
containing them. This is true for the destructor of the base class as well
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.
There can be two types of polymorphism:
1. Static polymorphism
This includes:
a. Overloading
b. Overriding
2. Dynamic polymorphism
This includes:
c. Virtual function

Overloading Functions:
 Same function name is given to different function
 Differ point:
a. The number of parameters
b. The data type of parameters
c. The order of appearance

Example:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
Construct a complete program to run these overloaded functions and write down your output
according to your input.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Overriding Functions:
 If derived class defines same function as defined in its base class, it is known as function
overriding in C++.
 Uses same method name and same type signature.
 Used by a child class to change behavior it inherited from its parent.
 Inheritance is compulsory.
 Must have exactly the same declaration in both base and derived class

Example:

Construct a complete program to run these overridden functions and write down your output
with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Virtual Functions:
Virtual functions are a type of dynamic polymorphism. A virtual function has following
properties:
 It uses pointer
• Compiler performs late binding/run time binding/dynamic binding on this function.
• Compiler gives preference to address in pointer.
Example:
#include<iostream>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print ()
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}
Run this code and write your output with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Pure Virtual Function:


• If a virtual function is equal to 0, it is a pure virtual function
virtual void sound()=0; //pure virtual function
• It has no definition and also called as do nothing function
• Once made it must be used in derived classes (compulsory else error is thrown).
Example:

Run this code and write your output with your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Practice tasks will now be displayed!


Lab Number 09
Operator Overloading

Objective:
Objective of this lab is to learn about:
 Operator Overloading

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Introduction:
In this lab session, we will practice how a mathematical operator like +,-,/ and * can defined between
two objects of some newly defined data types through classes. Previously we have been making
functions like add() and display() but now we will replace them with Operator + and Operator <<
respectively.

Operator Overloading
Operator Overloading is all about defining the functions of a specific mathematical operator between
two objects of some class.

Syntax:
returntype operator<sign> (parameters)
It is important to understand that
1. LHS - object for which member function is called
2. RHS – argument

Example 1:
Let’s implement a simple example Complex variable.
Run this code and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
The new thing in this example is Copy Constructor. Copy Constructor, like initializing constructor,
initializes a newly defined object of class to the values already held by another object. So, after c2, is
created in memory, it will get the same data as c1 has.

Overloading an Operator in existing example:


Did you ever think that display() is not the easy way to display an object of some class while previously
in Algo course you have been using insertion operator for that. Try using cout << sum; rather than using
this display function or try using sum = c1 + c2; instead of .add() function. No it won't work unless we
define the role of these operators for our class. Add following function to the above defined class
Complex.

Try this and write down your observations:


______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Overloading insertion operator:


Let’s overload the insertion operator to display the object data now.

You must have so many questions about the above function but for now, you just need to understand
the concept that insertion operator can be defined for any class.
Try this and write down your observations:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
_____________________

Practice Tasks will now be displayed!


Lab Number 10
Templates

Objective:
Objective of this lab is to learn about:
 Templates

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Introduction:
In this lab session, we will understand what templated functions and templated classes are, how they
can be used and what their advantages are.

Templates:
Templates are powerful features of C++ which allows you to write generic programs. In simple terms,
you can create a single function or a class to work with different data types using templates.

Templates are often used in larger codebase for the purpose of code reusability and flexibility of the
programs.

The concept of templates can be used in two different ways:

 Function Templates
 Class Templates

Function Templates
A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single normal function can
only work with one set of data types.

Declaration of Function Templates:


A function template starts with the keyword template followed by template parameter/s
inside <> which is followed by function declaration.

template <typename T>


T someFunction(T arg)
{
... .. ...
}

In the above code, T is a template argument that accepts different data types (int, float),
and typename is a keyword.

Example:

Class Templates
Like function templates, you can also create class templates for generic class operations.

Sometimes, you need a class implementation that is same for all classes, only the data types used are
different.

Normally, you would need to create a different class for each data type OR create different member
variables and functions within a single class.
However, class templates make it easy to reuse the same code for all data types.

Declaration of class Templates:


template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};

In the above declaration, T is the template argument which is a placeholder for the data type used.

Inside the class body, a member variable var and a member function someOperation() are both of
type T.

Example:
Write down any two advantages of using templates:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________

Practice Tasks will now be displayed!


Lab Number 11
Abstract Classes and Interfaces

Objective:
Objective of this lab is to learn about:
 Abstract Classes and Interfaces

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

Virtual Function:
A virtual function a member function which is declared within base class and is re-defined (Overriden) by
derived class. When you refer to a derived class object using a pointer or a reference to the base class,
you can call a virtual function for that object and execute the derived class’s version of the function.

Properties of Virtual Functions:


 Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.

Pure Virtual Functions:


A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration.

Syntax:
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};

Example:
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};

int main(void)
{
Derived d;
d.fun();
return 0;
}

Run this code and write down its output with your observations:
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________

Abstract Class:
Sometimes implementation of all function cannot be provided in a base class because we don’t know
the implementation. Such a class is called abstract class.
For example, let Shape be a base class. We cannot provide implementation of function draw() in Shape,
but we know every derived class must have implementation of draw(). Similarly an Animal class doesn’t
have implementation of move() (assuming that all animals move), but all animals must know how to
move. We cannot create objects of abstract classes.

Properties of abstract class:


1. A class is abstract if it has at least one pure virtual function.

Example:
In the following example, Test is an abstract class because it has a pure virtual function show().
// pure virtual functions make a class abstract
#include<iostream>
using namespace std;

class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};

int main(void)
{
Test t;
return 0;
}
Run this code and write down your observations:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

2. We can have pointers and references of abstract class type.


Example:
For example the following program works fine.
#include<iostream>
using namespace std;

class Base
{
public:
virtual void show() = 0;
};

class Derived: public Base


{
public:
void show() { cout << "In Derived \n"; }
};

int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
Run this code and write down its output with your observations :
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
3. If we do not override the pure virtual function in derived class, then derived class also becomes
abstract class.
Example:
The following example demonstrates the same.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};

class Derived : public Base { };

int main(void)
{
Derived d;
return 0;
}
Run this code and write down your observations:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
4. An abstract class can have constructors.
Example:
#include<iostream>
using namespace std;

// An abstract class with constructor


class Base
{
protected:
int x;
public:
virtual void fun() = 0;
Base(int i) { x = i; }
};

class Derived: public Base


{
int y;
public:
Derived(int i, int j):Base(i) { y = j; }
void fun() { cout << "x = " << x << ", y = " << y; }
};

int main(void)
{
Derived d(4, 5);
d.fun();
return 0;
}
Run this code and write down its output with your observations:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Interface:
The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class
from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves
only as an interface.

An interface does not have implementation of any of its methods, it can be considered as a collection of
method declarations. In C++, an interface can be simulated by making all methods as pure virtual.

Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions,
which means that it supports the interface declared by the ABC. Failure to override a pure virtual
function in a derived class, then attempting to instantiate objects of that class, is a compilation error.

Practice Tasks will now be displayed!


Lab Number 12
Introduction to QT IDE
For Console Application

Objective
Objective of this lab is to learn about:
 QT IDE

QT installation and first QT console Application


Follow these steps to install and use QT for your first console application:
Step 1) Download Qt Online Installer from the link
https://www.qt.io/download-thank-you?hsLang=en
Step 2) Click Next
Step 3) Login or skip (first check the terms and conditions)

Step 4) Click next


Step 5) Wait for the application to fetch installation data

Step 6) Give installation path and then click next


Step 7) Check MinGW 5.3.0 32 bit under Qt 5.11

Step 8) Check MinGW 5.3.0 under Tools


Step 9) Accept License agreement and set shortcut

Step 10) Click Next to start installation


Step 11) After installation, click finish to launch the Qt Creator Application.

Step 12) Click on New Project to start new project.


Step 13) Click on Application. Then click on Qt Console Application and then hit choose.

Step 14) Set project name and directory and then hit next
Step 15) Set Build System “qmake” and then hit next.

Step 16) Select Desktop Qt version MinGW 32 bit and hit next
Step 17) Then on Summary page click Finish

Step 18) Now your project is created and must look like this.
Step 19) Now can write any C++ code in main.cpp

Step 20) You can click on Debug button on the button left to switch to release mode.
Step 21) There will be 3 folders created. First(1) when you just created your project. Second(2) when you
run your code under Debug Setting. Third (3) when you run code under Release Setting.
Lab Number 13
Introduction to GUI
Application using QT

Objective
Objective of this lab is to learn about:
 Gui Application using QT

Introduction
Qt is a cross-platform framework that can be used to create applications which incorporate rich
Graphical User Interfaces (GUIs). It consists of several libraries, of which Qt Core, Qt GUI, Qt Widgets are
used to design basic standalone desktop applications with GUIs.
To start writing applications, we require the Qt Software Development Kit (SDK), which bundles Qt
Modules, Qt Creator (IDE) and Qt Documentation in a single package, to be installed on our computer.

Creating a New Project:


Follow the steps below to create a blank Qt Application Project:

The resulting window contains a sidebar containing important controls, the file structure of the
project, a window showing open documents, and the color editor, as shown:
File Structure:
The file structure for our project contains the following:
 HelloWorld.pro This is the Qt Project file containing information that allows Qt’s command-line
tool, QMake, to create ‘makefiles’ which are used by compilers to build the applications.
 Headers This directory contains all the header files (.h) for the application.
 Sources This directory contains all the source files (.cpp) for the application.
 Forms This directory contains all the user interface files (.ui) for the application.

Like any CPP application, the starting point for our application is main.cpp, where an instance of
MainWindow object is created, defined in mainwindow.h file. The MainWindow ‘form’ is, hence, the
first screen our end-user sees.

Customizing the UI:


To start adding graphical components to the MainWindow, open Forms > mainwindow.ui file. The
frontend of our application (next page) in the Design Environment shows up.

The following main categories can be found in the Components window, positioned to the left of UI:
 Layout Elements Allow the components to resize according to the user’s screen size.
 Buttons Clickable entities that allow the user to invoke different actions.
 Containers Components that enable us to organize other components on the UI better.
 Input Widgets Allow the user to input dynamic data to the application.
 Display Widgets Allow the application to display output to the user in a presentable manner.
To customize the UI, simply drag and position the different graphical components from the Components
Window onto the UI. Different aspects of each component can be altered from the Properties Window.
First Application:
Frontend
Backend:
Write the following code within void MainWindow::on_btn_showMessage_clicked() in the code editor:

QString message = ui->txt_user_input->text(); //get input text


ui->label->setText(message); //display input text

Execution:
From the menu bar, click on Build > Run to run the application.
Lab Number 14
TREES

Objective:
Objective of this lab is to learn about:
 Trees
1. Searching in a Tree
2. Insertion in a Tree

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from another block
 Spaghetti code and confusing code is not acceptable

TREES:
In computer science, a tree is an abstract model of a hierarchical structure
A (general) tree is a collection of Nodes and edges such that
1. There is a single node from which paths to other nodes emerge; this node is called the root
2. There is a single, unique path to reach any node of the tree

Tree Terminologies:
 Root: node without parent (A)
 Siblings: Children of the Same parent
 Internal node: node with at least one child, Non-leaf nodes are called internal nodes
(A, B, C, F)
 Leaf (aka External node): node without children (E, I, J, K, G, H, D)
 Depth of a node: number of ancestors
 Height of a tree: maximum depth of any node (3)
 If a tree is a collection of N nodes, then it has N-1 edges.
Binary tree
A finite set of elements that is either empty or is partitioned into three disjoint subsets.
 The first subset contains a single element called the root of the tree
 The other two subsets are themselves binary trees, called the left and right sub-trees of the
original tree
 Each element of a binary tree is called a node

We call the children of an internal node left child and right child
Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree
whose root has an ordered pair of children, each of which is a binary tree

Binary Search Tree:


A particular form of binary tree, such that for any node in the tree containing data value x:
– The right sub-tree has data values > x
– The left sub-tree has data values < x

Pointer-Based Implementation of a Binary (Search) Tree:


Structure of Node:
struct Node //node in the Tree
{
int data; //data portion
Node * Left; //pointer to left child
Node * Right; //pointer to right child
};

Searching a Node in a binary search tree:


 To search a specific node in a binary search tree one has to traverse through the tree until the
specific node is found.
 If the value of x, to be found, is less than the parent node then one should move to the left child.
 If the value of x, to be found, is greater than the parent node then one should move to the right
child.
 If the value of x, to be found, is equal to the parent node then it means that the node is found.
 Otherwise it means that x is not present in the tree.
Example:

Question:
Write down the pseudo Code to search a specific node in a tree.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________

Insertion:
To insert a new node following steps should be followed:
1. Create a new node
2. Check if the tree is empty
3. Otherwise traverse through the tree in such a way that
 if the coming data is less than the root data then move to the left child
 if the coming data is greater than the root data then move to the right child
 else if the number matches the root data then the new node would not be inserted.
4. Traverse until you reach the leaf node.
5. Then insert the new node.

Example:
Question:
Write down the pseudo Code to insert a specific node in a tree.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________

Practice tasks will now be displayed


Lab Number 15
TREES
Objective:
Objective of this lab is to learn about:
 Trees
i) Deletion of a node in a binary Search Tree
ii) Tree Traversal

Software Used:
 Notepad++
 Command Prompt

Important Notes
 Use meaningful variable names
 Indent your program so that statements inside a block can be distinguished from
another block
 Spaghetti code and confusing code is not acceptable

TREES:
In computer science, a tree is an abstract model of a hierarchical structure
A (general) tree is a collection of Nodes and edges such that
1. There is a single node from which paths to other nodes emerge; this node is called the root
2. There is a single, unique path to reach any node of the tree

Tree Terminologies:
 Root: node without parent (A)
 Siblings: Children of the Same parent
 Internal node: node with at least one child, Non-leaf nodes are called internal nodes
(A, B, C, F)
 Leaf (aka External node): node without children (E, I, J, K, G, H, D)
 Depth of a node: number of ancestors
 Height of a tree: maximum depth of any node (3)
 If a tree is a collection of N nodes, then it has N-1 edges.
Binary tree
A finite set of elements that is either empty or is partitioned into three disjoint subsets.
 The first subset contains a single element called the root of the tree
 The other two subsets are themselves binary trees, called the left and right sub-trees of the
original tree
 Each element of a binary tree is called a node
We call the children of an internal node left child and right child
Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree whose
root has an ordered pair of children, each of which is a binary tree

Binary Search Tree:


A particular form of binary tree, such that for any node in the tree containing data value x:
– The right sub-tree has data values > x
– The left sub-tree has data values < x

Pointer-Based Implementation of a Binary (Search) Tree:


Structure of Node:
struct Node //node in the Tree
{
int data; //data portion
Node * Left; //pointer to left child
Node * Right; //pointer to right child
};

Deletion of a node in a Binary Search Tree:


There are three cases for deletion in BST:
• Deletion of Leaf with No Child.
• Deletion of node with 1 Child.
• Deletion of node with 2 Child.
Deletion of Leaf (No Children):
1. Search for the node that needs to be deleted.
2. Node to be deleted is either on left side or on right side of its parent node.
3. If node to be deleted is on left side of its parent node then mark Left side of parent node to null.
4. If node to be deleted is on right side of its parent node then mark Right side of parent node to null.
Example:

Deletion on node with one Child:


1. Search for the node that needs to be deleted.
2. Node to be deleted is either on left side or on right side of its parent node.
3. Node to be deleted has only child present that can be on left side or right side.
4. If node to be deleted has left child present, then directly connect its parent node to left child of the
node to be deleted.
5. If node to be deleted has right child present, then directly connect its parent node to right child of
the node to be deleted.
6. In this way node to be deleted will be deleted from the Tree and the parent node will be directly
connected to child of the node to be deleted.

Example:
Deletion of Node with two Children:
1. Find a minimum value in the right subtree;
2. Replace value of the node to be removed with the found minimum. Now, right subtree contains
a duplicate!
3. Apply delete() to the right subtree to delete a duplicate.
Example:

Question:
Can you think of any other way to delete a node with two children?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________

Traversal:
When traversing any Binary Tree, the Algorithm has Three Choices of When to Visit a Node root:
 Preorder Traversal
1) Visit the root
2) Traverse the Left subtree in Preorder
3) Traverse the Right subtree in Preorder
 Inorder Traversal
1) Traverse the Left subtree in Inorder
2) Visit the root
3) Traverse the Right subtree in Inorder
 Postorder Traversal
1) Traverse the Left subtree in Postorder
2) Traverse the Right subtree in Postorder
3) Visit the root

Example:
• Preorder traversal -- A B D H E I C F J K G
• Postorder traversal -- H D I E B J K F G C A
• In-order traversal -- D H B I E A J F K C G
Question:
Write down the pseudo code for inorder traversal through a binary search tree?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________
_________________________________________________________________________________________________________

Practice tasks will now be displayed!


Lab Number 16
Project

Objective:
In this lab you can work on your assigned course project. The project for the course is required to be
chosen after the first sessional exam. The guidelines are as follows:

Project Guidelines:
1. Students are allowed to choose the project on their own.
2. Project will be done in groups
3. The project group members should not be more than 2.
4. Project should not be related to banking and finance.
5. Project should be related to the fields of mechatronics, automation, gaming or embedded
systems.
6. The students can use any open source library for the project.
7. Project Code should be a C++ code.
8. OpenCV and OpeGLl projects are encouraged.
9. Students can choose from open source code, but code explanation, dataflow diagram and
flowcharts are required.
10. Three presentations will be held: Project defense, progress presentation and Final Presentation.
11. Deadlines for the project presentations will be conveyed soon.

Das könnte Ihnen auch gefallen