You are on page 1of 56

Instructor: Ahmar Rashid

Introducing Each Other


Who are you?
Who am I?

Logistics and Stuff


Instructor
Ahmar Rashid, PhD Office: F08 Office timings (tentative): Monday 9am 1130 am

Teaching Assistant
Mr. Muhammad Mushtaq

Class Timings
Monday: 8 am

Wednesday: 1030 am
Thursday: 1130 am

Class Venue
CS Lecture Hall 1

Text Books
TEXT 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. Schaums OuTlines: Data Structures by Seymour Lipschutz. McGraw-

Hill; ISBN 0070601682. 2. Introduction to Algorithms by Thomas H. Cormen et al. The MIT Press; ISBN 0262033844 2. Data Structures using C by Aaron M. Tenenbaum. Prentice Hall; ISBN 0131997467.

GRADING CRETERIA
Quizes
Assignments Project/Presentation Midterm Examination Final Examination

15 % 5% 15% 20% 45 %

Assignments and Quizes


A 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 Methodology


No Plagiarism?
Plagiarism is defined in dictionaries as the "wrongful

appropriation," "close imitation," or publication" of another authors "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 assignments Consulting each other in the quizzes

Course Objective
Introduce 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 programming
A lot of thinking

What should you learn by the end of this course Ability to understand common programming problems and design and implement efficient data structures to solve them

Why should we study this course


Well, because it is the core computer sciences course Any 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 Schedule
Kindly consult the Course Outline handout

Introduction
Fundamentals of data structures
An overview of computer programming Data types Abstract data types C/C++ Background Review of pointers Defining pointer variables Supplying values to pointer variables

Information and Data


After 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 earths radius its volume and surface area
13

Data, Information, Knowledge, and Wisdom


Information knowledge obtained from investigation or

communication. Detectives and journalists gather information. Just the facts, Mam. 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 system In computer sciences, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently
Efficient data structures Efficient algorithms

Focus: Efficiency and performance


Time and space analysis of algorithms

Source: http://en.wikipedia.org/wiki/Data_structure

Important characteristics of a good software


A good Design
Easy to implement Easy to use Easy to maintain Reliable 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

Linked List

Data structure = representation and operations associated with a data type

Data Structure Applications


Arrays
lists (one dimensional arrays) matrices (two dimensional arrays) database applications

dynamic memory allocation


to implement other data structures, such as heaps, hash tables,

queues, stacks, strings

Stacks
expression evaluation and syntax parsing

Queues
scheduling transportation operations management

Data Structure Applications


Trees efficient searching of data (Binary search tree) manipulate hierarchical data manipulate sorted data router algorithms Linked lists can 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 instructions with a finite amount of data in a finite amount of time Algorithms are used for
calculation data processing, and automated reasoning

In simple words an algorithm is a step-by-step procedure for calculations

Sample Problem
What are the sequence of steps to be followed to start a car

21

The Algorithm to Start the Car


1.Insert the key 2.Make sure car is in neutral gear 3.Press the gas pedal/ (Accelerator) 4.Turn the key to the start position 5.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 pedal

2. Wait for 10 seconds , and repeat the steps 3 6, but no

more than 5 times

7. If the car does not start


1. Call the workshop
22

Programming and Problem Solving with C++ by Nell Dale and Chip Weems

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

24

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 . . .
25

Programming Life Cycle Phases


Problem-Solving
Analysis and Specification Algorithm/General Solution Verification

Implementation
Program/Concrete Solution Test Plan

Maintenance
Use Maintain

26

Problem-Solving Phase
Analyze 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

27

Sample Problem
Suppose a programmer needs to determine an employees weekly wages. How would the calculations be done by hand?

28

One Employees 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 employees wages?

40 x $ 24.75

= $990.00 $ 1435.50
29

12 x 1.5 x $ 24.75= $445.50 ___________

Weekly Wages, in General


If hours are more than 40.0
wages = (40.0 * payRate) + (hours - 40.0) * 1.5 *payRate
RECALL EXAMPLE

otherwise

(40 x $ 24.75) +(12 x 1.5 x $ 24.75) = $1435.50

wages = hours * payRate


30

Algorithm to Determine an Employees Weekly Wages


1. 2. 3. 4. 5. Get the employees hourly payRate Get the hours worked this week Calculate this weeks regularWages Calculate this weeks overtimeWages(if any) Add the regularWages to overtimeWages(if any) to determine totalWages for the week

payRate = $24.75 hours = 52 regularWages = (40 * payRate) = 40 * 24.75 = 990 overtimeWages = (hours - 40.0) * 1.5 *payRate = (52 40) * 1.5 * 24.75 = 445.5 totalWages = regularWages + overtimeWages = 990 + 445.5 = 1435.50
31

Programming Life Cycle


1 Problem-Solving Phase
Analysis and Specification General Solution(Algorithm) Verify

2 Implementation Phase
Concrete Solution(Program) Test

3 Maintenance Phase
Use Maintain
32

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

33

Implementation Phase: Program


Translating your algorithm into a programming

language is called coding

C++ Program Algorithm


Basic Program

Asims Program Algorithm


Amirs Program

Java Program
Same Algo Different Languages

NirasProgram
Same Algo Different Implementation
34

Implementation Phase: Test


Testing 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

35

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

36

Programming Life Cycle


1 Problem-Solving Phase
Analysis and Specification General Solution(Algorithm) Verify

2 Implementation Phase
Concrete Solution(Program) Test

3 Maintenance Phase
Use Maintain
37

A Tempting Shortcut?
DEBUG
REVISE REVISE DEBUG REVISE DEBUG

CODE
GOAL

TEST THINKING CODE

38

Basic Control Structures


A 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


39

SEQUENCE
Statement Statement Statement ...

int a =5; Int b = 5; Int sum, prod; sum = a + b; prod = a*b;

40

SELECTION(branch)
IF Condition THEN Statement1 ELSE Statement2 Statement1 Statement Condition Statement2 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";

41

LOOP(repetition)
False Condition ... Statement

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"; OUTPUT 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
42

SUBPROGRAM(function)
SUBPROGRAM1

SUBPROGRAM2

...

SUBPROGRAM1 a meaningful collection of SEQUENCE, SELECTION, LOOP, SUBPROGRAM

43

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

44

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

45

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.

46

Leap Year Algorithm


Prompt 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

47

IsLeapYear Algorithm

Divide the year by 4 If 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 and If the remainder isn't 0 Return false(The year is not a leap year) Otherwise, Return true(The year is a leap year)

48

C++ Program
//****************************************************** // 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; bool IsLeapYear(int); // Access cout, endl, cin // Prototype for subalgorithm

int main() { }

49

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

50

IsLeapYear

bool 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

51

Primitive Data Types in C/C++

Primitive Data types


Name Description Size Range

char
short int (short) Int iong int (long) bool

Character or small integer


Short Integer Integer Long integer Boolean value. It can take one of two values: true or false

1 byte
2 bytes 4 bytes 4 bytes 1 byte

signed: -128 to 127 unsigned: 0 to 255


signed: -32768 to 32767 unsigned: 0 to 65535 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 true or false

float
double long double wchar_t

Floating point number 4 bytes


Double precision floating point number Long double precision floating point number Wide character 8 bytes 8 bytes 2 or 4 bytes

+/- 3.4e +/- 38 (~7 digits)


+/- 1.7e +/- 308 (~15 digits) +/- 1.7e +/- 308 (~15 digits) 1 wide character

Abstract Data Types


In 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 Types


Abstract 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: Example


Example: 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;

You might also like