Chapter 1 General Overview DSA
Chapter 1 General Overview DSA
AND
ALGORITHM
https://sites.google.com/a/quest.edu.pk/dr-irfana-memon/lecture-slides
1
Upon completion of this course, students will be able to achieve
following objectives:
2
A series of lectures reviewing a number of basic concepts:
Algorithms and Data Structures
Static Data Structures
Searching Algorithms
Sorting Algorithms
List implementation through Array
ADT: Stack
ADT: Queue
Dynamic Data Structures (Linear)
Linked List (Linear Data Structure)
Dynamic Data Structures (Non-Linear)
Trees, Graphs, Hashing
3
NO TOPIC CLO
01 A General Overview CLO1
02 Introduction to Data Structures and Algorithm CLO1
03 String Processing CLO1
04 Abstract Data Types CLO1
05 Linked list CLO1
06 Stack and Queue CLO1
07 Recursion CLO1
08 Complexity Analysis CLO2
09 Sorting and Searching techniques CLO2
10 Trees CLO2
11 Graph CLO3
12 P & NP CLO3
4
5
Schaum's Outline Series, Theory and problems of Data Structures
by Seymour Lipschutz (Latest Edition)
Data Structures using C and C++, by A.Tenenbaum, Augenstein,
and Langsam (Latest Edition)
Principles Of Data Structures Using C And C++ by Vinu V Das
(Latest Edition)
Sams Teach Yourself Data Structures and Algorithms in 24 Hours,
Lafore Robert (Latest Edition)
Data structures and algorithms, Alfred V. Aho, John E. Hopcroft.
(Latest Edition)
Standish, Thomas A., Data Structures, Algorithms and Software
Principles in C, Addison-Wesley (Latest Edition)
Data Structures & Algorithm Analysis in C++, Weiss Mark Allen
(Latest Edition)
6
Assignments
Class participation
Class tests
Projects
7
There are no marks on attendance
It is
MANDATORY
8
You will be using the C++ programming language in this
course
9
This course does not teach C++ programming
10
11
A programming language is a language with a well-
defined syntax (grammar), type system, and semantics
that can be used to implement a set of algorithms.
12
Pascal
Qbasic
Visual basic
C language
C++
Fortran
Java
Haskell
13
Basic differences is:
Program is written in programming language
Algorithm is in English like pseudo-code language.
14
A Brief Overview of C++
15
The C programming language was designed by Dennis
Ritchie at Bell Laboratories in the early 1970s
Influenced by
ALGOL 60 (1960),
CPL (Cambridge, 1963),
BCPL (Martin Richard, 1967),
B (Ken Thompson, 1970)
16
C++ extends C
Provides capabilities for object-oriented programming
Objects are reusable software components that model
18
Case sensitive
Typed language
Low level access or more close to hardware.
Flexible in terms of User Data Type (UDT)
Suitable for most system programming tasks.
Compatibility with C++.
Pointer implementation.
Standard Library.
19
20
Flow chart
Algorithm to print “Hello World”
Start
1. Start
2. Write: “Hello World”
Write “Hello World”
3. End
End
21
22
Variables may be the most fundamental aspect of any
computer language.
A variable is a space in the computer’s memory set
aside for a certain kind of data and given a name for
easy reference.
Therefore variables are used so that the same space in
memory can hold different values at different times.
(But one value at a time).
Variable names correspond to locations in computer
memory.
Every variable has a name, type and value.
Data values processed in the program are stored in
memory locations and referenced through variables.
23
In C++, variable names are built from:
the letters of the alphabet (A-Z, or a-z)
the digits 0 through 9
the underscore. (no other special characters!)
A variable name must start with a letter or an underscore.
Spaces are not allowed in variable name.
Only the 32 characters of a variable name are significant.
Identifiers are case sensitive: sum≠SUM≠Sum≠sUM
A variable name must not be the same as a reserved word.
24
Certain words have a special meaning to the
C or C++ compiler.
They are called reserved words or keywords.
We should not try to use these words as names
of variables or function names in a program.
The keyword list for C contains 32 words .
25
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
26
Valid variable names:
totalArea _main
counter1 isEmpty
Count_trees pNuts
temp_in_F m_size
27
Valid variable names:
totalArea _main
counter1 isEmpty
Count_trees pNuts
temp_in_F m_size
Invalid variable names:
$product int main not-this
total% 19 3rd Student score
28
Valid variable names:
totalArea _main
counter1 isEmpty
Count_trees pNuts
temp_in_F m_size
Invalid variable names:
$product int main not-this
total% 19 3rd Student score
Legal, badly-chosen variable names:
l11 (is it L11, L1L, LL1, or LLL?)
x (what does it mean?)
maximum_number_of_students_in_my_class
a23456789_123456789_123456789_12345678
29
Programming languages store and process data in
various ways depending on the type of the data;
consequently, all data read, processed, or written by
a program must have a type.
A data type is
A set of values, and
A set of operations on those values
30
A data type is used to:
determines how much storage space is allocated
to variables.
Identify the type of a variable when the variable is
declared.
Identify the type of the return value of a function
Identify the type of a parameter expected by a
function.
31
Fundamental or Built-in data types
int, char, double, float, void
Enumeration .
32
Character combinations consisting of a backslash
(\) followed by a letter are called "escape
sequences."
To represent a newline, single quotation mark, or
certain other characters, you must use escape
sequences.
Escape sequences are non-printing characters.
\n new line
\t tab
\r carriage return
\a alert
\\ backslash
\” double quote
33
cout is used for displaying data on the screen.
The operator << called as insertion operator or put
to operator.
The Insertion operator can be overloaded.
Insertion operator is similar to the
printf() operation in C.
cout is the object of iostream class.
Data flow direction is from variable to output device.
Multiple outputs can be displayed using cout.
34
cin is used for accepting data from the keyboard.
The operator >> called as extraction operator or get
from operator.
The extraction operator can be overloaded.
Extraction operator is similar to the scanf() operation in
C.
cin is the object of istream class.
Data flow direction is from input device to variable.
Due to the use of input statement, the program will wait
till the user type some input and that input is stored in
variable.
Multiple inputs can be accepted using cin.
35
36
#include<iostream.h>
#include<conio.h>
void main(void)
{
clrscr();
int number1;
int number2;
cout<<"Enter First Number: ";
cin>>number1; //accept first number
cout<<"Enter Second Number: ";
cin>>number2; //accept first number
cout<<"Addition : ";
cout<<number1+number2; //Display Addition
getch();
} 37
Control Structures/
Decision making statements
38
Sequential control structure
Selection control structure
if statement (one-way)
if-else statement (two-way)
switch statement (multi-way)
Repetitive control structure
for loop
while loop
do-while loop
39
1. Write a C++ program, that ask user to enter the
temperature in Fahrenheit scale, convert it into
centigrade and print the temperature in
centigrade.
2. Write a C++ program to build simple calculator
to add, subtract, multiply, and divide using
switch statement
40
In Programming; we frequently need to perform
an action more than once (repetitively).
The mechanism that meets this need is the
“Loop”.
Repeating some portion of the program
either specified number of times or until a
particular condition is being satisfied.
Three methods (loops) by which we can repeat
the portion of program:
Using a for statement
Using a while statement
Using a do-while statement
41
42
The while loop provides a mechanism for
repeating C statements until a condition is true.
Syntax:
While (control expression)
program statement ;
The while statement works as follows:
1) Control expression is evaluated.
2) If it is FALSE, skip over the loop.
3) If it is TRUE, loop body is executed.
4) Go back to step 1
43
The do while statement is a
variant of the while loop in
which the condition test is
performed at the “bottom” of
the loop.
This guarantees that the loop is
executed at least once whether
the condition is TRUE or FALSE.
The syntax of the do while
statement is
do
program statement;
while (control expression) ;
and it works as follows
1) The body of the loop is executed.
2) The control expression is
evaluated (“exit condition”).
3) If it is TRUE, go back to step 1.
4) If it is FALSE, exit loop. 44
The for Loop is frequently used, usually where the
loop will be traversed a fixed number of times. It is
very flexible.
The while Loop keeps repeating an action until an
associated test returns false. This is useful where the
programmer does not know in advance how many
times the loop will be traversed.
The do While Loop is similar to the While Loop, but
the test occurs after the loop body is executed. This
ensures that the loop body is run at least once.
45
1. Write a C++ program, to generate Fibonacci
series up to 50 (using for-loop).
2. Write C++ program to display all prime
numbers between Two interval entered by user
(using do-while loop).
46
Arrays
47
An array is a group of items that can be identified as
similar because they are of the same nature
(collection of homogenous items).
Multi-dimensional arrays.
48
• A one-dimensional array is a list of related
variables.
• The general form of a one-dimensional array
declaration is: type variable_name[size]
• type: base type of the array, determines the
data type of each element in the array
• size: how many elements the array will hold
• variable_name: the name of the array
49
• A two-dimensional array is a list of one-dimensional
arrays.
• To declare a two-dimensional integer array two_dim of
size 10,20
• we would write: int matrix[3][4]; This corresponds to a
table with 3 rows and 4 columns.
50
• C++ allows arrays with more than two dimensions.
51
Write a C++ program, to store 5 numbers entered by
user in an array and display first and last number only.
Write C++ program to generate the following matrix.
52
53
The Top-down design approach is based on dividing the main
problem into smaller tasks which may be divided into simpler
tasks, then implementing each simple task by a subprogram or a
function
A C++ function or a subprogram is simply a chunk of C++ code
that has
A descriptive function name, e.g.
computeTaxes to compute the taxes for an employee
55
Although C++ is shipped with a lot of standard
functions, these functions are not enough for all users,
therefore, C++ provides its users with a way to define
their own functions (or user-defined function)
56
Generally speaking, we define a C++ function in two steps
(preferably but not mandatory)
Step #1 – declare the function signature in either a header
file (.h file) or before the main function of the program
Step #2 – Implement the function in either an
implementation file (.cpp) or after the main function
A C++ function consists of two parts
The function header, and
The function body
The function header has the following syntax
<return value> <name> (<parameter list>)
The function body is simply a C++ code enclosed between { }
57
#include <iostream>
using namespace std;
double computeTaxes(double);
int main()
{
double income,taxes;
cout<<"enter income =";
cin>>income;
// Compute Taxes
taxes=computeTaxes(income);
cout<<"taxes are: "<<taxes;
}
double computeTaxes(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
58
59
A Structure is a collection of related data items, possibly of
different types.
A structure type in C++ is called struct.
A struct is heterogeneous in that it can be composed of data of
different types.
Individual components of a struct type are called members (or
fields).
Members can be of different types (simple, array or struct).
The declarations of the structure members
Day, month, and year (enclosed in braces)
Example:
struct Date {
int day; The “Date” structure
int month; has 3 members,
int year;
}; day, month & year.
60
Once a structure variable has been struct Date {
defined, its members can be accessed int month;
using dot operator. int year;
Here’s how the first member is given
a value: };
A.month= 10;
The structure member is written in void main(void)
three parts: the name of the structure
variable (A); {
The dot operator, which consists of a //initialize variable
period (.);
member name (month) Date A;
This means “the month member of }
Date.”
The real name of the dot operator is
member access operator, but of
course no one wants to use such a
lengthy term.
61
62
63
A Pointer provides a way of accessing a
variable without referring to the variable
directly.
The mechanism used for this purpose is the
address of the variable.
A variable that stores the address of another
variable is called a pointer variable.
64
Pointer
Pointer Variables
Dynamic Memory Allocation
Functions
65
Pointer variable: A variable that holds an
address
Can perform some tasks more easily with an
address than by accessing memory via a
symbolic name:
Accessing unnamed memory locations
Array manipulation
etc.
66
To operate on data stored in an array
To enable convenient access within a
function to large blocks data, such as arrays,
that are defined outside the function.
To allocate space for new variables
dynamically–that is during program
execution
67
The class is the cornerstone of C++
It gives the C++ its identity from C
It makes possible encapsulation, data hiding and
inheritance
Class:
Consists of both data and methods
Defines properties and behavior of a set of entities
Object:
An instance of a class
A variable identified by a unique name
68
Header class Rectangle
class class_name {
{ private:
permission_label:
int width;
member;
Body int length;
permission_label:
member; public:
... void set(int w, int
}; l);
int area();
}; 69
Abstract the common attributes of a group of
entities, their values determine the state of an
object
Can be of any type, built-in or user-defined
non-static data member
Each class object has its own copy
Cannot be initialized explicitly in the class body
Can be initialized with member function, or class
constructor
static data member
Acts as a global object, part of a class, not part of an
object of that class
One copy per class type, not one copy per object
Can be initialized explicitly in the class body
70
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
count
int length;
static int count; r1 r2
public: width width
length length
void set(int w, int l);
int area(); width
r3 length
}
71
Used to
access the values of the data members
(accessor)
perform operations on the data members
(implementor)
Are declared inside the class body, in the
same way as declaring a function
Their definition can be placed inside the
class body, or outside the class body
Can access both public and private
members of the class
Can be referred to using dot or arrow
member access operator
72
class Rectangle
{
private:
int width, length;
class name
public:
void set (int w, int l);
int area() {return width*length; } member function
name
}
74
class Time
{
private : function declaration
int hrs, mins, secs ;
public :
void Write ( ) const ; function definition
};
75
Information hiding
To prevent the internal representation from direct access
from outside the class
Access Specifiers
public
may be accessible from anywhere within a program
private
may be accessed only by the member functions, and friends of this
class, not open for nonmember functions
protected
acts as public for derived classes (virtual)
behaves as private for the rest of the program
Difference between classes and structs in C++
the default access specifier is private in classes
the default access specifier is public in structs
76
class Time
{
public :
void Set ( int hours , int minutes , int seconds ) ;
void Increment ( ) ;
void Write ( ) const ;
Time ( int initHrs, int initMins, int initSecs ) ; // constructor
Time ( ) ; // default constructor
private :
int hrs ;
int mins ;
int secs ;
};
77
Time class
Set
Private data:
Increment
hrs
Write
mins
Time secs
Time
78
The default access specifier is private
The data members are usually private or protected
A private member function is a helper, may only
be accessed by another member function of the
same class (exception friend function)
The public member functions are part of the class
interface
Each access control section is optional, repeatable,
and sections may occur in any order
79
Object:
a variable or an instance of a class
Declaration of an Object
Initiation of an Object
80
OBJECT
set of methods
Operations (public member functions)
81
class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
}
82
#include <iostream.h> // member function definitions
int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display();
} 83
Class canbe considered as a user-defined data
type, while an object is just a variable of certain
class.
84
Wish
You
Good Luck
85