css 221 lecture 1

56
Instructor: Ahmar Rashid

Upload: faizan-khan

Post on 01-Dec-2014

123 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSS 221 Lecture 1

Instructor: Ahmar Rashid

Page 2: CSS 221 Lecture 1

Introducing Each OtherWho are you?Who am I?

Page 3: CSS 221 Lecture 1

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

Page 4: CSS 221 Lecture 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.

Page 5: CSS 221 Lecture 1

GRADING CRETERIAQuizes 15 %Assignments 5 %Project/Presentation 15%Midterm Examination 20%Final Examination 45 %

Page 6: CSS 221 Lecture 1

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

Page 7: CSS 221 Lecture 1

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

Page 8: CSS 221 Lecture 1

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

Page 9: CSS 221 Lecture 1

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

Page 10: CSS 221 Lecture 1

Weekly ScheduleKindly consult the Course Outline handout

Page 11: CSS 221 Lecture 1

IntroductionFundamentals of data structuresAn overview of computer programmingData typesAbstract data typesC/C++ BackgroundReview of pointers

Defining pointer variables Supplying values to pointer variables

Page 12: CSS 221 Lecture 1
Page 13: CSS 221 Lecture 1

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

Page 14: CSS 221 Lecture 1

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/

Page 15: CSS 221 Lecture 1

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

Page 16: CSS 221 Lecture 1

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

Page 17: CSS 221 Lecture 1

Some Example Data Structures

Arrays Stack Tree

Data structure = representation and operations associated with a data type

Linked List

Page 18: CSS 221 Lecture 1

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

Page 19: CSS 221 Lecture 1

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

Page 20: CSS 221 Lecture 1

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

Page 21: CSS 221 Lecture 1

21

Sample Problem

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

Page 22: CSS 221 Lecture 1

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

Page 23: CSS 221 Lecture 1

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

Page 24: CSS 221 Lecture 1

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

Page 25: CSS 221 Lecture 1

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

. . .

Page 26: CSS 221 Lecture 1

26

Programming Life Cycle Phases• Problem-Solving

• Analysis and Specification• Algorithm/General Solution• Verification

• Implementation• Program/Concrete Solution• Test Plan

• Maintenance• Use• Maintain

Page 27: CSS 221 Lecture 1

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

Page 28: CSS 221 Lecture 1

28

Sample Problem

Suppose a programmer needs to determine an employee’s weekly wages.

How would the calculations be done by hand?

Page 29: CSS 221 Lecture 1

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

Page 30: CSS 221 Lecture 1

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

Page 31: CSS 221 Lecture 1

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

Page 32: CSS 221 Lecture 1

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

Page 33: CSS 221 Lecture 1

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

Page 34: CSS 221 Lecture 1

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

Page 35: CSS 221 Lecture 1

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

Page 36: CSS 221 Lecture 1

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

Page 37: CSS 221 Lecture 1

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

Page 38: CSS 221 Lecture 1

38

GOAL

THINKINGCODE

REVISEREVISE

REVISE

DEBUG

DEBUG

DEBUG

TEST

CODEShortcut?

Page 39: CSS 221 Lecture 1

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

Page 40: CSS 221 Lecture 1

40

SEQUENCE

Statement Statement Statement . . .

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

Page 41: CSS 221 Lecture 1

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";

Page 42: CSS 221 Lecture 1

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!

Page 43: CSS 221 Lecture 1

43

SUBPROGRAM(function)SUBPROGRAM1 . . .

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

SUBPROGRAM2

Page 44: CSS 221 Lecture 1

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

Page 45: CSS 221 Lecture 1

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

Page 46: CSS 221 Lecture 1

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.

Page 47: CSS 221 Lecture 1

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”

Page 48: CSS 221 Lecture 1

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)

Page 49: CSS 221 Lecture 1

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

Page 50: CSS 221 Lecture 1

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}

Page 51: CSS 221 Lecture 1

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

}

Page 52: CSS 221 Lecture 1

Primitive Data Types in C/C++

Page 53: CSS 221 Lecture 1

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

Page 54: CSS 221 Lecture 1

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

Page 55: CSS 221 Lecture 1

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.

Page 56: CSS 221 Lecture 1

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;