Instructor: Ahmar Rashid
Introducing Each OtherWho are you?Who am I?
Logistics and StuffInstructor
Ahmar Rashid, PhDOffice: F08Office timings (tentative): Monday 9am 1130 am
Teaching AssistantMr. Muhammad Mushtaq
Class Timings Monday: 8 amWednesday: 1030 amThursday: 1130 am
Class VenueCS Lecture Hall 1
Text BooksTEXT BOOKS:1. Data Structures and Algorithm Analysis by Mark Weiss.
Addison Wesley; ISBN 080539057X.2. Data Structures and Algorithm Analysis in C by Mark
Weiss. Addison Wesley; ISBN: 0-201-49840-5. REFERENCE BOOKS: 1. Schaum’s OuTlines: Data Structures by Seymour
Lipschutz. McGraw-Hill; ISBN 0070601682.2. Introduction to Algorithms by Thomas H. Cormen et al.
The MIT Press; ISBN 02620338442. Data Structures using C by Aaron M. Tenenbaum.
Prentice Hall; ISBN 0131997467.
GRADING CRETERIAQuizes 15 %Assignments 5 %Project/Presentation 15%Midterm Examination 20%Final Examination 45 %
Assignments and QuizesA number of assignments and quizzes will be
taken Announced and/or unannounced quizzes may
be given to students any time during the lecture
Worst quiz may be dropped at the end of the course
Assignment and Quiz MethodologyNo Plagiarism?Plagiarism is defined in dictionaries as the
"wrongful appropriation," "close imitation," or “publication" of another author’s "language, thoughts, ideas, or expressions," and the representation of them as one's own original work (source: www.wikipedia.org)
Can you consult/collaborate with each other?Consulting each other in the assignmentsConsulting each other in the quizzes
Course ObjectiveIntroduce the basic concepts of data
structures /ADTs, and use them efficiently in algorithms for solving various problems using C/C++
What should you expect in this course?Extensive programmingA lot of thinking
What should you learn by the end of this courseAbility to understand common programming
problems and design and implement efficient data structures to solve them
Why should we study this courseWell, because it is the core computer sciences
courseAny other reason to study this course?We want to make a successful career after
graduation The most common programming interviews
questions Linked lists Strings Binary Trees Arrays Queues
Source: http://maxnoy.com/interviews.html
Weekly ScheduleKindly consult the Course Outline handout
IntroductionFundamentals of data structuresAn overview of computer programmingData typesAbstract data typesC/C++ BackgroundReview of pointers
Defining pointer variables Supplying values to pointer variables
13
Information and DataAfter you write the program, you must give
the computer the information or data necessary to solve the problem
Doffirence b/w information and data?Information: is any knowledge in the basic
form that can be communicated, including abstract ideas and concepts such as” the earth is round”
Data: is information in a form the computer can use, e.g. the numbers and letters making up the formula that relate earth’s radius its volume and surface area
Data, Information, Knowledge, and WisdomInformation – “knowledge obtained from investigation or
communication.” Detectives and journalists gather information. Just the facts, Ma’m.
Data “reliable information based on observation and record-keeping.” Scientists, marketing specialists, and government agencies gather data.
fact – “something known to be true,” or “something that can be proved to be true.”
knowledge – “the condition of knowing.” Knowledge is the whole package of what we have learned from the experience of living. It may or may not be factual. To my knowledge, the world is flat.
Source: http://www.dailywritingtips.com/data-and-information/
What is a Data Structure?Data structures are used in almost every
program or software systemIn computer sciences, a data structure is a
particular way of storing and organizing data in a computer so that it can be used efficientlyEfficient data structures Efficient algorithms
Focus: Efficiency and performanceTime and space analysis of algorithms
Source: http://en.wikipedia.org/wiki/Data_structure
Important characteristics of a good softwareA good DesignEasy to implementEasy to useEasy to maintainReliable solution of the given problem So, the data structure to solve a particular
problem should be selected with the above objectives in mind
Source: http://en.wikipedia.org/wiki/Data_structure
Some Example Data Structures
Arrays Stack Tree
Data structure = representation and operations associated with a data type
Linked List
Data Structure ApplicationsArrays
lists (one dimensional arrays)matrices (two dimensional arrays)database applicationsdynamic memory allocationto implement other data structures, such as heaps, hash
tables, queues, stacks, strings
Stacksexpression evaluation and syntax parsing
Queuesschedulingtransportationoperations management
Data Structure ApplicationsTrees
efficient searching of data (Binary search tree)manipulate hierarchical datamanipulate sorted datarouter algorithms
Linked listscan be used to implement several other common
abstract data structures, such as stacks queues symbolic expressions, and etc
What is an Algorithm?In mathematics and computer science, an algorithm is
a step-by-step procedure for solving a problem expressed as a finite list of well-defined instructionswith a finite amount of datain a finite amount of time
Algorithms are used for calculationdata processing, andautomated reasoning
In simple words an algorithm is a step-by-step procedure for calculations
21
Sample Problem
What are the sequence of steps to be followed to start a car
22
The Algorithm to Start the Car1.Insert the key2.Make sure car is in neutral gear3.Press the gas pedal/ (Accelerator)4.Turn the key to the start position5.If the engine starts in 6 seconds
1.Release the key to the ignition position
6.Else if the engine does not start in 6 seconds 1.Release the key and gas pedal2.Wait for 10 seconds , and repeat the steps 3 – 6, but
no more than 5 times
7. If the car does not start1.Call the workshop
Programming and Problem Solving with C++ by Nell Dale and Chip Weems
24
Computer Programming: A Brief Overview What is Computer Programming? Programming Life-Cycle Phases Creating an Algorithm Machine Language vs. High Level Languages Compilation and Execution Processes Computing Profession Ethics Problem-Solving Techniques
25
What is Computer Programming?
It is the process of planning a sequence of steps(called instructions) for a computer to follow.
STEP 1
STEP 2
STEP 3
. . .
26
Programming Life Cycle Phases• Problem-Solving
• Analysis and Specification• Algorithm/General Solution• Verification
• Implementation• Program/Concrete Solution• Test Plan
• Maintenance• Use• Maintain
27
Problem-Solving PhaseAnalyze the problem and specify what
the solution must do
Develop a general solution(algorithm) to solve the problem
Verify that your solution really solves the problem
28
Sample Problem
Suppose a programmer needs to determine an employee’s weekly wages.
How would the calculations be done by hand?
29
One Employee’s Wages In one week an employee works 52
hours at the hourly pay rate of $24.75. Assume a 40.0 hour normal work week and an overtime pay rate factor of 1.5.
What are the employee’s wages?
40 x $ 24.75 = $990.00
12 x 1.5 x $ 24.75= $445.50 ___________
$ 1435.50
30
If hours are more than 40.0 wages =
(40.0 * payRate) + (hours - 40.0) * 1.5 *payRate
otherwise wages = hours * payRate
Weekly Wages, in General
RECALL EXAMPLE (40 x $ 24.75) +(12 x 1.5 x $ 24.75) = $1435.50
31
Algorithm to Determine an Employee’s Weekly Wages
1. Get the employee’s hourly payRate 2. Get the hours worked this week 3. Calculate this week’s regularWages 4. Calculate this week’s overtimeWages(if any) 5. Add the regularWages to overtimeWages(if any) to
determine totalWages for the week
payRate = $24.75hours = 52regularWages = (40 * payRate) = 40 * 24.75 = 990overtimeWages = (hours - 40.0) * 1.5 *payRate
= (52 – 40) * 1.5 * 24.75 = 445.5totalWages = regularWages + overtimeWages
= 990 + 445.5 = 1435.50
32
Programming Life Cycle1 Problem-Solving Phase
Analysis and Specification General Solution(Algorithm) Verify
2 Implementation Phase Concrete Solution(Program) Test
3 Maintenance Phase Use Maintain
33
What is a Programming Language?
A programming language is a language with strict grammar rules, symbols, and special words used to construct a computer program
34
Implementation Phase:Program
Translating your algorithm into a programming language is called coding
Algorithm
C++ Program
Basic Program
Java Program
Algorithm
Asim’s Program
Amir’s Program
Nira’sProgram
Same AlgoDifferent Languages
Same AlgoDifferent Implementation
35
Implementation Phase: TestTesting your program means
running(executing) your program on the computer, to see if it produces correct results
If it does not, then you must find out what is wrong with your program or algorithm and fix it--this is called debugging
36
Maintenance Phase
Use and modify the program to meet changing requirements or correct errors that show up in using it
Maintenance begins when your program is put into use and accounts for the majority of effort on most programs
37
Programming Life Cycle1 Problem-Solving Phase
Analysis and Specification General Solution(Algorithm) Verify
2 Implementation Phase Concrete Solution(Program) Test
3 Maintenance Phase Use Maintain
38
GOAL
THINKINGCODE
REVISEREVISE
REVISE
DEBUG
DEBUG
DEBUG
TEST
CODEShortcut?
39
Basic Control StructuresA sequence is a series of statements that
execute one after another
A selection(branch) statement is used to determine which of two different statements to execute depending on certain conditions
A looping(repetition) statement is used to repeat statements while certain conditions are met
A subprogram is a smaller part of another program; a collection of subprograms solves the original problem
40
SEQUENCE
Statement Statement Statement . . .
int a =5;Int b = 5;Int sum, prod;sum = a + b;prod = a*b;
41
SELECTION(branch)IF Condition THEN Statement1 ELSE Statement2
Statement1
Statement
Statement2
Condition . . .
True
False
int age;cout<“”Enter your age\n”;cin>> age;if (age <16) cout<< “\nYou are just a child”;else if ((age >=16 )&& (age <30 )) cout<<“\nHi Young guy”;else cout<<“ \nGood Morning Sir”;end
cin>> x;if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0";
42
LOOP(repetition)
Statement
Condition. . .
False
True
int n;cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n“;OUTPUT: Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!\n";OUTPUT10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
43
SUBPROGRAM(function)SUBPROGRAM1 . . .
SUBPROGRAM1 a meaningful collection of SEQUENCE, SELECTION, LOOP, SUBPROGRAM
SUBPROGRAM2
44
Problem Solving Techniques Ask questions -- about the data, the process, the
output, error conditions
Look for familiar things -- certain situations arise again and again
Solve by analogy -- it may give you a place to start
Use means-ends analysis -- determine the I/O and then work out the details
45
More Problem Solving Techniques
Divide and conquer -- break up large problems into manageable units
Building-block approach -- can you solve small pieces of the problem?
Merge solutions -- instead of joining them end to end to avoid duplicate steps
Overcome mental block -- by rewriting the problem in your own words
46
Is a year a leap year? Problem You need to write a set of
instructions that can be used to determine whether a year is a leap year.
The instructions must be very clear because they are to be used by a class of fourth graders, who have just learned about multiplication and division.
They plan to use the instructions as part of an assignment to determine whether any of their relatives were born in a leap year.
47
Leap Year AlgorithmPrompt the user to enter a four-digit year
Read the year
If IsLeapYear
Write “Year is a leap year”
Otherwise
Write “Year is not a leap year”
48
IsLeapYear AlgorithmDivide the year by 4If the remainder isn't zero,
Return false(The year is not a leap year)Otherwise divide the year by 10 and If the remainder isn't 0,
Return true(The year is a leap year)Otherwise, divide the year by 400 andIf the remainder isn't 0
Return false(The year is not a leap year)Otherwise, Return true(The year is a leap year)
49
//******************************************************// LeapYear program// This program inputs a year and prints whether the year // is a leap year or not//******************************************************#include <iostream> // Access output stream
using namespace std; // Access cout, endl, cin
bool IsLeapYear(int); // Prototype for subalgorithm
int main(){ …}
C++ Program
50
Body of Main{ int year; // Year to be tested cout << "Enter a year AD, for example, 1997." << endl; // Prompt for input cin >> year; // Read year
if(IsLeapYear(year)) // Test for leap year cout << year << " is a leap year." << endl;
else cout << year << " is not a leap year." << endl; return 0; // Indicates successful
// completion}
51
IsLeapYearbool IsLeapYear(int year)// IsLeapYear returns true if year is a leap year and// false otherwise{ if(year % 4 != 0) // Is year not divisible by 4? return false; // If so, can't be a leap year else if(year % 100 != 0) // Is year not a multiple of 100? return true; // If so, is a leap year else if(year % 400 != 0) // Is year not a multiple of 400? return false; // If so, then is not a leap
year else return true; // Is a leap year
}
Primitive Data Types in C/C++
Primitive Data typesName Description Size Range
char Character or small integer
1 byte signed: -128 to 127unsigned: 0 to 255
short int (short) Short Integer 2 bytes signed: -32768 to 32767unsigned: 0 to 65535
Int Integer 4 bytes signed: -2147483648 to 2147483647unsigned: 0 to 4294967295
iong int (long) Long integer 4 bytes signed: -2147483648 to 2147483647unsigned: 0 to 4294967295
bool Boolean value. It can take one of two values: true or false
1 byte true or false
float Floating point number
4 bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number
8 bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number
8 bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t Wide character 2 or 4 bytes
1 wide character
Abstract Data TypesIn computing, an abstract data type (ADT) is
a mathematical model for a certain class of data structures that have
similar behavior; or for certain data types of one or more
programming languages that have similar semantics.
Source: http://en.wikipedia.org/wiki/Data_structure
Abstract Data TypesAbstract data types are purely theoretical entities
used to simplify the description of abstract algorithms,to classify and evaluate data structures, and to formally describe the type systems of
programming languages. However, an ADT may be
implemented by specific data types or data structures, in many ways and in many programming languages; or
described in a formal specification language.
Abstract Data Types: ExampleExample: abstract stack (functional)A complete functional-style definition of a
stack ADT could use the three operations:push: takes a stack state and an arbitrary
value, returns a stack state;top: takes a stack state, returns a value;pop: takes a stack state, returns a stack state;