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

DSA Week1

The document provides an overview of prerequisite programming concepts for a data structures and algorithms course. It discusses basics of computer programming including programming languages, machine code, assembler programming, and higher-level languages. It also covers C++ environments, basic program construction in C++, preprocessor directives, header files, and functions. The document is intended to review prerequisite knowledge before learning about data structures and algorithms.

Uploaded by

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

DSA Week1

The document provides an overview of prerequisite programming concepts for a data structures and algorithms course. It discusses basics of computer programming including programming languages, machine code, assembler programming, and higher-level languages. It also covers C++ environments, basic program construction in C++, preprocessor directives, header files, and functions. The document is intended to review prerequisite knowledge before learning about data structures and algorithms.

Uploaded by

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

Data Structures &

Algorithms
Week-1
Sessional Work
• 2 Quizzes
• 4 Assignments
• Each Group Presentation
• Group Constraint(Not more than 5 students)
Warning
Consider it as FINAL NOTICE
Threat
• Don’t approach me for GPA.
Contents

• Pre requisite programming concepts


• Introduction to Data Structures
• Introduction to Algorithms
Pre requisite programming concepts

Basics of Computer Programming

• Computer Programming is the


art of making a computer do
what you want it to do.
• A computer program is simply a
set of instructions to tell a
computer how to solve a
particular problem.
Pre requisite programming concepts

Basics of Computer Programming


• It's rather like a recipe:
• a set of instructions to tell a cook how to
make a particular dish.
• It describes the ingredients (the data) and the
sequence of steps (the process) needed to
convert the ingredients into the cake or
whatever.
Pre requisite programming concepts

Programming Language
• Just as you speak to a friend in a language so you
'speak' to the computer in a language. The only
language that the computer understands is called
binary.
• Binary is unfortunately very difficult for humans to
read or write so we have to use an intermediate
language and get it translated into binary for us.
Pre requisite programming concepts

Programming Language

• This is rather like watching the


American and Russian presidents
talking at a meeting.
• One speaks in English, then
an interpreter repeats what
has been said in Russian.
The other replies in Russian
and the interpreter again
repeats the sentence, this
time in English.
Pre requisite programming concepts

Programming Language
• Surprisingly enough the thing that translates our
intermediate language into binary is also called
an interpreter.
• And just as you usually need a different
interpreter to translate English into Russian than
you do to translate Arabic into Russian so you
need a different computer interpreter to translate
Python into binary from the one that translates
VBScript into binary.
Pre requisite programming concepts

Machine Code Programming


• The very first programmers actually had to enter the
binary codes themselves, this is known as machine code
programming and is incredibly difficult.

• The next stage was to create a translator that simply


converted English equivalents of the binary codes into
binary so that instead of having to remember that the
code 001273 05 04 meant add 5 to 4 programmers could
now write ADD 5 4.
Pre requisite programming concepts

Assembler Programming
• This very simple improvement made life much
simpler and these systems of codes were really
the first programming languages, one for each
type of computer. They were known as
assembler languages and Assembler
programming is still used for a few specialized
programming tasks today.
• It was still very difficult and took a lot of
programming effort to achieve even simple tasks.
Pre requisite programming concepts

Higher level computer languages


• Gradually computer scientists developed
higher level computer languages to make the
job easier. This was just as well because at
the same time users were inventing ever
more complex jobs for computers to solve!
Pre requisite programming concepts

Higher level computer languages

• This competition between the computer


scientists and the users is still going on
and new languages keep on appearing.
Pre requisite programming concepts

Points to remember

• Programs control the computer


• Programming languages allow us to 'speak'
to the computer at a level that is closer to
how humans think than how computers
'think'
Pre requisite programming concepts

Points to remember
• Basically a programmer writes a program in a high
level language which is interpreted into binary that
the computer understands.
• In technical speak the programmer generates source
code and the interpreter generates object code.
Sometimes object code has other names like: binary
code or machine code.
Pre requisite programming concepts

C++, a computer language that supports object


oriented programming

• Why do we need OOP?


• What does it do that traditional languages such as C,
Pascal, and BASIC don’t?
• Two key concepts in OOP are objects and classes. What
do these terms mean?
• What is the relationship between C++ and the older C
language?
Pre requisite programming concepts

Why do we need OOP?


• Limitations in earlier approaches to programming.

• To appreciate what OOP does, we need to


understand what these limitations are and how they
arose from traditional programming languages.
Pre requisite programming concepts

Procedural Languages
• C, Pascal, FORTRAN, and similar languages
• Each statement in the language tells the computer to
do something
• Get some input,
• Add these numbers,
• Divide by six,
• Display that output.
• A program in a procedural language is a list of
instructions.
Pre requisite programming concepts

Division into Functions


• When programs become larger, a single list of
instructions becomes unwieldy.
• function was adopted as a way to make
programs more comprehensible to their
human creators.
• A procedural program is divided into functions, and
each function has a clearly defined purpose.
Pre requisite programming concepts

Division into Functions


• The idea of breaking a program into functions can be further extended
by grouping a number of functions together into a larger entity called a
module.
• Dividing a program into functions and modules is one of the
cornerstones of structured programming.
• This influenced programming organization for several decades before
the advent of object-oriented programming.
Pre requisite programming concepts

Basics of a typical C++ Environment

It consist of 6 phases
• Editor
• Preprocessor
• Compilers
• Linkers
• Loaders
• Execute
Pre requisite programming concepts
Program is created in the
Editor Disk editor and stored on disk.
Preprocessor program
Preprocessor Disk processes the code.
Compiler creates
Compiler Disk object code and stores
it on disk.
Linker Disk Linker links the object
code with the libraries
Primary Memory
Loader
Loader puts program
in memory.
Disk ..
..
..

Primary Memory
CPU takes each
CPU instruction and
executes it, possibly
storing new data
..
..
values as the program
..
executes.
Pre requisite programming concepts

Basic Program Construction


• Compilers take source code and transform it into
executable files, which your computer can run as it
does other programs.
• Source files are text files (extension .CPP)
• Executable files have the .EXE extension
Pre requisite programming concepts

Your First Program


Pre requisite programming concepts

Preprocessor Directives
• The first two lines that begin the program are preprocessor directives.
e.g., #include <iostream.h>
#include<conio.h>
• It isn’t a program statement
• It isn’t a part of a function body
• It does not end with a semicolon
Pre requisite programming concepts

Program statement vs preprocessor directive


• Program statements are instructions to the computer to do something,
such as adding two numbers or printing a sentence.
• A preprocessor directive, on the other hand, is an instruction to the
compiler.
• A part of the compiler called the preprocessor deals with these
directives before it begins the real compilation process.
Pre requisite programming concepts

Program statement vs preprocessor directive


• The preprocessor directive #include tells the
compiler to insert another file into your source file.
• The type file usually included by #include is called a
header file.
Pre requisite programming concepts

Header Files
• iostream is an example of a header file.
• It’s concerned with basic input/output operations,
and contains declarations that are needed by the
cout identifier and the << operator.
• Without these declarations, the compiler won’t
recognize cout and will think << is being used
incorrectly
Pre requisite programming concepts

Functions
• The parentheses following the word main are the
distinguishing feature of a function.
• Without parentheses compiler would think that main
refers to some other program element.
• The word int preceding the function name indicates
that this particular function has a return value of
type int.
Pre requisite programming concepts

Braces and the Function Body


• The body of a function is surrounded by braces
(sometimes called curly brackets).
• Every function must use this pair of braces around the
function body.
• In this example there are only three statements in the
function body:
• the line starting with cout, the line starting with getch and the
line starting with return.
• However, a function body can consist of many statements.
Pre requisite programming concepts

Program Statements
• There are three statements in the FIRST program: the line
• cout << “Hello World: My first C++ program”;
• getch();
• and the return statement return 0;
Pre requisite programming concepts

Output Using cout


• The identifier cout (pronounced “C out”) is actually an object. It is
predefined in C++ to correspond to the standard output stream.
• The operator << is called the insertion or put to operator.
• It directs the contents on its right to the object on its left.
• In our example it directs the string constant “Hello World: My first C++
program” to cout, which sends it to the display.
Pre requisite programming concepts
Pre requisite programming concepts

String Constants
• The phrase in quotation marks, “Hello World: My
first C++ program”, is an example of a string
constant.
• Its value is set when the program is written, and it
retains this value throughout the program’s
existence.
Pre requisite programming concepts

Program Statements

• The first statement tells the computer to display the


quoted phrase.
• A semicolon signals the end of the statement.
• If you leave out the semicolon, the compiler will
signal an error.
Pre requisite programming concepts

Program Statements
• getch() apart from holding the screen or waiting for a character to be
entered to exit the output screen , it also print the input given by the
user.
• The last statement in the function body is return 0;
• This tells main() to return the value 0 to whoever called it, in this case
the operating system or compiler. The value 0 indicates that the
program had terminated successfully.
Pre requisite programming concepts

Comments
• They help the person writing a program, and
anyone else who must read the source file,
understand what’s going on.
• The compiler ignores comments
Pre requisite programming concepts

Comment Syntax
• Comments start with a double slash symbol (//) and terminate at the
end of the line.
Pre requisite programming concepts

Alternative Comment Syntax


Pre requisite programming concepts

Outputs
Pre requisite programming concepts

Memory Concepts
• Variable names
• Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
• When new value placed into variable, overwrites previous value

• std::cin >> integer1; integer1 45

• Assume user entered 45


integer1 45
integer2 72
• std::cin >> integer2;
• Assume user entered 72
integer1 45
integer2 72
• sum = integer1 + integer2;
sum 117
43
Pre requisite programming concepts

Increment Operators
• The ++ operator increments (adds 1 to) its argument.
• Normal way:

• Using arithmetic assignment operator

• Using Increment operator


Pre requisite programming concepts

The Decrement (--) Operator


• The decrement operator, --, behaves very much like the increment
operator, except that it subtracts 1 from its operand.
• It too can be used in both prefix and postfix forms.
• Example
• count--
• --count
Pre requisite programming concepts

Arithmetic Operators
• Arithmetic calculations
• * : Multiplication
• / : Division
• Integer division truncates remainder
• 7 / 5 evaluates to 1
• % : Modulus operator returns remainder
• 7 % 5 evaluates to 2

Operator(s) Operation(s) Order of evaluation (precedence)

() Parentheses Evaluated first. If the parentheses are nested, the


expression in the innermost pair is evaluated first. If
there are several pairs of parentheses “on the same level”
(i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Evaluated second. If there are several, they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

46
Pre requisite programming concepts

Relational Operators
• A relational operator compares two values.
• The values can be any built-in C++ data type, such as char, int, and
float or they can be user-defined classes.
• The comparison involves such relationships as equal to, less than, and
greater than.
• The result of the comparison is true or false; for example, either two
values are equal (true), or they’re not (false).
Pre requisite programming concepts
Decision Making: Equality and Relational
Operators
Standard algebraic C++ equality Example Meaning of
equality operator or or relational of C++ C++ condition
relational operator operator condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y

 >= x >= y x is greater than or equal to y

 <= x <= y x is less than or equal to y

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y

48
Pre requisite programming concepts

Example
Pre requisite programming concepts
OUTPUT
Pre requisite programming concepts

Example Expressions
Pre requisite programming concepts

Logical Operators
• Used as conditions in loops, if statements
• && (logical AND)
• true if both conditions are true
if ( gender == 1 && age >= 65 )
++seniorFemales;

• || (logical OR)
• true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;

52
Pre requisite programming concepts

Logical Operators
• ! (logical NOT, logical negation)
• Returns true when its condition is false, & vice versa
if ( !( grade == sentinelValue ) )
cout << "The next grade is " << grade << endl;
Alternative:
if ( grade != sentinelValue )
cout << "The next grade is " << grade << endl;

53
Pre requisite programming concepts
Confusing Equality (==) and Assignment (=)
Operators
• Common error
• Does not typically cause syntax errors
• Aspects of problem
• Expressions that have a value can be used for decision
• Zero = false, nonzero = true
• Assignment statements produce a value (the value to be assigned)

if == was replaced with =


if ( payCode = 4 )
cout << "You get a bonus!" << endl;
What happens?

54
Control Structures
• Sequential execution
• Statements executed in order
• Transfer of control
• Next statement executed not next one in sequence
• Structured programming – “goto”-less programming
• 3 control structures to build any program
• Sequence structure
• Programs executed sequentially by default
• Selection structures
• if, if/else, switch
• Repetition structures
• while, do/while, for

55
Pre requisite programming concepts

if/else Selection Structure


• Ternary conditional operator (?:)
• Three arguments (condition, value if true, value if false)
• Code could be written:
cout << ( grade >= 60 ? “Passed” : “Failed” );

Condition Value if true Value if false

false true
grade >= 60

print “Failed” print “Passed”

56
Pre requisite programming concepts

switch Multiple-Selection Structure


• switch
• Test variable for multiple values
• Series of case labels and optional default case

switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or == value3
statements
break;

default: // taken if none matches


statements
break;
} 57
Pre requisite programming concepts

Loops
• Loops cause a section of your program to be
repeated a certain number of times.
• The repetition continues while a condition is true a
certain number of times.
• When the condition becomes false, the loop ends and
control passes to the statements following the loop.
Pre requisite programming concepts

Kinds of Loop
• There are three kinds of loops in C++:
• for loop,
• while loop,
• do loop.
Pre requisite programming concepts

Pointers
• Variables used in a program can be considered as boxes that are
never empty.
• They are filled with some content either by the programmer or, if
uninitialized, by the operating system.
• A variable has at least two attributes: the content or value and the
location of the box or variable in computer memory.
• This content can be a number, a character, or a compound item such
as a structure or union.
• However, this content can also be the location of another variable;
variables with such contents are called pointers.
• Pointers are usually auxiliary variables that allow us to access the
values of other variables indirectly.
Pointers
Pre requisite programming concepts

int i=15,j,*p,*q;
i and j are numerical
variables and p and q are
pointers to numbers
Pre requisite concepts
• Primitive/Built-in Data types
int
char
boolean
string
float
long
double
Pre requisite concepts
Encapsulation
• Object-oriented programming (OOP) revolves around the concept of
an object.
• A class is a template in accordance to which objects are created.
• Information-hiding principle

• What are the access modifiers???


Pre requisite concepts
Access Modifiers/Specifiers
Public
Private
Protected
Pre requisite concepts
Inheritance
int main()
{
BaseClass obj;
obj.f();
obj.g();
obj.h();
}

Find Error????
Pre requisite concepts
Polymorphism
Polymorphism refers to the ability of acquiring many forms.

• Virtual Functions
• Function Overloading
Mid Term Examination
• Introduction to Data Structures and Algorithms;
• Complexity Analysis of Algorithms;
• Arrays;
• Sorting Algorithms: Insertion Sort, Selection Sort, Bubble Sort, Shell
Sort, Heap Sort, Quick Sort, Merge Sort, Radix Sort, Bucket Sort;
• Linked Lists: Singly Linked Lists, Doubly Linked Lists, Circular List;
• Stacks, Queues, and Priority Queue;
• Recursion: Function call and Recursion Implementation, Tail
Recursion, Non-tail Recursion, Indirect Recursion, Nested Recursion,
Backtracking.
PAPP
•Problem
•Algorithm
•Program
•Process
DATA STRUCTURE
Data Structure
A data structure is a data organization, management and storage
format that enables efficient access and modification.
Data structures help us to organize the data in the computer, resulting
in more efficient programs.

STUDENT RECORD FILE

Examples:
Array, Lists, Stacks, Queue, Trees, Graphs
Need for Data Structures
 Data structures organize data  more efficient
programs.
 More powerful computers  more complex
applications.
 More complex applications demand more
calculations.
Organizing Data
 Any organization for a collection of records that
can be searched, processed in any order, or
modified.
 The choice of data structure and algorithm can
make the difference between a program running
in a few seconds or many days.
Efficiency
 A solution is said to be efficient if it solves the problem within its
resource constraints.
• Space
• Time

 The cost of a solution is the amount of resources that the


solution consumes.
Selecting a Data Structure
Select a data structure as follows:
1. Analyze the problem to determine the resource constraints a
solution must meet.
2. Determine the basic operations that must be supported.
Quantify the resource constraints for each operation.
3. Select the data structure that best meets these requirements.
Basic Data Structure

Basic Data Structures

Linear Data Structures Non-Linear Data Structures

Arrays Linked Lists Stacks Queues Trees Graphs Hash Tables


array

Linked list

queue
tree stack
Types of Data Structure
• Linear: In Linear data structure, values are arrange in linear
fashion.
• Array: Fixed-size
• Linked-list: Variable-size
• Stack: Add to top and remove from top
• Queue: Add to back and remove from front
• Priority queue: Add anywhere, remove the highest priority
Types of Data Structure
• Non-Linear: The data values in this structure are not arranged in
order.
• Hash tables: Unordered lists which use a ‘hash function’ to insert
and search
• Tree: Data is organized in branches.
• Graph: A more general branching structure, with less strict
connection conditions than for a tree
Type of Data Structures
• Homogenous: In this type of data structures, values of the same types of data are
stored.
• Array

• Non-Homogenous: In this type of data structures, data values of different types


are grouped and stored.
• Structures
• Classes
Abstract Data Type and Data Structure
• Definition:-
• Abstract Data Types (ADTs) stores data and allow various operations on
the data to access and change it.
• A mathematical model, together with various operations defined on
the model
• An ADT is a collection of data and associated operations for
manipulating that data

• Data Structures
• Physical implementation of an ADT
• data structures used in implementations are provided in a language
(primitive or built-in) or are built from the language constructs (user-
defined)
• Each operation associated with the ADT is implemented by one
or more subroutines in the implementation
Abstract Data Type
• ADTs support abstraction, encapsulation, and information hiding.

• Abstraction is the structuring of a problem into well-defined entities by defining


their data and operations.

• The principle of hiding the used data structure and to only provide a well-defined
interface is known as encapsulation.
The Core Operations of ADT
• Every Collection ADT should provide a way to:
• add an item
• remove an item
• find, retrieve, or access an item

• Many, many more possibilities


• is the collection empty
• make the collection empty
• give me a sub set of the collection
• No single data structure works well for all purposes, and so it is important to
know the strengths and limitations of several of them
Some Questions to Ask
• Are all data inserted into the data structure at the
beginning, or are insertions interspersed with other
operations?
• Can data be deleted?
• Are all data processed in some well-defined order, or is
random access allowed?
Data Structure Philosophy
 Each data structure has costs and benefits.
 Rarely is one data structure better than another in all situations.
 A data structure requires:
• space for each data item it stores,
• time to perform each basic operation,
• programming efforts.
Data Structure Operations

• Traversing
• Searching
• Insertion
• Deletion
• Sorting
• Merging
Algorithms
• Algorithm is a step-by-step procedure, which
defines a set of instructions to be executed in a
certain order to get the desired output.
Algorithm: SUM(A, B)
• Algorithms resemble recipes. Recipes tell you how
to accomplish a task by performing a number of Step 1 - START
steps. For example, to bake a cake the steps are: Step 2 - C ← A + B + 10
preheat the oven; mix flour, sugar, and eggs Step 3 - Stop
thoroughly; pour into a baking pan; and so forth
• Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be
implemented in more than one programming
language.
What is Pseudo Code ???
Categories of Algorithms
• From the data structure point of view, following are some important
categories of algorithms −
• Search − Algorithm to search an item in a data structure.
• Sort − Algorithm to sort items in a certain order.
• Insert − Algorithm to insert item in a data structure.
• Update − Algorithm to update an existing item in a data structure.
• Delete − Algorithm to delete an existing item from a data structure.
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have
the following characteristics −
• Unambiguous − Algorithm should be clear and unambiguous. Each of its
steps (or phases), and their inputs/outputs should be clear and must lead
to only one meaning.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined outputs, and
should match the desired output.
• Finiteness − Algorithms must terminate after a finite number of steps.
• Feasibility − Should be feasible with the available resources.
• Independent − An algorithm should have step-by-step directions, which
should be independent of any programming code.
How to Write an Algorithm?
• There are no well-defined standards for writing algorithms. Rather, it
is problem and resource dependent. Algorithms are never written to
support a particular programming code.
• As we know that all programming languages share basic code
constructs like loops (do, for, while), flow-control (if-else), etc. These
common constructs can be used to write an algorithm.
• We write algorithms in a step-by-step manner, but it is not always the
case. Algorithm writing is a process and is executed after the problem
domain is well-defined. That is, we should know the problem domain,
for which we are designing a solution.
Arrays
• Array is a container which can hold a fix number of items and these items
should be of the same type. Most of the data structures make use of
arrays to implement their algorithms.
• Elementary data structure that exists as built-in in most programming
languages.
Arrays
 Array declaration: int x[6];
 An array is collection of cells of void main()
the same type. {
int x[6];
 The collection has the name ‘x’. int j;
for(j=0; j < 6; j++)
 The cells are numbered with {
consecutive integers. x[j] = 2*j;
cout<<x[j];
 To access a cell, use the array }
}
name and an index:
x[0], x[1], x[2], x[3], x[4], x[5]
Arrays
x[0]
• Array cells are contiguous in x[1]
computer memory
x[2]
• The memory can be thought of as x[3]
an array.
x[4]

x[5]
Arrays

int x[6];

int n;
x[0] = 5;

x[1] = 2;
x = 3;// not allowed
x = a + b; // not allowed
x = &n; // not allowed
Array-Basic Operations
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index

You might also like