242
Introduction to Introduction to Programming Programming H. Turgut Uyar H. Turgut Uyar [email protected] [email protected]

Sunum

Embed Size (px)

Citation preview

Page 1: Sunum

Introduction toIntroduction toProgrammingProgramming

H. Turgut UyarH. Turgut Uyar

[email protected]@cs.itu.edu.tr

Page 2: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Computer ProgramsComputer Programs

►how to represent the problem?how to represent the problem? computers work on numberscomputers work on numbers program about the highways in Turkeyprogram about the highways in Turkey entities: cities and roadsentities: cities and roads representing a city: name, latitude, representing a city: name, latitude,

longitudelongitude

►how to express the solution?how to express the solution?

Page 3: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Representing the ProblemRepresenting the Problem

► representing a road: representing a road: lineline assume the road is assume the road is

straightstraight start and end citiesstart and end cities

► very easyvery easy► very inaccuratevery inaccurate

İstanbul

Ankara

İzmir

Page 4: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Representing the ProblemRepresenting the Problem

► representing a road: representing a road: coconsecutive linesnsecutive lines

► very hardvery hard► more accurate more accurate

more complicatedmore complicated

İstanbul

Ankara

İzmir

Page 5: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Representation: ModelRepresentation: Model

►FIRST STEPFIRST STEP: build a correct / accurate : build a correct / accurate (and feasible) model(and feasible) model

►what you are solving is the model, not what you are solving is the model, not the problem itselfthe problem itself incorrect model incorrect model incorrect solution incorrect solution inaccurate model inaccurate model meaningless solution meaningless solution infeasible model infeasible model expensive expensive

implementationimplementation

Page 6: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Representing the ProblemRepresenting the Problem

►representing highways:representing highways: if you are only interested in total if you are only interested in total

distances, you can use ldistances, you can use linesines if you will talk about “the 274th km of the if you will talk about “the 274th km of the

İstanbul-Ankara highway”, you should use İstanbul-Ankara highway”, you should use consecutive linesconsecutive lines

Page 7: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

DataData

►data that model an entity are data that model an entity are represented by represented by variablesvariables symbolic name for the datasymbolic name for the data variables take variables take valuesvalues city variables: city variables: namename latitudelatitude longitudelongitude

to represent İstanbul:to represent İstanbul:namename: “İstanbul”: “İstanbul”

latitudelatitude: 41: 41

longitudelongitude: 29: 29

Page 8: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

VariablesVariables

►variables are kept in memoryvariables are kept in memory variable is the name of the memory cellvariable is the name of the memory cell value is the content of the memory cellvalue is the content of the memory cell

41

latitude

“İstanbul”

name

29

longitude

Page 9: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AssignmentAssignment

►block structured programs proceed by block structured programs proceed by assigning values to variablesassigning values to variables

►notation: notation: latitude latitude 41 41 ““store the value 41 in the memory cell store the value 41 in the memory cell

named latitude”named latitude”

► left hand side is a variableleft hand side is a variable►right hand side is an right hand side is an expressionexpression

a computation that yields a valuea computation that yields a value

Page 10: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ExpressionsExpressions

►can be a single value or variable:can be a single value or variable: 4141 latitudelatitude

►can be combinations of values and can be combinations of values and variables connected via variables connected via operatorsoperators:: 4 * longitude4 * longitude mmultiplication ultiplication

operatoroperator latitude + longitudelatitude + longitude addition operatoraddition operator

Page 11: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AssignmentAssignment

►ASSIGNMENT IS NOT EQUALITY!!!ASSIGNMENT IS NOT EQUALITY!!!►41 41 latitude latitude doesn’t make sense doesn’t make sense► i i i + 1 i + 1 means: increment the value means: increment the value

of of ii by 1 by 1 if if ii was 5 before the operation, it will was 5 before the operation, it will

become 6 after the operationbecome 6 after the operation

►mathematically it would be incorrect:mathematically it would be incorrect:0 = 10 = 1

Page 12: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

SwapSwap

►swap the values of two variables:swap the values of two variables:

32

num1

154

num2

before the operation

154

num1

32

num2

after the operation

Page 13: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

SwapSwap: Incorrect: Incorrect

num1 num1 num2 num2 num2 num2 num1 num1 32

num1

154

num2

154

num1

154

num2

154

num1

154

num2

num1 num2 num2 num1

Page 14: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

SwapSwap

tmp tmp num1 num1 num1 num1 num2 num2 num2 num2 tmp tmp

154

num1

32

num2

32

tmp

tmp num1

32

num1

154

num2 tmp

32

num1

154

num2

32

tmp

num1 num2

154

num1

154

num2

32

tmp

num2 tmp

Page 15: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Data TypesData Types

►basic data types:basic data types: integerinteger real numberreal number logicallogical charactercharacter stringstring

►composite data types: recordcomposite data types: record►vector data types: arrayvector data types: array

Page 16: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Basic Data TypesBasic Data Types

► integerinteger birthyear, number of letters in the birthyear, number of letters in the

surname, height in cmsurname, height in cm

►real numbersreal numbers height in m, average of several exam height in m, average of several exam

scores, square root of a numberscores, square root of a number

► logical: values can be logical: values can be truetrue or or falsefalse student successful, older than 18 yearsstudent successful, older than 18 years

Page 17: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

CharacterCharacter

►any symbol: letter, digit, punctuation any symbol: letter, digit, punctuation mark, ...mark, ... first letter of surname, the key the user first letter of surname, the key the user

pressedpressed

►mostly written between single quotes:mostly written between single quotes: ‘‘Y’Y’, , ‘4’‘4’, , ‘?’‘?’

Page 18: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

EncodingEncoding

►numbers correspond to symbolsnumbers correspond to symbols►ASCII, ISO8859-X, UnicodeASCII, ISO8859-X, Unicode

240

240

integer

‘ğ’

ISO8859-9‘ð’

ISO8859-1

Page 19: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StringsStrings

►name, word, sentence, ISBN number, ...name, word, sentence, ISBN number, ...►mostly written between double quotes:mostly written between double quotes:

““Dennis Ritchie”Dennis Ritchie”, , “ISBN 0-13-110362-8”“ISBN 0-13-110362-8”

►use numbers if you plan to make use numbers if you plan to make arithmetic operations on it:arithmetic operations on it: student numbers at ITU: 9-digit numbersstudent numbers at ITU: 9-digit numbers will you add/multiply/... student numbers?will you add/multiply/... student numbers? no sense in using integers, use stringsno sense in using integers, use strings

Page 20: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Composite Data TypesComposite Data Types

►grouping types to form a new typegrouping types to form a new type

►access:access: capital.name capital.name “Ankara” “Ankara” NOT city.name NOT city.name “Ankara” “Ankara”

name

latitude

city

capital

longitude

Page 21: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Composite Data TypesComposite Data Types

►composite composite types can be types can be nestednested

►access:access: tem.code tem.code “E-6” “E-6” tem.end.name tem.end.name

“Ankara”“Ankara”

name

latitude

highway

start

longitude

name

latitude

longitude

end

code length

tem

Page 22: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Vector Data TypesVector Data Types

►grouping elements of the same typegrouping elements of the same type exam scores for a 50 student class:exam scores for a 50 student class:

►50 integer variables: score1, score2, ..., 50 integer variables: score1, score2, ..., score50score50

►an integer array with 50 elements: scorean integer array with 50 elements: score

score

1 2 50

►access:access: scorescore2222 95 95

score4 score13 score22score1

Page 23: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StringsStrings

►strings are usually arrays of charactersstrings are usually arrays of characters

fullname

‘D’

1

‘e’ ‘n’ ‘n’ ‘i’ ‘s’ ‘ ‘ ‘R’ ‘i’ ...

2 3 4 5 6 7 8 9 10

Page 24: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Arrays of RecordsArrays of Records

►represent the factors of a number:represent the factors of a number: an array where each member is a factoran array where each member is a factor a factor is a record of a base and a powera factor is a record of a base and a power

2base

3

power

7base

1

power

11base

2

power

factors►access:access:

factorsfactors22.base .base 7 7

Page 25: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Expressing the SolutionExpressing the Solution

► step-by-step guide step-by-step guide to the solution: to the solution: algorithmalgorithm

► recipe for Jamaican recipe for Jamaican rice and peas:rice and peas: put 1 1/2 can of beans in put 1 1/2 can of beans in

4-5 cups of water4-5 cups of water add 1/4 can of coconut add 1/4 can of coconut

milk, 1 sprig of thyme milk, 1 sprig of thyme and salt and pepper to and salt and pepper to tastetaste

cook until beans are softcook until beans are soft smash the bottom of an smash the bottom of an

escallion and add it to escallion and add it to the pot along with 2 cups the pot along with 2 cups of rice and 1/4 can of of rice and 1/4 can of coconut milk and 2 coconut milk and 2 sprigs of thymesprigs of thyme

remove any access water remove any access water over 2cm above the riceover 2cm above the rice

bring to a boil for 5 minbring to a boil for 5 min continue to cook covered continue to cook covered

until rice is tenderuntil rice is tender

Page 26: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AlgorithmAlgorithm

► there must be no there must be no room for judgementroom for judgement 4-5 cups? sprig?4-5 cups? sprig? salt and pepper to salt and pepper to

taste?taste? beans are soft? rice beans are soft? rice

is tender?is tender?

► this cooking recipe this cooking recipe is NOT an algorithm is NOT an algorithm

► must be finitemust be finite► in a finite number of in a finite number of

steps:steps: either find the either find the

correct solutioncorrect solution or report failure to or report failure to

find a solutionfind a solution

► must not run must not run foreverforever

Page 27: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

►describe algorithmsdescribe algorithms►elements:elements:

box: an operationbox: an operation arrow: flow directionarrow: flow direction diamond: decision pointdiamond: decision point parallelogram: input/output operationparallelogram: input/output operation

Page 28: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

► find the maximum find the maximum score in an exam score in an exam with 50 studentswith 50 students represent exam represent exam

scores by a 50 scores by a 50 element integer element integer array (variable: array (variable: scorescore))

represent maximum represent maximum score by an integer score by an integer (variable: (variable: maxmax))

1.1. choose first score as choose first score as maximummaximum

2.2. if there are more if there are more students go to step 3, students go to step 3, else go to step 5else go to step 5

3.3. if next score is if next score is higher than higher than maximum, choose it maximum, choose it as maximumas maximum

4.4. proceed to next proceed to next studentstudent

5.5. print the maximum print the maximum

Page 29: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

► representation representation problem:problem: more students? next more students? next

score?score? counter variable: counter variable: ii

1.1. max max score score11, i , i 2 2

2.2. if i if i 50 go to step 3 50 go to step 3 else go to step 5else go to step 5

3.3. if scoreif scoreii > max > max

then max then max score scoreii

4.4. i i i + 1 and go to i + 1 and go to step 2step 2

5.5. print maxprint max

Page 30: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowchartsstart

max score1

i 2

i 50

scorei > max

Y

i i + 1

N max scorei

Y

print max

stop

N

Page 31: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowchartsstart

max 43

i 2

i 6

scorei > max

Y

i i + 1

N max scorei

Y

print max

stop

N

2<6

74>43

74

3

3<6

65<74

82

4

4<6

58<74

5

5<6

74<82

6

6=6

43

1

74 65 58 82

2 3 4 5

37

6

37<82

7

7>6

82

Page 32: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

►using tables to represent flow:using tables to represent flow:

i 6 scorei > maxmax i

T (2 < 6) T (74 > 43)43 2

T (3 < 6) F (65 < 74)74 3

T (4 < 6) F (58 < 74)4

T (5 < 6) T (82 > 74)5

T (6 = 6) F (37 < 82)82 6

F (7 > 6)7

Page 33: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

►number guessing game:number guessing game: one player picks a number (target) one player picks a number (target)

between lower and upper boundsbetween lower and upper bounds the other player makes a guess:the other player makes a guess:

►if guess is bigger than target, picker says if guess is bigger than target, picker says “smaller”“smaller”

►if guess is smaller than target, picker says if guess is smaller than target, picker says “bigger”“bigger”

►game ends when guess = targetgame ends when guess = target

Page 34: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

► Algorithm II:Algorithm II: try the number in try the number in

the middlethe middle if “smaller” narrow if “smaller” narrow

the search to the the search to the bottom halfbottom half

if “bigger” narrow if “bigger” narrow the search to the top the search to the top halfhalf

► Algorithm I:Algorithm I: start with start with lowerlower, ,

increment by 1 until increment by 1 until foundfound

1.1. guess guess lower lower

2.2. if guess = target if guess = target stopstop

3.3. guess guess guess + 1 guess + 1 and go to step 2and go to step 2

Page 35: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

1.1. bottom bottom lower, top lower, top upper upper

2.2. guess guess (top + bottom) /2 (top + bottom) /2

3.3. if guess = target stop if guess = target stop

4.4. if guess > target then top if guess > target then top guess - 1 guess - 1

otherwise bottom otherwise bottom guess + 1 guess + 1

and go to step 2and go to step 2

Page 36: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowchartsstart

bottom lower

top upper

guess (bottom + top) / 2

guess = target

print guess

stop

Y

guess > target

N

top guess - 1

Y

bottom guess + 1

N

Page 37: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

print guess

stop

Y

guess > target

N

top guess - 1

Y

bottom guess + 1

N

32

32=19

32>19

31

16

16=19

16<19

17

24

24=19

24>19

23

20

20=19

20>19

19

18

18=19

18<19

19

19

19=19

19

start

bottom 1

top 63

guess (bottom + top) / 2

guess = target

Page 38: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FlowchartsFlowcharts

guess=targetbottom top guess

1 63 32

F (32 > 19)31 16

F (16 < 19)17 24

F (24 > 19)23 20

F (20 > 19)19 18

F (18 < 19)19 19

T (19 = 19)

Page 39: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Comparing AlgorithmsComparing Algorithms

►number guessing: which algorithm is number guessing: which algorithm is better?better?

►speed:speed: worst case: first one 63, second one 6worst case: first one 63, second one 6 average case: first one 32, second one ~5average case: first one 32, second one ~5

►size: second one requires two more size: second one requires two more variablesvariables

Page 40: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Block StructuresBlock Structures

► sequencesequence ► selectionselection► repetitionrepetition

block1

block2

condition

block1 block2

condition

block

Page 41: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►divide the main task to sub-tasksdivide the main task to sub-tasks►consider each sub-task as a main task consider each sub-task as a main task

and divide into sub-sub-tasks, ...and divide into sub-sub-tasks, ... divide-and-conquerdivide-and-conquer

►top-down designtop-down design►each task is implemented by a each task is implemented by a

procedureprocedure (in C a (in C a functionfunction))

Page 42: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

main task

sub-task-1 sub-task-2 sub-task-3

sub-task-1a sub-task-3a sub-task-3b

Page 43: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►procedures are only interested in procedures are only interested in WHAT sub-procedures are doing, not WHAT sub-procedures are doing, not HOW they are doing itHOW they are doing it

►smaller units are easier to managesmaller units are easier to manage►maintaining is easiermaintaining is easier

if the HOW of the sub-procedure changes, if the HOW of the sub-procedure changes, the super-procedure is not affectedthe super-procedure is not affected

Page 44: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►procedures should be general:procedures should be general: instead of “find the maximum score in the instead of “find the maximum score in the

final exam of BIL105E”final exam of BIL105E” do “find the maximum of any array”do “find the maximum of any array” you can use this to find the “maximum you can use this to find the “maximum

score in the final exam of BIL105E”score in the final exam of BIL105E” and also to find the “maximum shoe size and also to find the “maximum shoe size

of the LA Lakers players”of the LA Lakers players”

Page 45: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ParametersParameters

►which data will the procedure work on?which data will the procedure work on? input parameterinput parameter::

►the scores in the final exam of BIL105Ethe scores in the final exam of BIL105E►the shoe sizes of the LA Lakers players the shoe sizes of the LA Lakers players

►what value will the procedure what value will the procedure produce?produce? output parameteroutput parameter::

►maximum scoremaximum score►maximum shoe sizemaximum shoe size

Page 46: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►find the greatest common divisor (gcd) find the greatest common divisor (gcd) of two numbers:of two numbers:1.1. decompose the first number to its prime decompose the first number to its prime

factorsfactors

2.2. decompose the second number to its decompose the second number to its prime factorsprime factors

3.3. find the common factors of both numbers find the common factors of both numbers

4.4. compute the gcd from the common compute the gcd from the common factorsfactors

Page 47: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►sample numbers: 9702 and 945sample numbers: 9702 and 9451.1. 9702 = 2 * 3 9702 = 2 * 322 * 7 * 722 * 11 * 11

2.2. 945 = 3 945 = 333 * 5 * 7 * 5 * 7

3.3. 3 322 * 7 * 7

4.4. 63 63

Page 48: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

compute gcd

factorizefind common

factors

97022

* 3

2 * 7

2 * 1

1945

33 *

5 * 7 2 *

32 *

72 *

11

33 *

5 *

7 32 * 7

Page 49: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Euclides AlgorithmEuclides Algorithm

►finding the greatest common divisor finding the greatest common divisor (gcd) of two numbers: Euclides (gcd) of two numbers: Euclides algorithmalgorithm let let aa be the bigger number and be the bigger number and b b the the

smaller numbersmaller number the gcd of the gcd of aa and and bb is the same as the gcd is the same as the gcd

of of bb and and a % ba % b

Page 50: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Euclides AlgorithmEuclides Algorithm

print a

N

r a % b

a b

b r

Y

Y Nnum1 > num2

a num1

b num2

a num2

b num1

b > 0

Page 51: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Euclides AlgorithmEuclides Algorithm

ra b

2529702 945

189945 252

63252 189

0189 63

Page 52: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Comparing AlgorithmsComparing Algorithms

►Algorithm I:Algorithm I: hard to factorize numbers hard to factorize numbers easier to compute the gcd/lcm of more easier to compute the gcd/lcm of more

than two numbers?than two numbers?

►Algorithm II (Euclides):Algorithm II (Euclides): very fastvery fast very easy to implementvery easy to implement

Page 53: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

InputInput

►most programs read the data from most programs read the data from outside:outside: ask the user: get from keyboardask the user: get from keyboard read from a fileread from a file read from the environment: get read from the environment: get

temperature of the room via a sensortemperature of the room via a sensor

► input commands transfer the value input commands transfer the value read from outside to a variableread from outside to a variable

Page 54: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutputOutput

►what to do with the produced results?what to do with the produced results? tell the user: print it on the screentell the user: print it on the screen write it to a file or printerwrite it to a file or printer send to the environment: control the send to the environment: control the

valve of a gas pipevalve of a gas pipe

►output commands send results to output commands send results to output unitsoutput units

►error messages to error uniterror messages to error unit

Page 55: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Program TypesProgram Types

► console / command console / command line / text mode line / text mode programs:programs: read inputsread inputs process data and process data and

produce resultsproduce results show outputsshow outputs

► graphical programs graphical programs are event driven:are event driven: prepare the prepare the

environment environment (windows, (windows, buttons, ...)buttons, ...)

wait for events wait for events (mouse click, key (mouse click, key press, ...)press, ...)

respond to eventsrespond to events

Page 56: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Development StagesDevelopment Stages

► design: on “paper”design: on “paper” model, algorithmmodel, algorithm which programming which programming

language?language? software engineeringsoftware engineering

► coding: writing the coding: writing the programprogram source codesource code editoreditor

► testing: does the testing: does the program work as program work as expected?expected? scenariosscenarios

► debugging: finding debugging: finding and correcting the and correcting the errorserrors debuggerdebugger

Page 57: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ErrorsErrors

►syntax errorssyntax errors not conforming to the rules of the not conforming to the rules of the

languagelanguage

► logical errorslogical errors division by zerodivision by zero

Page 58: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Evaluating ProgramsEvaluating Programs

► efficiencyefficiency speedspeed hardware hardware

requirementsrequirements

► portabilityportability can it run on another can it run on another

platform without platform without much change?much change?

source code source code portabilityportability

► understandibilityunderstandibility can others (or you) can others (or you)

understand your understand your code?code?

► ease of maintenanceease of maintenance can new features be can new features be

added?added?

► robustnessrobustness can it tolerate user can it tolerate user

errors?errors?

Page 59: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Machine CodeMachine Code

► executable files executable files have to have a have to have a computer-computer-understandable understandable formatformat

► executable format executable format differs betweendiffers between hardwarehardware operating systemsoperating systems

► programmers programmers cannot write cannot write directly in machine directly in machine codecode

► write source code in write source code in a a high-level high-level languagelanguage

► use tools to convert use tools to convert source code to source code to machine codemachine code

Page 60: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ConversionConversion

► interpretedinterpreted read a command read a command

from source codefrom source code convertconvert executeexecute repeat for next repeat for next

commandcommand if error report (only if error report (only

first error) and abortfirst error) and abort

► compiledcompiled read in the whole read in the whole

source codesource code convert and build an convert and build an

executable fileexecutable file if error report (all if error report (all

errors) and no errors) and no executableexecutable

conversion is done conversion is done once once much faster much faster

Page 61: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

LibrariesLibraries

► every feature built every feature built into the language into the language hard and slow hard and slow implementationimplementation

► small, fast core small, fast core language + language + extensionsextensions

► no built-in square no built-in square root feature in Croot feature in C

► extra features are extra features are kept in procedure kept in procedure archives called archives called librarieslibraries

► why use libraries?why use libraries? thoroughly tested thoroughly tested

reliable and efficientreliable and efficient save timesave time

Page 62: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StandardsStandards

►to achieve portability, standards are to achieve portability, standards are neededneeded

►ANSI C: core C language,librariesANSI C: core C language,libraries► ISO C/C++ standardsISO C/C++ standards►POSIX: how to access the operating POSIX: how to access the operating

system?system?►no standard for graphics operations!no standard for graphics operations!

Page 63: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Building the ExecutableBuilding the Executable

► compilercompiler: produces : produces machine code for machine code for the procedures in the procedures in the source code the source code object codeobject code

► linkerlinker: combines the : combines the object code with the object code with the library procedures library procedures used in the source used in the source code code executable executable

source code object code

libraries

executable

Page 64: Sunum

Introduction to Introduction to thetheC LanguageC Language

Page 65: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

First ExampleFirst Example/* My first C program. * * This program computes .. */

#include <iostream> // cout,cin#include <stdlib.h>

#define PI 3.14

int main(void){ float radius; float circum, area;

std::cout << “Radius: “; std::cin >> radius; circum = 2 * PI * radius; area = PI * radius * radius; std::cout << “Circumference: “ << circum << “\n”; std::cout << “Area: “ << area << “\n”; return EXIT_SUCCESS;}

INPUT

PROCESSING

OUTPUT

VARIABLES

Page 66: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

CommentsComments

► comments improve comments improve the the understandability of understandability of your codeyour code anything between anything between /*/*

and and */*/ anything from anything from //// to to

end of lineend of line completely ignored completely ignored

by the compilerby the compiler

/* My first C program. * * This program computes .. */

#include <iostream> // cout,cin#include <stdlib.h>

#define PI 3.14

int main(void){ ...}

Page 67: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FunctionsFunctions

► execution starts with execution starts with function function mainmain each program must have each program must have

one and only one one and only one mainmain starts with:starts with:

int main(void)int main(void) ends withends with::

return EXIT_SUCCESS;return EXIT_SUCCESS; program successfulprogram successful

► blocks are delimited blocks are delimited using curly bracesusing curly braces

int main(void){ ...

... return EXIT_SUCCESS;}

start of main function

block of main function

Page 68: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

int main(void){ float radius; float circum, area;

cout << “Radius: “; cin >> radius; circum = 2 * PI * radius; area = PI * radius * radius; cout << “Circumference: “ << circum << endl; cout << “Area: “ << area << endl; return EXIT_SUCCESS;}

StatementsStatements

► statements end with statements end with semicolonsemicolon

► they can span they can span across linesacross lines

► multiple blanks are multiple blanks are regarded as one regarded as one blankblank except in stringsexcept in strings

Page 69: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

int main(void){ float radius; float circum, area;

std::cout << “Radius: “; std::cin >> radius; circum = 2 * PI * radius; area = PI * radius * radius; std::cout << “Circumference: “ << circum << “\n”; std::cout << “Area: “ << area << “\n”; return EXIT_SUCCESS;}

IndentationIndentation

► all statements all statements belonging to the belonging to the same block should same block should have the same left have the same left marginmargin

Page 70: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

int main(void){ float radius; float circum, area;

std::cout << “Radius: “; std::cin >> radius; circum = 2 * PI * radius; area = PI * radius * radius; std::cout << “Circumference: “ << circum << “\n”; std::cout << “Area: “ << area << “\n”; return EXIT_SUCCESS;}

AssignAssignmentment

► assignment is done assignment is done using the using the == symbol symbol

► NOT EQUALITYNOT EQUALITY

Page 71: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

#include <iostream>#include <stdlib.h>...int main(void){ ... std::cout << “Radius: “; std::cin >> radius; ... return EXIT_SUCCESS;}

Header FilesHeader Files

► needed for using needed for using library entitieslibrary entities to use to use std::coutstd::cout and and

std::cinstd::cin, we need , we need iostreamiostream

to use to use EXIT_SUCCESSEXIT_SUCCESS, we , we need need stdlib.hstdlib.h

Page 72: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Rules for NamesRules for Names

► valid symbols: lower valid symbols: lower and uppercase and uppercase letters of English, letters of English, digits and digits and underscoreunderscore pi, weight, weight1pi, weight, weight1

andand weight_1 are weight_1 are validvalid

, ağırlık, ağırlık and and weight- weight-1 are not valid1 are not valid

► first symbol must first symbol must not be a digitnot be a digit 1weight is not valid1weight is not valid

► should not be should not be longer than 31 longer than 31 symbolssymbols

► names are case-names are case-sensitive:sensitive: weight and wEiGHt weight and wEiGHt

are differentare different

Page 73: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Rules for NamesRules for Names

►C reserved words can not be chosen C reserved words can not be chosen as namesas names int, main, void and return are not valid int, main, void and return are not valid

► library names can be chosen as names library names can be chosen as names but they will become unaccessiblebut they will become unaccessible

Page 74: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Name ConventionsName Conventions

►CONVENTION:CONVENTION: start variable names with lowercase start variable names with lowercase

lettersletters use meaningful namesuse meaningful names if name consists of more than one word if name consists of more than one word

use one of:use one of: birth_month, birthMonthbirth_month, birthMonth

Page 75: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

NumbersNumbers

► integers:integers: decimal: decimal: 5959 octal: start with 0: octal: start with 0: 073073 hexadecimal: start with 0x: hexadecimal: start with 0x: 0x3b0x3b

►real numbers:real numbers: decimal: decimal: 3.143.14 scientific: use E: scientific: use E: 0.314E1, 31.4E-10.314E1, 31.4E-1

Page 76: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

VariablesVariables

► variables must be variables must be defined before useddefined before used data type and namedata type and name

► reserve a memory reserve a memory cell for this variablecell for this variable

► definitions can be definitions can be groupedgrouped

int main(void){ float radius; float circum, area;

std::cout << “Radius: “; …}

one variable

of type float

radius

two variables

of type float

circum area

Page 77: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

int main(void)

{

float radius, circum=0.0, area=0.0;

cout << “Radius: “;

,,,,

VariablesVariables

► initial values can be initial values can be assigned to assigned to variablesvariables

► define variables define variables beforebefore statements statements

► CONVENTION:CONVENTION: leave one blank line leave one blank line

between end of between end of variable definitions variable definitions and start of and start of statementsstatements

radius

0.0

circum

0.0

area

blank line

Page 78: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Data TypesData Types

► integers: integers: intint short / longshort / long signed / unsignedsigned / unsigned

► real numbers: real numbers: floatfloat► double precision double precision

real number: real number: doubledouble► symbol: symbol: charchar► logical: logical: boolbool

► type determines type determines value rangevalue range

► if short int is 16 bitsif short int is 16 bits signed short int can signed short int can

represent -32768 to represent -32768 to 3276732767

unsigned short int unsigned short int can represent 0 to can represent 0 to 6553565535

► sizeofsizeof

Page 79: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ConstantsConstants

► improve improve understandibilityunderstandibility symbolic name symbolic name

instead of numberinstead of number

► changing is easierchanging is easier use 3.14159 instead use 3.14159 instead

of 3.14 of 3.14 change at change at one pointone point

...

#define PI 3.14

...

int main(void)

{

...

circum = 2 * PI * radius;

area = PI * radius * radius;

...

}

Page 80: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ConstantsConstants

► using using #define#define

#define NAME value#define NAME value as if you have as if you have

written 3.14 instead written 3.14 instead of PI everywhere in of PI everywhere in the codethe code

► CONVENTION:CONVENTION: use all uppercase use all uppercase

names for constantsnames for constants

► using using constconst:: put put constconst in front of in front of

variable declarationvariable declaration defines a read-only defines a read-only

variablevariable

float circum, area;float circum, area;

const float pi = 3.14;const float pi = 3.14;

circum = 2 * pi * circum = 2 * pi * radius;radius;

Page 81: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Arithmetic ExpressionsArithmetic Expressions

► addition: addition: ++► subtraction: subtraction: --► multiplication: multiplication: **► division: division: //► remainder: remainder: %%► math library math library

functions:functions: sin,cos,exp,log,pow,.sin,cos,exp,log,pow,.

....

► CONVENTION:CONVENTION: leave one blank leave one blank

space before and space before and after operatorsafter operators

also before and after also before and after = in assignments= in assignments

Page 82: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PrecedencePrecedence

►expressions in parenthesesexpressions in parentheses►unary unary ++ and and --:: -2-2►* / %* / %►+ -+ -►operators of equal precedence are operators of equal precedence are

evaluated left to rightevaluated left to right

Page 83: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PrecedencePrecedence

a + b + c + d + e / 5a + b + c + d + e / 5► will be evaluated as:will be evaluated as:

(a + b + c + d) + e / (a + b + c + d) + e / 55

► to divide the sum by to divide the sum by 5:5:

(a + b + c + d + e) / (a + b + c + d + e) / 55

p * r % q + w / x - yp * r % q + w / x - y► will be evaluated as:will be evaluated as:

p * rp * r

p * r % qp * r % q

w / xw / x

p * r % q + w / xp * r % q + w / x

p * r % q + w / x - yp * r % q + w / x - y

Page 84: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

TypecastingTypecasting

► if both operands if both operands are integers, are integers, result is integerresult is integer

► if either one or if either one or both real, result both real, result realreal 14 / 4 = 314 / 4 = 3 14.0 / 4 = 3.514.0 / 4 = 3.5

int num1 = 14, num2 = 4;int num1 = 14, num2 = 4;

float quotient;float quotient;

quotient = num1 / num2;quotient = num1 / num2;

► convert a variable to convert a variable to some other type:some other type:

► (type) expression(type) expression(float) num1(float) num1

quotient = (float) num1 / quotient = (float) num1 / num2;num2;

Page 85: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Increment / DecrementIncrement / Decrement

►can be combined with assignment:can be combined with assignment: a = a + 5;a = a + 5;a += 5;a += 5; a *= b + 1;a *= b + 1; a = a * (b + 1);a = a * (b + 1);

► increment: increment: ++++►decrement: decrement: ----

a = a + 1; a += 1; a++; ++a;a = a + 1; a += 1; a++; ++a; b = b - 1; b -= 1; b--; --b;b = b - 1; b -= 1; b--; --b;

Page 86: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Input / OutputInput / Output

► input:input:cin >> radius;cin >> radius;

► transfer the value transfer the value that the user has that the user has typed to typed to radiusradius

► multiple values can multiple values can be read in one be read in one statement:statement:cin >> num1 >> cin >> num1 >>

num2;num2;

► output:output:cout << “Area: “cout << “Area: “

<< area << endl;<< area << endl;

► send string or value send string or value of expression to of expression to outputoutput

► endlendl: end line (start : end line (start a new line)a new line)

Page 87: Sunum

Flow ControlFlow Control

Page 88: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Computing RootsComputing Roots

►find the roots of the second degree find the roots of the second degree equation: equation: axax22 + bx + c = 0 + bx + c = 0xx1,21,2= (-b = (-b (b (b22 - 4ac) - 4ac)½½) / (2 * a)) / (2 * a)

►compute discriminant: compute discriminant: bb22 - 4ac - 4ac if negative: “no real roots”if negative: “no real roots” if zero: “two colliding roots at ...”if zero: “two colliding roots at ...” if positive: “two real roots at ...”if positive: “two real roots at ...”

Page 89: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Computing Roots: OutlineComputing Roots: Outline

► variables:variables: aa, , bb and and cc: :

coefficients of the coefficients of the polinompolinom

discdisc: discriminant: discriminant x1 x1 andand x2 x2: real : real

rootsroots

► note the input note the input command:command: 3 variables in one 3 variables in one

input commandinput command

...int main(void){ float a, b, c; float disc; float x1, x2;

std::cout << “Enter coefficients: “;

std::cin >> a >> b >> c; disc = b * b - 4 * a * c; // compute the roots // and report accordingly return EXIT_SUCCESS;}

Page 90: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ConditionsConditions

► logical expression:logical expression: comparison of two arithmetic expressionscomparison of two arithmetic expressions either true or falseeither true or false

►disc < 0disc < 0 if value of if value of discdisc is less than 0, then is less than 0, then truetrue otherwise, otherwise, falsefalse

►true true is represented with 1, is represented with 1, false false with 0with 0 any expression not equal to 0 is any expression not equal to 0 is truetrue

Page 91: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Comparison OperatorsComparison Operators

► equal: equal: x == yx == y► not equal: not equal: x != yx != y► less than: less than: x < yx < y► greater than: greater than: x > yx > y► less or equal: less or equal: x <= x <=

yy► greater or equal:greater or equal:

x >= yx >= y

► ExamplesExamples age >= 18age >= 18 (year % 4) == 0(year % 4) == 0

► works for chars too: works for chars too: only for Englishonly for English

► not for stringsnot for strings► real numbers should real numbers should

not be compared for not be compared for equalityequality

Page 92: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Logical OperatorsLogical Operators

► negating conditions:negating conditions: NOT operator: NOT operator: !! !(age >= 18)!(age >= 18) same as: same as: age < 18age < 18

► combining several combining several conditionsconditions 18 <= x < 6518 <= x < 65 does does

not worknot work 18 <= x18 <= x and and x < 65x < 65

AND operator: AND operator: &&&& OR operator: OR operator: |||| (18 <= x) && (x < (18 <= x) && (x <

65)65) !((18 <= x) && (x < !((18 <= x) && (x <

65))65)) (18 > x) || (x >= 65)(18 > x) || (x >= 65)

► precedence: precedence: ! && ||! && ||► leap year:leap year:

(year % 4 == 0) &&(year % 4 == 0) &&(year % 100 != 0) ||(year % 100 != 0) ||(year % 400 == 0)(year % 400 == 0)

Page 93: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

...if (disc == 0) { x1 = -b / (2 * a); std::cout << “Two colliding roots

at ” << x1 << “\n”;} else { x1 = (-b + sqrt(disc)) / (2 * a); x2 = (-b - sqrt(disc)) / (2 * a); std::cout << “Two real roots at ” << x1 << “ and ” << x2 <<

“\n”;}....

SelectionSelection

if if discdisc is equal to 0 is equal to 0► execute first block: execute first block:

operations for colliding operations for colliding roots (2 statements)roots (2 statements)

if notif not► execute second block: execute second block:

operations for distinct operations for distinct real roots (3 real roots (3 statements)statements)

elseelse block is not block is not obligatoryobligatory

► if true execute block, if true execute block, else do nothingelse do nothing

Page 94: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

SelectionSelection

► one statement blocks one statement blocks don’t need bracesdon’t need braces

► could also be:could also be:if (disc < 0) {if (disc < 0) {

cout << “No real ...”cout << “No real ...”

} else {} else {

......

► NOTE THE NOTE THE INDENTATIONINDENTATION

...

if (disc < 0)

cout << “No real roots.” << endl;

else {

if (disc == 0) {

...

} else {

...

}

}

....

Page 95: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Conditional OperatorConditional Operator

►choose one of two expressionschoose one of two expressionsz = x < y ? x : y;z = x < y ? x : y;

if (x < y)if (x < y)

z = x;z = x;

elseelse

z = y;z = y;

►an operator, not a selection structure!an operator, not a selection structure!

Page 96: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multiple SelectionMultiple Selection

► carry out operation carry out operation specified by userspecified by user

► variablesvariables num1num1, and , and num2num2: :

operandsoperands opop: operator (one of : operator (one of

+ - * / %)+ - * / %) resultresult: result of : result of

operationoperation

...

int main(void)

{

int num1, num2, result;

char op;

cout << “Type the operation: “;

cin >> num1 >> op >> num2;

// carry out operation

cout << “Result: ” << result << endl;

return EXIT_SUCCESS;

}

Page 97: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multiple SelectionMultiple Selection

if (op == ‘+’) {if (op == ‘+’) {

result = num1 + num2;result = num1 + num2;

} else {} else {

if (op == ‘-’) {if (op == ‘-’) {

result = num1 - num2;result = num1 - num2;

} else {} else {

if (op == ‘*’) {if (op == ‘*’) {

........► comparing same expression comparing same expression

with several valueswith several values

switch (op) {switch (op) {

case ‘+’:case ‘+’:

result = num1 + num2;result = num1 + num2;

break;break;

........

case ‘%’:case ‘%’:

result = num1 % num2;result = num1 % num2;

break;break;

default:default:

cout << “No such op” << cout << “No such op” << endl;endl;

return EXIT_FAILURE;return EXIT_FAILURE;

}}

Page 98: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multiple SelectionMultiple Selection

switch (expression) {switch (expression) {

case value_1:case value_1:

block_1;block_1;

break;break;

........

case value_n:case value_n:

block_n;block_n;

break;break;

default:default:

default_block;default_block;

break;break;

}}

block_1 breakY

block_n breakY

case 1

case n

N

default

block

N

Page 99: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multiple SelectionMultiple Selection

► defaultdefault case not case not obligatoryobligatory

► compare with:compare with: integers and charsintegers and chars not real numbers or not real numbers or

stringsstrings not variablesnot variables

► if no if no breakbreak:: continue with block continue with block

of next case!of next case!

block_1Y

block_2 breakY

case 1

case 2

N

N

Page 100: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

GCD (Euclides): OutlineGCD (Euclides): Outline

► variables:variables: num1num1 and and num2num2: :

the numbers for the numbers for which we want to which we want to find the gcdfind the gcd

aa, , bb and and rr: the : the numbers used in numbers used in the repetition part the repetition part of the algorithmof the algorithm

...

int main(void)

{

int num1, num2;

int a, b, r = 1;

cout << “Enter the numbers: “;

cin >> num1 >> num2;

// compute the gcd

cout << “The gcd of “ << num1 << “ and “

<< num2 << “ is “ << a << endl;

return EXIT_SUCCESS;

}

Page 101: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

...

int main(void)

{

...

// determine a and b

while (b > 0) {

r = a % b;

a = b;

b = r;

}

...

}

RepetitionRepetition

► while while bb is greater is greater than 0than 0

► make sure the loop make sure the loop terminates!terminates!

Page 102: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

...

while (true) {

// prepare for check

if (outer termination condition)

break;

// outer loop body

while (true) {

// prepare for check

if (inner termination condition)

break;

// inner loop body

}

// outer loop body

}

...

RepetitionRepetition

► endless loopendless loop check for check for

termination termination conditioncondition

► if met: if met: breakbreak get out of the inmost get out of the inmost

switchswitch, , whilewhile, , do-do-whilewhile or or forfor

not out of not out of ifif

Page 103: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Coin Toss SimulationCoin Toss Simulation

Yi count

N

print heads

print tailstoss

i i + 1

tails tails + 1

Tails

print “Tails”

Heads

heads heads + 1

print “Heads”

Page 104: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline► variables:variables:

countcount: total coin : total coin toss counttoss count

ii: which toss is : which toss is next?next?

numbernumber: used for : used for simulating the tosssimulating the toss

heads heads andand tails tails: : how many heads how many heads and how many and how many tails?tails?

...

int main(void)

{

int count, i;

float number;

int heads = 0, tails = 0;

cout << “How many times to toss? “;

cin >> count;

// toss the coins

cout << “Heads count: “ << heads << endl

<< “Tails count: “ << tails << endl;

return EXIT_SUCCESS;

}

Page 105: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline

► for: repetition blockfor: repetition block► if: selection block 1if: selection block 1► else: selection block else: selection block

22

...

int main(void)

{

...

for (i = 1; i <= count; i++) {

number = (float) rand() / RAND_MAX;

if (number < 0.5) {

cout << “Heads” << endl;

heads++;

} else {

cout << “Tails” << endl;

tails++;

}

}

...

}

Page 106: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Counter-Controlled Counter-Controlled RepetitionRepetition

► repeating a block a repeating a block a number of timesnumber of times

► use a counter: use a counter: ii what is the starting what is the starting

value? value? 11 what is the ending what is the ending

value? value? countcount what is the what is the

increment step? increment step? 11

...

int main(void)

{

...

for (i = 1; i <= count; i++) {

number = (float) rand() / RAND_MAX;

if (number < 0.5) {

cout << “Heads” << endl;

heads++;

} else {

cout << “Tails” << endl;

tails++;

}

}

...

}

Page 107: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Counter-Controlled Counter-Controlled RepetitionRepetition

for (start assignment;for (start assignment;

continue condition;continue condition;

increment) {increment) {

block;block;

}}

start assignment;start assignment;

while (continue condition) {while (continue condition) {

block;block;

increment;increment;

}}

incrementing is done incrementing is done AFTER the execution AFTER the execution of the blockof the block

► the first round is not the first round is not skippedskipped

if condition does not if condition does not hold at the start, hold at the start, block is not executed block is not executed at allat all

increment could be increment could be anythinganything

Page 108: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Random NumbersRandom Numbers

► how to toss a coin?how to toss a coin? produce a random produce a random

number (real) number (real) between 0 and 1between 0 and 1

if smaller than 0.5 if smaller than 0.5 call it “heads”, call it “heads”, otherwise call it otherwise call it “tails”“tails”

► C’s built-in random C’s built-in random number generator:number generator: rand()rand(): generates a : generates a

random number random number (integer) between (integer) between 00 and and RAND_MAXRAND_MAX

rand() / RAND_MAXrand() / RAND_MAX is between 0 and 1is between 0 and 1

1 + rand() % limit1 + rand() % limit

Page 109: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Random NumbersRandom Numbers

► random numbers are random numbers are generated in a generated in a sequencesequence r0 r1 r2 r3 .........r0 r1 r2 r3 ......... each number is each number is

computed using the computed using the number that precedes number that precedes is in the sequenceis in the sequence

to start the sequence to start the sequence we need a we need a seedseed (r0) (r0)

► same seed results same seed results in same sequencein same sequence srand()srand(): sets seed: sets seed we need a different we need a different

seed for each seed for each executionexecution

time()time(): number of : number of seconds since Jan 1, seconds since Jan 1, 19701970

► input parameter: input parameter: NULLNULL

Page 110: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Random NumbersRandom Numbers

► to use to use srand()srand() and and rand()rand(), we , we need need stdlib.hstdlib.h

► to use to use time()time(), , we need we need time.htime.h

#include <iostream>

#include <stdlib.h>

#include <time.h>

...

int main(void)

{

...

srand(time(NULL));

...

number = (float) rand() / RAND_MAX;

...

}

Page 111: Sunum

Derived Data TypesDerived Data Types

Page 112: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Programmer-Defined TypesProgrammer-Defined Types

►programming languages provide basic programming languages provide basic data types: data types: int, float, bool, ...int, float, bool, ...

►they also provide mechanisms for they also provide mechanisms for defining our own data typesdefining our own data types give an existing data type a new namegive an existing data type a new name combine existing data types to form a combine existing data types to form a

new data typenew data type

Page 113: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

New Names for TypesNew Names for Types

►typedef existing_type new_name;typedef existing_type new_name; student scores in an exam:student scores in an exam:

int midterm1, midterm2, final;int midterm1, midterm2, final;

create a new data type score_t:create a new data type score_t:typedef int score_t;typedef int score_t;

score_t midterm1, midterm2, final;score_t midterm1, midterm2, final;

►old type name is still validold type name is still valid

Page 114: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AdvantagesAdvantages

►understanding is easierunderstanding is easier►changing is easierchanging is easier

later we decide we need real numbers for later we decide we need real numbers for student scores:student scores:typedef float score_t;typedef float score_t;

change at one point instead of going change at one point instead of going through the whole codethrough the whole code

Page 115: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Craps SimulationCraps Simulation

►player rolls dice:player rolls dice: if 7 or 11: player winsif 7 or 11: player wins if 2, 3 or 12: player losesif 2, 3 or 12: player loses otherwise sum is player’s “point”otherwise sum is player’s “point”

►player rolls again until:player rolls again until: point: player winspoint: player wins 7: player loses7: player loses

Page 116: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline

► variables:variables: die1die1, , die2die2 and and sumsum: :

value of first and value of first and second dice and second dice and their sumtheir sum

pointpoint: player’s point: player’s point game_statusgame_status: :

continue / win / losecontinue / win / lose

...

// type definitions

...

int main(void)

{

int die1, die2, sum, point;

status_t game_status;

// first roll

// check outcome

// continue to roll while not determined

// report

return EXIT_SUCCESS;

}

Page 117: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Enumerated TypeEnumerated Type

►game can be in one of three statesgame can be in one of three states►how to represent the states?how to represent the states?

encode (assign a value to each state)encode (assign a value to each state)#define GAME_CONTINUES 0#define GAME_CONTINUES 0

#define PLAYER_WINS 1#define PLAYER_WINS 1

#define PLAYER_LOSES 2#define PLAYER_LOSES 2

values don’t matter as long as they are values don’t matter as long as they are differentdifferent

Page 118: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Enumerated TypeEnumerated Type

►defining a group of constants in one defining a group of constants in one statement:statement: enum { constant definitions };enum { constant definitions };

enum { GAME_CONTINUES = 0,enum { GAME_CONTINUES = 0,

PLAYER_WINS = 1,PLAYER_WINS = 1,

PLAYER_LOSES = 2 };PLAYER_LOSES = 2 };

►same as using multiple same as using multiple #define#define statementsstatements

Page 119: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Enumerated TypeEnumerated Type

► if constant values are omitted:if constant values are omitted: first constant is 0, subsequent ones are first constant is 0, subsequent ones are

incremented by 1incremented by 1enum { GAME_CONTINUES,enum { GAME_CONTINUES,

PLAYER_WINS, PLAYER_LOSES };PLAYER_WINS, PLAYER_LOSES };

any omitted value is 1 more than the one any omitted value is 1 more than the one beforebeforeenum { JAN = 1, FEB, ... DEC };enum { JAN = 1, FEB, ... DEC };

Page 120: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Enumerated TypeEnumerated Type►giving a group of constants a type giving a group of constants a type

name:name: enum tag { constant definitions };enum tag { constant definitions };

enum status_e { GAME_CONTINUES,enum status_e { GAME_CONTINUES,

PLAYER_WINS, PLAYER_LOSES };PLAYER_WINS, PLAYER_LOSES };

name of new type: name of new type: enum tagenum tag

►variables can be defined of this type:variables can be defined of this type:enum status_e game_status=GAME_CONTINUES;enum status_e game_status=GAME_CONTINUES;

►variables can take any valuevariables can take any valuegame_status = 25;game_status = 25;

Page 121: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Enumerated TypeEnumerated Type► enumerated enumerated

type type declarations declarations are made are made right after right after the the #include#include statementsstatements

#include ...

...

enum status_e { GAME_CONTINUES,

PLAYER_WINS, PLAYER_LOSES };

typedef enum status_e status_t;

...

int main(void)

{

...

status_t game_status = GAME_CONTINUES;

....

}

Page 122: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

switch (sum) {

case 7:

case 11:

game_status = PLAYER_WINS;

break;

case 2:

case 3:

case 12:

game_status = PLAYER_LOSES;

break;

default:

game_status = GAME_CONTINUES;

point = sum;

break;

}

Fall-Through CasesFall-Through Cases► intentionally intentionally

leaving out leaving out breakbreak statements in statements in casescases

► cases are cases are groupedgrouped

Page 123: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

// first roll

// if win or lose skip the loop below

while (game_status == GAME_CONTINUES) {

// roll again

if (sum == point)

game_status = PLAYER_WINS;

else {

if (sum == 7)

game_status = PLAYER_LOSES;

}

}

// either loop was skipped: win / lose

// or we got out of loop: win / lose

End of ProgramEnd of Program► is it possible is it possible

that this that this program will program will run forever?run forever?

Page 124: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Parallel ResistorsParallel Resistors

►compute the equivalent of several compute the equivalent of several parallel resistors:parallel resistors: 1 / R = 1 / R1 + 1 / R2 + ... + 1 / Rn1 / R = 1 / R1 + 1 / R2 + ... + 1 / Rn R = 1 / (1 / R1 + 1 / R2 + ... + 1 / Rn)R = 1 / (1 / R1 + 1 / R2 + ... + 1 / Rn)

►resistor values are input by the userresistor values are input by the user►when finished the user will input 0when finished the user will input 0

Page 125: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline► variables:variables:

resistorresistor: resistor : resistor value typed by the value typed by the useruser

sumsum: sum of 1/Ri : sum of 1/Ri so farso far

aa, , bb and and rr: used to : used to find the gcd for find the gcd for simplifying the simplifying the fractionfraction

ii: counter: counter

...

// type definitions

...

int main(void)

{

int resistor;

rational_t sum = { 0, 1 };

int a, b, r;

int i = 0;

// get resistor values from user

// and compute the equivalent

// report

return EXIT_SUCCESS;

}

Page 126: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

InputInput► endless loop:endless loop:

break when user break when user types 0types 0

► how would you how would you reorganize this reorganize this code without code without using endless using endless loop?loop?

...

while (true) {

cout << “Enter resistor value: “;

cin >> resistor;

if (resistor == 0)

break;

// add the new resistor value

// to the sum so far

// simplify the sum

}

Page 127: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StructuresStructures

►combining existing data types to form combining existing data types to form a new data type:a new data type: struct tag { field declarations };struct tag { field declarations }; rational numbers:rational numbers:

struct rational_s {struct rational_s {

int nom;int nom;

int denom;int denom;

};};

name of new type: name of new type: struct tagstruct tag

Page 128: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StructuresStructures

►field declarations are NOT variable field declarations are NOT variable definitions!!!definitions!!!

0

nom

1

denom

struct

rational_s

sum no memory is allocated no memory is allocated

until a variable of this type until a variable of this type is defined!is defined!struct rational_s sum;struct rational_s sum;

initial values can be given initial values can be given in curly braces:in curly braces:struct rational_s sum = { 0, 1 struct rational_s sum = { 0, 1

};};

Page 129: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StructuresStructures► structure structure

declarations are declarations are made right after made right after the the #include#include statementsstatements

#include ...

...

struct rational_s {

int nom, denom;

};

typedef struct rational_s rational_t;

...

int main(void)

{

...

rational_t sum = { 0, 1 };

....

}

Page 130: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StructuresStructures► fields of a fields of a

structure variable structure variable are accessed are accessed using the dotted using the dotted notationnotation

...

while (true) {

// get next resistor value

sum.nom = sum.nom * resistor

+ sum.denom;

sum.denom *= sum.denom * resistor;

// find gcd of sum.nom and

// sum.denom (gcd is in a)

sum.nom = sum.nom / a;

sum.denom = sum.denom / a;

}

...

/// print sum.denom / sum.nom

Page 131: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Nested StructuresNested Structuresenum month_e { JAN = 1, FEB, .. DEC };

typedef enum month_e month_t;

struct date_s {

int day;

month_t month;

int year;

};

typedef struct date_s date_t;

struct acyear_s {

date_t begin, end;

};

typedef struct acyear_s acyear_t;

day

month

begin

year

day

month

year

end

acyear2002

Page 132: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Assigning StructuresAssigning Structures

► instead of assigning fields one-by-one:instead of assigning fields one-by-one:acyear2002.end.day = acyear2002.begin.day;acyear2002.end.day = acyear2002.begin.day;

acyear2002.end.month = acyear2002.end.month = acyear2002.begin.month;acyear2002.begin.month;

acyear2002.end.year = acyear2002.begin.year;acyear2002.end.year = acyear2002.begin.year;

►a structure can be assigned to another a structure can be assigned to another structure in one assignment:structure in one assignment:

acyear2002.end = acyear2002.begin;acyear2002.end = acyear2002.begin;

acyear2003 = acyear2002;acyear2003 = acyear2002;

Page 133: Sunum

ArraysArrays

Page 134: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Statistical CalculationsStatistical Calculations

►get student scores in an exam from get student scores in an exam from useruser

►calculate mean, variance, standard calculate mean, variance, standard deviation and absolute deviationdeviation and absolute deviation

Page 135: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Statistics: Statistics

► variables:variables: scorescore: : array for array for

student scoresstudent scores no_studentsno_students: : number number

of studentsof students meanmean, , variancevariance, ,

std_devstd_dev and and abs_devabs_dev: : desired resultsdesired results

totaltotal, , sqr_totalsqr_total and and abs_totalabs_total: : sums in sums in the formulathe formula

ii: : loop counterloop counter

...#define MAXSTUDENTS 100...int main(void){ int score[MAXSTUDENTS]; int no_students; float mean, variance, std_dev, abs_dev; float total = 0.0, sqr_total = 0.0, abs_total = 0.0; int i;

// calculate and report return EXIT_SUCCESS;}

Page 136: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Statistics: Statistics

► to calculate the to calculate the standard and standard and absolute deviations, absolute deviations, we need the meanwe need the mean

► user input and user input and mean calculation mean calculation can be done in the can be done in the same loopsame loop

► both deviations can both deviations can be calculated in the be calculated in the same loopsame loop

...int main(void){ // variable definitions

// get the scores // and calculate the mean

// calculate the standard // and absolute deviations

return EXIT_SUCCESS;}

Page 137: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Why Use an Array?Why Use an Array?

►to calculate the standard and absolute to calculate the standard and absolute deviations, we also need all student deviations, we also need all student scoresscores we may not “forget” after reading and we may not “forget” after reading and

adding to the sumadding to the sum

► imagine using separate variables for imagine using separate variables for each scoreeach score

Page 138: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Array DefinitionArray Definition

type array_name[number];type array_name[number];►type is the type of type is the type of eacheach element element►number is the number of elementsnumber is the number of elements

define an array variable score with MAXSTUDENTS elements where each element is an integer

int int score[MAXSTUDENTS];score[MAXSTUDENTS];

Page 139: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory AllocationMemory Allocation

►memory space to hold this array will memory space to hold this array will be allocated at the start of executionbe allocated at the start of execution

►number of elements must be a number of elements must be a constantconstant score

MAXSTUDENTS

int int int

Page 140: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory AllocationMemory Allocation

►we must estimate the maximum we must estimate the maximum possible array size:possible array size: actual size is no_students, array size is actual size is no_students, array size is

MAXSTUDENTSMAXSTUDENTS

►actual size is smaller: waste memoryactual size is smaller: waste memory►actual size is larger: won’t work actual size is larger: won’t work

limitationlimitation ““in a class with at most 100 students”in a class with at most 100 students”

Page 141: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Array Array InitialInitializationization

► initial value can be initial value can be given ingiven in curly curly braces:braces:int score[MAXSTUDENTS] = {int score[MAXSTUDENTS] = { 85,85, 71,71, .....,.,

3333 };};

int score[MAXSTUDENTS] = { 0 };int score[MAXSTUDENTS] = { 0 };85 71 33

score

MAXSTUDENTS

int int int

Page 142: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Implicit DefinitionImplicit Definition

►number of elements can be omitted if number of elements can be omitted if initial value is specified:initial value is specified:type array_name[] = { initial_values };type array_name[] = { initial_values };

►compiler counts the number in the list compiler counts the number in the list and determines the array sizeand determines the array size DANGEROUSDANGEROUS!!!!!!

Page 143: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Accessing ElementsAccessing Elements

►elements are accessed by specifying elements are accessed by specifying their index in square brackets:their index in square brackets:score[17] = 55;score[17] = 55;

x = 5 * score[43];x = 5 * score[43];

► index expressions can contain index expressions can contain variables:variables:cin >> score[i];cin >> score[i];

Page 144: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Array Array IndexingIndexing

►the index of first element is always 0the index of first element is always 0►the index of last element is always 1 the index of last element is always 1

less than the array sizeless than the array size in an array with n elements, there is no in an array with n elements, there is no

element with index n or greater!element with index n or greater!

score

0 1 99

Page 145: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Bounds CheckingBounds Checking

►the compiler does NOT check whether the compiler does NOT check whether the index is within the bounds!!!the index is within the bounds!!! accessing an element: start from the accessing an element: start from the

beginning and proceed index elementsbeginning and proceed index elements if not within bounds: overwrite other if not within bounds: overwrite other

variable or segmentation faultvariable or segmentation faultscore

0 1 99

Page 146: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Array LoopsArray Loops

► typical loop for an typical loop for an array with size n:array with size n:for (i = 0;for (i = 0; i < n; i++)i < n; i++)

► read into read into iith th element, but tell the element, but tell the user user i+1i+1

► same counter same counter variable for both variable for both loops (not always)loops (not always)

for (i = 0; i < no_students; i++) { cout << “Score of student “ << i + 1 << “: “; cin >> score[i]; total += score[i];}

mean = total / no_students;for (i = 0; i < no_students; i++) { sqr_total += sqr(score[i] - mean); abs_total += fabs(score[i] - mean);}

variance = sqr_total / (no_students - 1);std_dev = sqrt(variance);abs_dev = abs_total / no_students;

Page 147: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: String Reversing: String Reversing

► get a sentence from get a sentence from the user, reverse the user, reverse and printand print

► variables:variables: sentencesentence: sentence : sentence

to be reversedto be reversed lenlen: length of : length of

sentencesentence ii: loop counter: loop counter tmptmp: temporary : temporary

variable for swapvariable for swap

...#define MAXLENGTH 80...int main(void){ char sentence[MAXLENGTH]; int len, i; char tmp;

cout << “Enter the sentence: “; gets(sentence); // reverse and report return EXIT_SUCCESS;}

Page 148: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

StringsStrings

►strings are character arraysstrings are character arrays►the end of a string is marked using the end of a string is marked using ‘\0’‘\0’

a string can hold at most 1 less characters a string can hold at most 1 less characters than the array sizethan the array size

‘T’ ‘e’

sentence

‘s’ ‘t’ ‘i’ ‘n’ ‘\0’

0 1 2 3

‘ g’ ‘ ’ ‘o’ ‘n’ ‘e’

4 5 6 7 8 9 1011 12 78 79

Page 149: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

String String InitialInitializationization

►strings variables can be initialized:strings variables can be initialized:char sentence[MAXLENGTH] = “Testing char sentence[MAXLENGTH] = “Testing

one”;one”;

char sentence[] = “Testing one”;char sentence[] = “Testing one”;

►same as:same as:char sentence[12] = “Testing one”char sentence[12] = “Testing one”

‘T’ ‘e’

sentence

‘s’ ‘t’ ‘i’ ‘n’ ‘\0’

0 1 2 3

‘ g’ ‘ ’ ‘o’ ‘n’ ‘e’

4 5 6 7 8 9 1011

Page 150: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

String InputString Input

► if string can contain spaces, if string can contain spaces, cincin will will only take the part up to the first spaceonly take the part up to the first space

►use use getsgets to read in a string with to read in a string with spacesspaces

►getsgets does NOT check the size! does NOT check the size! user can type a string longer than you user can type a string longer than you

have allocated for the stringhave allocated for the string

Page 151: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

String LibraryString Library

►since strings are arrays, you can not since strings are arrays, you can not simply assign or check for equalitysimply assign or check for equality

►use string library functions instead:use string library functions instead: strlen(s)strlen(s): length of string : length of string ss strcpy(dest,src)strcpy(dest,src): copy content of : copy content of srcsrc to to

destdest strcat(dest,src)strcat(dest,src): append content of : append content of srcsrc to to

end of end of destdest►destdest must have enough memory allocated! must have enough memory allocated!

Page 152: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

String LibraryString Library

strcmp(s1,s2)strcmp(s1,s2): compare contents of : compare contents of s1s1 and and s2s2::s1 = s2: 0s1 = s2: 0

s1 < s2: < 0s1 < s2: < 0

s1 > s2: > 0s1 > s2: > 0

length checking versions of these length checking versions of these functions:functions: strncpy strncat strncmpstrncpy strncat strncmp

Page 153: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ReversingReversing

►swap swap iith character from the beginning th character from the beginning with with iith character from the endth character from the end

►continue until the middlecontinue until the middle

‘T’ ‘e’ ‘s’ ‘t’ ‘i’ ‘n’ ‘\0’

0 1 2 3

‘ g’ ‘ ’ ‘o’ ‘n’ ‘e’

4 5 6 7 8 9 1011

Page 154: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Matrix Multiplication: Matrix Multiplication

► variables:variables: leftleft and and rightright: matrices : matrices

to be multipliedto be multiplied productproduct: result of : result of

multiplicationmultiplication rlrl, , clcl, , rrrr and and crcr: actual : actual

row and column sizes of row and column sizes of left and right matricesleft and right matrices

► rrrr must always be equal must always be equal to to clcl

ii, , jj and and kk: loop counters: loop counters

...#define MAXSIZE 30...int main(void){ int left[MAXSIZE][MAXSIZE], right[MAXSIZE][MAXSIZE], product[MAXSIZE][MAXSIZE] =

{ 0 }; int rl, cl, cr; int &rr = cl; int i, j, k;

// get matrices // multiply // print result return EXIT_SUCCESS;}

Page 155: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multidimensional ArraysMultidimensional Arrays

►a matrix is a two-dimensional arraya matrix is a two-dimensional array►the size of each dimension is specified the size of each dimension is specified

in square bracketsin square brackets initial values in bracesinitial values in braces

define a two-dimensional array variable define a two-dimensional array variable named named ““leftleft””, where the first dimension , where the first dimension has size 30, the second dimension has has size 30, the second dimension has size 30 and each element is an integersize 30 and each element is an integer

int left[30][30];

Page 156: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory LayoutMemory Layout

►the matrix will have rows * columns the matrix will have rows * columns elements, placed consecutively in elements, placed consecutively in memory:memory:left

0,0 0,1 0,29 1,0 1,1

28,28 28,29 29,0 29,2829,29

Page 157: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multidimensional Array Multidimensional Array IndexingIndexing

►a matrix could also be considered as a matrix could also be considered as an array of arraysan array of arrays left is an array with 30 elements where left is an array with 30 elements where

each element is an array of 30 integerseach element is an array of 30 integers left[0] is an array of 30 integersleft[0] is an array of 30 integers

►each dimension is indexed separatelyeach dimension is indexed separately left[i][j]left[i][j]: element on the : element on the iith row and th row and jjth th

columncolumn

Page 158: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multidimensional Array LoopsMultidimensional Array Loops

► nested loops:nested loops: i becomes 0i becomes 0

► j varies j varies fromfrom 0 0 to to cl - cl - 11

i becomes 1i becomes 1► j starts over and j starts over and

varies between 0 and varies between 0 and cl - 1cl - 1

...... i becomes 29i becomes 29

► j starts overj starts over

cin >> rl >> cl >> cr;

for (i = 0; i < rl; i++) { for (j = 0; j < cl; j++) { cout << ... cin >> left[i][j]; }}

for (i = 0; i < rr; i++) { for (j = 0; j < cr; j++) { cout << ... cin >> right[i][j]; }}

Page 159: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Matrix Matrix AdditionAddition

► both left and right both left and right matrices must have the matrices must have the same dimensions (same dimensions (rlrl and and clcl))

► the the sumsum matrix will matrix will havehave the same the same dimensionsdimensions

► for each entry in the for each entry in the result, result, add the add the corresponding corresponding elements of theelements of the leftleft andand rightright matri matricesces

for (i = 0; i < rl; i++) { for (j = 0; j < cl; j++) { sum[i][j] = left[i][j] + right[i]

[j]; }}

Page 160: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Matrix Matrix TranspositionTransposition

► on the left matrixon the left matrix► the the transpositiontransposition

matrix will havematrix will have clcl rows rows and and rlrl columns columns

► how about storing the how about storing the result in the same result in the same matrix?matrix?

► is this code correct?is this code correct?

for (i = 0; i < cl; i++) { for (j = 0; j < rl; j++) { trans[i][j] = left[j][i]; }}

for (i = 0; i < cl; i++) { for (j = 0; j < rl; j++) { left[i][j] = left[j][i]; }}

Page 161: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Matrix MultiplicationMatrix Multiplication

► the product matrix the product matrix will have will have rlrl rows and rows and crcr columns columns

► for each entry in the for each entry in the result, multiply and result, multiply and add the add the iith row of th row of the left matrix with the left matrix with the the jjth column of th column of the right matrixthe right matrix clcl multiply / add multiply / add

operationsoperations

for (i = 0; i < rl; i++) { for (j = 0; j < cr; j++) { for (k = 0; k < cl; k++) product[i][j] += left[i][k] * right[k][j]; }}

Page 162: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ReferencesReferences

►a new name for a variablea new name for a variable same memory locationsame memory location changing one also changes the otherchanging one also changes the other

cl rrrr is a new name for the cl rr is a new name for the cl variablevariable

int &rr = cl;

Page 163: Sunum

FunctionsFunctions

Page 164: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

AbstractionAbstraction

►only one function until now: only one function until now: mainmain►for larger tasks, main task is divided for larger tasks, main task is divided

into subtasksinto subtasks►each (sub)task is implemented using a each (sub)task is implemented using a

functionfunction

Page 165: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ParametersParameters

► several input parametersseveral input parameters sqrt: one (number)sqrt: one (number) pow: two (base and power)pow: two (base and power) rand: nonerand: none srand: one (seed)srand: one (seed)

► at most one output parameterat most one output parameter sqrt: one (square root of number)sqrt: one (square root of number) pow: one (result of exponentiation)pow: one (result of exponentiation) rand: one (random number)rand: one (random number) srand: nonesrand: none

Page 166: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function CallFunction Call

►calling function (caller)calling function (caller)►called function (callee)called function (callee)

main function calls rand functionmain function calls rand function►main is the calling functionmain is the calling function►rand is the called functionrand is the called function

►after the called function is finished, the after the called function is finished, the calling function resumes execution calling function resumes execution with the next statementwith the next statement

Page 167: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Parameter PassingParameter Passing

► calling function calling function passespasses the input the input parameters to the parameters to the called functioncalled function

► called function called function returnsreturns the output the output parameter back to parameter back to the calling functionthe calling function

► what to do with the what to do with the return value?return value? assign it to a variable:assign it to a variable:

number = rand();number = rand();

use it in an use it in an expression:expression:

die = 1 + rand() % 6;die = 1 + rand() % 6;

pass it to another pass it to another function as input function as input parameter:parameter:

srand(time(NULL));srand(time(NULL));

Page 168: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Type CompatibilityType Compatibility

► type of the returned type of the returned value should be value should be compatible with its compatible with its usage in the calling usage in the calling function:function:pow(x, y) % mpow(x, y) % m

► input parameter list input parameter list should also be should also be compatible:compatible: number of number of

parametersparameterspow(x, y, z)pow(x, y, z)

types and order of types and order of parametersparameters

strlen(50)strlen(50)

Page 169: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Factorization: Factorization

► mainmain function gets the function gets the number from the user, number from the user, factorizes it and prints factorizes it and prints the factorsthe factors

► is_primeis_prime function function checks whether its checks whether its input parameter is input parameter is prime or notprime or not

► next_primenext_prime function function returns the first prime returns the first prime number greater than its number greater than its input parameterinput parameter

...int next_prime(int prime);...int main(void){ ...}

bool is_prime(int cand){ ...}

int next_prime(int prime){ ...}

Page 170: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Main Function: Main Function

► variables:variables: numbernumber: number to : number to

be factorizedbe factorized factorfactor: prime factor : prime factor

candidatecandidate

► we do not care HOW we do not care HOW next_primenext_prime works! works!

...int main(void){ int number, factor = 2;

cout << …; cin >> number; while (number > 1) { while (number % factor == 0) { cout << factor << “ “; number = number / factor; } factor = next_prime(factor); } cout << endl; return EXIT_SUCCESS;}

Page 171: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function ComponentsFunction Components

►header: WHAT does this function do?header: WHAT does this function do? name of functionname of function types and order of input parameterstypes and order of input parameters type of output parametertype of output parameter compiler needs this information in order compiler needs this information in order

to do type checkingto do type checking

►body: HOW does this function work?body: HOW does this function work? block of statementsblock of statements

Page 172: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function DeclarationFunction Declaration

►specifying the function header:specifying the function header:output_parameter_type output_parameter_type

function_name(input_parameter_list);function_name(input_parameter_list);►note the semicolon!note the semicolon!►output parameter type can not be an output parameter type can not be an

arrayarray► if no output parameter:if no output parameter:

void function_name(input_parameter_list);void function_name(input_parameter_list);► if no input parameter:if no input parameter:

output_parameter_type function_name(void);output_parameter_type function_name(void);

Page 173: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Example DeclarationsExample Declarations

double sqrt(double x);double sqrt(double x);double pow(double x, double y);double pow(double x, double y);int rand(void);int rand(void);void srand(unsigned int seed);void srand(unsigned int seed);int next_prime(int prime);int next_prime(int prime);

►careful: type of each parameter must careful: type of each parameter must be given separatelybe given separately

► INCORRECT:INCORRECT:double pow(double x, y);double pow(double x, y);

Page 174: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function DefinitionFunction Definition

► the first line is the the first line is the headerheader without the without the

semicolon!!!semicolon!!!

► output parameter is output parameter is passed back to the passed back to the caller using caller using returnreturn multiple return multiple return

statements allowedstatements allowed

► we do not care HOW we do not care HOW is_primeis_prime works works

...int next_prime(int prime){ int cand;

cand = (prime == 2) ? 3 : prime + 2;

while (!is_prime(cand)) cand += 2; return cand;}

Page 175: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function DefinitionFunction Definition

► 2 is prime2 is prime► any other even any other even

number is not primenumber is not prime► try all odd numbers try all odd numbers

between 3 and the between 3 and the square rootsquare root if any of them if any of them

divides the number, divides the number, it is not primeit is not prime

► otherwise it is primeotherwise it is prime

...bool is_prime(int cand){ int count;

if (cand == 2) return true; if (cand % 2 == 0) return false; for (count = 3; count * count <= cand; count += 2) { if (cand % count == 0) return false; } return true;}

Page 176: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Function Call RuleFunction Call Rule

► either the declarationeither the declaration► or the definitionor the definition

of the called function of the called function must be placed before must be placed before the calling functionthe calling function main can call next_primemain can call next_prime next_prime can call next_prime can call

is_primeis_prime main can NOT call main can NOT call

is_primeis_prime

► header files contain the header files contain the function headersfunction headers

...int next_prime(int prime);...int main(void){ ...}

bool is_prime(int cand){ ...}

int next_prime(int prime){ ...}

Page 177: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Parameter PassingParameter Passing

► each expression each expression listed in the function listed in the function call is assigned to call is assigned to the corresponding the corresponding input parameterinput parameter

► call by valuecall by value

► main:main:factor=next_prime(factofactor=next_prime(facto

r);r); factor in main –factor in main –>>

prime in next_primeprime in next_prime

► factor:factor:return cand;return cand; cand in next_prime –cand in next_prime –>>

factor in mainfactor in main

Page 178: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PParameter Passingarameter Passing

►any expression can be passed as input any expression can be passed as input parameter as long as types are parameter as long as types are compatible:compatible:is_prime(13)is_prime(13)

is_prime(cand + 1)is_prime(cand + 1)

►same for output parameter:same for output parameter:return cand + 2;return cand + 2;

Page 179: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ScopeScope

► each variable can only be accessed in the each variable can only be accessed in the function in which is it defined:function in which is it defined: ““factor in main”factor in main”

► variables in different functions can have the variables in different functions can have the same namesame name ““cand in next_prime”, “cand in is_prime”cand in next_prime”, “cand in is_prime”

► scopescope: the part of the program where that : the part of the program where that variable can be accessedvariable can be accessed

► variables “live” within their scope:variables “live” within their scope: memory will be allocated when entering functionmemory will be allocated when entering function and freed when exiting the functionand freed when exiting the function

Page 180: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Local VariablesLocal Variables

►any variable defined in the function any variable defined in the function bodybody

► input parametersinput parameters

number factor

2

main

2

prime cand

3

next_prime

3

cand count

3

is_prime

Page 181: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Global VariablesGlobal Variables

► any variable defined any variable defined outside all functionsoutside all functions the scope is the the scope is the

entire program (all entire program (all functions)functions)

if any function if any function changes the value, changes the value, all functions will be all functions will be affectedaffected

...int cand = 2;...int main(void){ ...}

bool is_prime(void){ ...}

int next_prime(void){ ...}

Page 182: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Global VariablesGlobal Variables

►candcand is accessible by is accessible by mainmain, , next_primenext_prime and and is_primeis_prime what are the new functions of what are the new functions of next_primenext_prime

and and is_primeis_prime??

number factor

mainprimecand

next_prime

count

is_prime

Page 183: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Call by ReferenceCall by Referencevoid swap(int x, int y){ int tmp;

tmp = x; x = y; y = tmp;}

int main(void){ int m, n; ... swap(m, n); ...}

► changes to input changes to input parameters in the parameters in the called function do not called function do not affect variables in the affect variables in the calling functioncalling function xx and and yy in the in the swapswap

function are swappedfunction are swapped mm and and nn in the in the mainmain

function do not changefunction do not change► if they should affect:if they should affect:

void swap(int &x, int &y)void swap(int &x, int &y)

Page 184: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: GCD using FactorizationOutline: GCD using Factorization

► mainmain function: function: get numbers from the get numbers from the

useruser call call factorizefactorize to factor to factor

the first numberthe first number call call factorizefactorize to factor to factor

the second numberthe second number call call gcd_factorsgcd_factors to find to find

the common factorsthe common factors compute and print the compute and print the

gcdgcd

...void factorize(...);void gcd_factors(...);

int main(void){ ...}

void factorize(...){ ...}

void gcd_factors(...){ ...}

Page 185: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Factor Data StructureFactor Data Structure

► a factor consists of a factor consists of two integer fields:two integer fields: basebase, , powerpower

► factorize function is factorize function is similar to similar to mainmain in the in the previous exampleprevious example counts the counts the powerpower

valuevalue next_primenext_prime and and

is_primeis_prime are identical are identical

#include <iostream>...

#define MAXFACTOR 50

struct factor_s { int base, power;};typedef struct factor_s factor_t;

...

int main(void){

...

Page 186: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: mainOutline: main

► variables:variables: number1number1, , number2number2: :

numbers to be factorizednumbers to be factorized factors1factors1, , factors2factors2: factors : factors

of of number1number1 and and number2number2 factors3factors3: factors of gcd: factors of gcd n1n1, , n2n2, , n3n3: actual element : actual element

counts of factors1, counts of factors1, factors2factors2 and and factors3factors3

► factorizefactorize should return should return the list of factorsthe list of factors arrays can not be returnedarrays can not be returned number of elements number of elements

should also be returnedshould also be returned► same goes for same goes for

gcd_factorsgcd_factors

...int main(void){ int number1, number2; factor_t factors1[MAXFACTOR], factors2[MAXFACTOR], factors3[MAXFACTOR]; int n1, n2, n3; long int gcd = 1L; int i;

…}...

Page 187: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Using Input Parameters for Using Input Parameters for OutputOutput

► use the input use the input parameters to send the parameters to send the necessary values to the necessary values to the calling functioncalling function

► redefine redefine factorizefactorize:: factors the first input factors the first input

parameter, stores the parameter, stores the factors in the elements of factors in the elements of the second input the second input parameter (an array) and parameter (an array) and stores the number of stores the number of elements in the third elements in the third input parameterinput parameter

does not return any valuedoes not return any value

int main(void){ …

factorize(number1, factors1, n1); factorize(number2, factors2, n2); gcd_factors(factors1, n1, factors2, n2, factors3, n3); for (i = 0; i < n3; i++) gcd = gcd * pow( (double) factors3[i].base, (double) factors3[i].power); ...}

Page 188: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Passing Arrays as Input Passing Arrays as Input ParametersParameters

► to indicate that an to indicate that an input variable is an input variable is an array: square array: square brackets after the brackets after the namename..., factor_t factors[], ......, factor_t factors[], ...

► unless explicitly unless explicitly prohibited, elements prohibited, elements of an input array CAN of an input array CAN be changedbe changed use use constconst to prohibit to prohibit

...void factorize(int x, factor_t factors[], int &n){ int factor = 2;

n = 0; while (x > 1) { if (x % factor == 0) { factors[n].base = factor; factors[n].power = 0; while (x % factor == 0) { factors[n].power++; x = x / factor; } n++; } factor = next_prime(factor); }}...

Page 189: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: gcd_factorsOutline: gcd_factors

► we can assume we can assume that that factors1factors1 and and factors2factors2 are in are in ascending orderascending order

► i1i1 and and i2i2: index of : index of next element in next element in factors1factors1 and and factors2factors2

void gcd_factors(const factor_t factors1[], int n1,

const factor_t factors2[], int n2,

factor_t factors[], int &n){ int i1 = 0, i2 = 0;

n = 0; while ((i1 < n1) && (i2 < n2)) { // compare the factors // and choose one if common }}

Page 190: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Finding the Common FactorsFinding the Common Factors

► at each step:at each step: advance the one advance the one

with the smaller with the smaller basebase

if bases are equal, if bases are equal, choose the one with choose the one with smaller power and smaller power and advance bothadvance both

n = 0; while ((i1 < n1) && (i2 < n2)) { if (factors1[i1].base factors[i2].base) i1++; else if (factors1[i1].base >

factors[i2].base) i2++; else { factors[n].base = factors[i1].base; if (factors[i1].power

factors2[i2].power) factors[n].power =

factors1[i1].power; else factors[n].power =

factors2[i2].power; i1++; i2++; n++; } }

Page 191: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

C/C++ DifferencesC/C++ Differences

► functions with the functions with the same name:same name: in C: not allowedin C: not allowed in C++: allowed if in C++: allowed if

input parameters are input parameters are differentdifferent

► default parameters:default parameters: assume 0 for assume 0 for startstart if if

not specifiednot specified find_charfind_char can take 2 can take 2

or 3 parametersor 3 parameters

int find_char(char s[], char c, int start = 0){ int index = -1, i;

for (i = start; s[i] != ‘\0’; i++) { if (s[i] == c) { index = i; break; } } return index;}

Page 192: Sunum

PointersPointers

Page 193: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Static VariablesStatic Variables

►size must be known at compile-timesize must be known at compile-time size of array must be constantsize of array must be constant waste of memory space - limitationwaste of memory space - limitation

►memory is allocated on entering the memory is allocated on entering the function and released on exitfunction and released on exit variables of variables of mainmain live throughout the live throughout the

whole executionwhole execution may not be needed all at oncemay not be needed all at once

Page 194: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Dynamic VariablesDynamic Variables

►allocate memory when needed, allocate memory when needed, release when donerelease when done do memory management yourselfdo memory management yourself error-prone process, especially for error-prone process, especially for

beginnersbeginners

►allocate as much memory as is allocate as much memory as is needed:needed: determine size at run-time instead of determine size at run-time instead of

compile-timecompile-time

Page 195: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PointersPointers

►pointer is an ordinary variablepointer is an ordinary variable► its value is the address of a memory its value is the address of a memory

cellcellp

422 422 8000

p

120008000

Page 196: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Pointer OperatorsPointer Operators

► pointer: an addresspointer: an address► pointer’s content: a pointer’s content: a

value of some typevalue of some type ** operator: dereferencing operator: dereferencing

► address of a variable:address of a variable: && operator operator

► special value: special value: NULLNULL is not a valid addressis not a valid address can not be dereferencedcan not be dereferenced

p: 8000p: 8000

*p: 422*p: 422

&p: 12000&p: 12000

422 8000

p

120008000

Page 197: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Pointer VariablesPointer Variables

► itself an addressitself an address similar to an integersimilar to an integer allocate enough memory to hold an allocate enough memory to hold an

addressaddress

►how will its content be interpreted?how will its content be interpreted?►pointer variable definition:pointer variable definition:

type *name;type *name;

Page 198: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Pointer ExamplesPointer Examples

int *p = NULL;int *p = NULL;

int x = 422;int x = 422;► assume that assume that

address of x is 8000address of x is 8000

p = &x;p = &x;

*p = 555;*p = 555;

NULL

p x

422

8000

p x

422

8000

p x

555

Page 199: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Statistics: Statistics

► same statistical same statistical calculations as in calculations as in static arrays, this static arrays, this time using dynamic time using dynamic arraysarrays

► all all variablesvariables the the same except:same except: scorescore: a pointer to : a pointer to

an integeran integer

int main(void){ int *score = NULL; int no_students; float mean, variance, std_dev, abs_dev; float total = 0.0, sqr_total = 0.0, abs_total = 0.0; int i;

// calculate and report return EXIT_SUCCESS;}

Page 200: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory AllocationMemory Allocation

► memory MUST be memory MUST be allocated before usedallocated before used

new type[number]new type[number]score = new score = new

int[no_students];int[no_students]; CAN contain variablesCAN contain variables allocates contigous allocates contigous

memory areamemory area gives starting address gives starting address

of raw areaof raw area

NULL

score no_students

53

53 * sizeof(int)

6500

Page 201: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory ManagementMemory Management

► to release allocated memory:to release allocated memory:delete name;delete name; size not specifiedsize not specifieddelete score;delete score;

► no no newnew and and deletedelete in C: in C: allocation: allocation: malloc(requested size in bytes)malloc(requested size in bytes)

► return address should be cast:return address should be cast:score = (int *) malloc(no_students * sizeof(int));score = (int *) malloc(no_students * sizeof(int));

release: release: freefreefree(score);free(score);

need the need the stdlib.hstdlib.h header file header file

Page 202: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Dynamic ArraysDynamic Arrays

► dynamic arrays are dynamic arrays are accessed the same way accessed the same way as static arraysas static arrays

► name of array is a name of array is a pointer to its first pointer to its first variable:variable: score[0] is the same as score[0] is the same as

*score*score

► pointer arithmetic:pointer arithmetic: score[1] is the same as score[1] is the same as

*(score + 1)*(score + 1) score[n] is the same as score[n] is the same as

*(score + n)*(score + n)

...int *score = NULL;

cout << ...;cin >> no_students;score = new int[no_students];for (i = 0; i < no_students; i++) { cout << ...; cin >> score[i]; total = total + score[i];}...delete score;...

Page 203: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Pointer ParametersPointer Parameters

►when passing arrays as input parameters when passing arrays as input parameters to functions, always a pointer is passedto functions, always a pointer is passed

►the following are identical:the following are identical:void factorize(int number, factor_t factors[], int &n)void factorize(int number, factor_t factors[], int &n)

void factorize(int number, factor_t *factors, int &n)void factorize(int number, factor_t *factors, int &n)

►unlike arrays, pointers can be returned:unlike arrays, pointers can be returned:char *char *

Page 204: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutlineOutline: Morse Encoding: Morse Encoding

► mainmain function: function: gets a word from the gets a word from the

useruser calls calls encodeencode to get the to get the

encoded stringencoded string prints and exitsprints and exits

► encodeencode function: function: takes a string as input takes a string as input

parametesparametes creates a new (encoded) creates a new (encoded)

stringstring returns the newly returns the newly

created stringcreated string original string is not original string is not

changed: changed: constconst

...char *encode(const char *s);

int main(void){ char word[MAXLENGTH]; char *morse = NULL;

cout << ...; cin >> word; morse = encode(word); cout << morse ..; delete morse; return EXIT_SUCCESS;}

Page 205: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Memory ManagementMemory Management

► encodeencode function function allocates the space allocates the space for the new stringfor the new string

► can not release itcan not release it► mainmain releases it releases it

char *encode(const char *s){ static char encoding...; char *morse = NULL; int i;

morse = new char[MAXLENGTH];

morse[0] = ‘\0’; for (i = 0; s[i] != ‘\0’; i++) { strcat(morse, encoding[s[i] – ‘a’]); strcat(morse, “ “); } return morse;}

Page 206: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Static Local VariablesStatic Local Variables

► the the encodingencoding array in array in the the encodeencode function function does not need to be does not need to be created and destroyed created and destroyed at each callat each call

► no need to make it no need to make it global: global: mainmain will not use will not use itit

► make it static:make it static: lives throughout the lives throughout the

whole programwhole program but only accessible locallybut only accessible locally

char *encode(const char *s){ static char encoding[][5] = { “.-”, “-...”, ...};

...}

Page 207: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Call by AddressCall by Address

►no references in Cno references in C►to change the value of the variable to change the value of the variable

passed as input parameter in the called passed as input parameter in the called function:function: caller sends the address of the variable using caller sends the address of the variable using

&& callee takes input parameter as pointercallee takes input parameter as pointer callee changes content of pointercallee changes content of pointer

►call by value, where values are addressescall by value, where values are addresses

Page 208: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Call by AddressCall by Addressvoid swap(int *x, int *y){ int tmp;

tmp = *x; *x = *y; *y = tmp;}

int main(void){ int m, n; ... swap(&m, &n); ...}

Page 209: Sunum

Input Input // Output Output

Page 210: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

OutputOutput

►no no coutcout in C, use in C, use printfprintf instead: instead:cout cout << << “Hello, world!”“Hello, world!” << endl; << endl;

printf(“Hello, world!printf(“Hello, world!\n\n”);”); \n\n instead of instead of endlendl

►printfprintf syntax: syntax: printf(format printf(format stringstring, expression list);, expression list); format string controls the outputformat string controls the output print strings andprint strings and//or values of expressionsor values of expressions

Page 211: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Format StringFormat String

►strings are transferred directly to outputstrings are transferred directly to output►% followed by a symbol is a format % followed by a symbol is a format

specifierspecifier %d%d: decimal, : decimal, %x%x: hexadecimal, : hexadecimal, %f%f: float: float %c%c: character, : character, %s%s: string: string

► \ followed by a symbol is a special symbol\ followed by a symbol is a special symbol \n\n: newline: newline \t\t: tab: tab \\\\: backslash: backslash

Page 212: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Format SpecifiersFormat Specifiers

► there must be one specifier for each to be there must be one specifier for each to be printedprinted

► the expression will be printed at the location the expression will be printed at the location its specifier is written in the format stringits specifier is written in the format string

► the specifier controls how the expression will the specifier controls how the expression will be printedbe printedcout cout << << “The area of a circle with radius “ “The area of a circle with radius “ <<<< radius radius

<<<< ” is “ ” is “ << << 3.14 * radius * radius3.14 * radius * radius << endl; << endl;

printf(“The area of a circle with radius %d is %fprintf(“The area of a circle with radius %d is %f\n\n”, ”, radius, 3.14 * radius * radius);radius, 3.14 * radius * radius);

Page 213: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

InputInput

►no no cincin in C, use in C, use scanfscanf instead instead►syntax very similar to printfsyntax very similar to printf

cin cin >>>> radius; radius;

scanf(“%d”, &radius);scanf(“%d”, &radius);

►call by addresscall by address►when reading a string:when reading a string:

cin cin >> word;>> word;

scanf(“%s”, word);scanf(“%s”, word);

Page 214: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: Statistics Once AgainOutline: Statistics Once Again

► get the exam scores get the exam scores from a filefrom a file

► write the results to a write the results to a filefile

► get the file names get the file names from the command from the command lineline not interacting with not interacting with

the userthe user

stat3 scores.txt stat3 scores.txt results.txtresults.txt

…#include <stdio.h>…int main(int argc, char *argv[]){ // variable definitions

// check usage // get scores from input file and // compute total // compute statistics // write results to output file

return EXIT_SUCCESS;}

Page 215: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Command Line ParametersCommand Line Parameters

► passing parameters to passing parameters to the the mainmain function function argcargc: number of : number of

argumentsarguments argvargv: array of arguments : array of arguments

where each argument is where each argument is a stringa string

argv[0]argv[0] is the name of is the name of the program itself: the program itself: stat3stat3

argv[1]argv[1] is the first is the first parameter: parameter: scores.txtscores.txt

argv[2]argv[2] is the second is the second parameter: parameter: results.txtresults.txt

int main(int argc, char *argv[]){ ...

if (argc != 3) { printf(“Usage: %s input_file output_file\n”,

argv[0]); exit(EXIT_FAILURE); } ...}

Page 216: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

FilesFiles

► file variables are of file variables are of type type FILE *FILE * determines where to determines where to

read and write in the read and write in the filefile

► stages of file stages of file processing:processing: openopen read, write, ...read, write, ... closeclose

int main(int argc, char *argv[]){ ... FILE *infile, *outfile;

// open the input file // read from the input file // close the input file

// open the output file // write results to the output

file // close the output file}

Page 217: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Opening FilesOpening Files

► to open a file: to open a file: fopenfopenfopen(path, mode)fopen(path, mode)

► pathpath: name of file on : name of file on diskdisk

► modemode:: ““r”r”: read-only: read-only ““w”w”: write-only: write-only ““r+” “w+”r+” “w+”: read and : read and

writewrite ““w”w” and and “w+”“w+” create the create the

file if it does not exist, file if it does not exist, truncate it if it does existtruncate it if it does exist

► to close a file: to close a file: fclosefclose

int main(int argc, char *argv[]){ ... FILE *infile, *outfile;

infile = fopen(argv[1], “r”); // read from the input file fclose(infile);

outfile = fopen(argv[2], “w”); // write results to the output file fclose(outfile); ...}

Page 218: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Reading from FilesReading from Files

► file pointer is placed at file pointer is placed at the beginning of file on the beginning of file on openopen each read each read // write write

advances the pointeradvances the pointer

► to read: to read: fscanffscanf same as same as scanfscanf, just reads , just reads

from filefrom file moves pointer to next moves pointer to next

line: repeated readsline: repeated reads

► to check end-of-file: to check end-of-file: feoffeof

int main(int argc, char *argv[]){ ... no_students = 0; while (1) { fscanf(infile, “%d”, &score[no_students]); if (feof(infile)) break; total = total + score[no_students] no_students++; } ...}

Page 219: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Writing to FilesWriting to Files

► to write: to write: fprintffprintf same as same as printfprintf, just , just

writes to filewrites to file moves pointer to moves pointer to

next line: repeated next line: repeated writeswrites

int main(int argc, char *argv[]){ ... fprintf(outfile, “Number of students: %d\n”, no_students); fprintf(outfile, “Mean: %f\n”, mean); fprintf(outfile, “Variance: %f\n”, variance); fprintf(outfile, “Standard deviation: %f\n”, std_dev); ...}

Page 220: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Standard IStandard I//O StreamsO Streams

►standard input: standard input: stdinstdin scanfscanf is the same as is the same as fscanf(stdin,...)fscanf(stdin,...)

►standard output: standard output: stdoutstdout printfprintf is the same as is the same as fprintf(stdout,...)fprintf(stdout,...)

►standard error: standard error: stderrstderr

Page 221: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Error MessagesError Messages

► it is better practice to it is better practice to send error messages send error messages to the error stream:to the error stream:cerr cerr << << message;message;

fprintf(stderr, message)fprintf(stderr, message)

► if error is critical, if error is critical, exitexit► perrorperror displays displays

standard error standard error messagesmessages

int main(int argc, char *argv[]){ ... infile = fopen(argv[1], “r”); if (infile == NULL) { fprintf(stderr, “Input file could not be opened.\n”); exit(EXIT_FAILURE); } ...}

Page 222: Sunum

PreprocessorPreprocessor

Page 223: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PreprocessingPreprocessing

►source code goes through a source code goes through a preprocessing stage before compilingpreprocessing stage before compiling

source code object code

libraries

executableintermediate

source code

PREPROCESSOR COMPILER LINKER

Page 224: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

PreprocessorPreprocessor

►removes the commentsremoves the comments►processes the preprocessor directives:processes the preprocessor directives:

#define#define: define constants or macros: define constants or macros

#define PI 3.14#define PI 3.14 #include#include: place the file at this point in the : place the file at this point in the

sourcesource

#include <stdlib.h>#include <stdlib.h>

Page 225: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

MacrosMacros

►repeated code segments not worth repeated code segments not worth making a functionmaking a function

sqr_total = sqr_total +sqr_total = sqr_total +

(score[i] – mean) * (score[i] – mean);(score[i] – mean) * (score[i] – mean);

writing a function to compute square is writing a function to compute square is overkilloverkill#define sqr(x) (x) * (x)#define sqr(x) (x) * (x)

replace each occurrence of the macro by replace each occurrence of the macro by its expanded equivalentits expanded equivalentsqr_total = sqr_total + sqr(score[i] - mean)sqr_total = sqr_total + sqr(score[i] - mean)

Page 226: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Expanding MacrosExpanding Macros

►macros are just dumb substitutions!macros are just dumb substitutions!#define sqr(x) x * x#define sqr(x) x * x

sqr_total = sqr_total + sqr(score[i] - mean);sqr_total = sqr_total + sqr(score[i] - mean); would be:would be:

sqr_total = sqr_total +sqr_total = sqr_total +

score[i] – mean * score[i] – mean;score[i] – mean * score[i] – mean;

Page 227: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

ProjectsProjects

►source file gets too big:source file gets too big: hard to managehard to manage takes longer to compile and linktakes longer to compile and link

►split into multiple source filessplit into multiple source files easier to manageeasier to manage compiling takes less timecompiling takes less time

►group relevant functions in the same filegroup relevant functions in the same file computations / user interfacecomputations / user interface

Page 228: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Building ProjectsBuilding Projects

►first compile separately then linkfirst compile separately then link

source code n object code n

libraries

executable

source code 1 object code 1

source code 2 object code 2

Page 229: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: Multiple SourcesOutline: Multiple Sources

►program finds:program finds: factors of a numberfactors of a number gcd of two numbersgcd of two numbers lcm of two numberslcm of two numbers

►functions splitted into two source files:functions splitted into two source files: user interaction in file user interaction in file project.cppproject.cpp computations in computations in ops.cppops.cpp

Page 230: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: project.cppOutline: project.cpp

► factorizefactorize, , gcdgcd and and lcmlcm functions are functions are called in called in project.cppproject.cpp

► but they are defined but they are defined in in ops.cppops.cpp

► compiler needs the compiler needs the declarationsdeclarations

► also needs the also needs the structstruct definition for definition for a factora factor

int main(void){ // variables

while (true) { // draw menu and get choice switch (choice) { ... case 3: ... factorize() ... ... factors[i].base ... case 4: ... gcd() ... case 5: ... lcm() ... ... } }}

Page 231: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

DeclarationsDeclarations

► what if there is what if there is another source file another source file that also calls these that also calls these functions?functions?

► the the structstruct definition definition for factor is needed for factor is needed both in both in project.cppproject.cpp and and ops.cppops.cpp write twice?write twice?

...void factorize(...);void gcd(...);void lcm(...);...int main(void){ ...}

Page 232: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Header FileHeader File

► put shared put shared declarations in a declarations in a header file: header file: ops.hops.h

► include the header include the header file in each source file in each source file that needs the file that needs the declarationsdeclarationsinclude “ops.h”include “ops.h” “”“” instead of instead of <><>

#define MAXFACTOR 50

struct factor_s { int base, power;};typedef struct factor_s factor_t;

void factorize(int x, factor_t factors[],

int &n);int gcd(int number1, int number2);int lcm(int number1, int number2);

Page 233: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Outline: ops.cppOutline: ops.cpp

► declarations of declarations of is_primeis_prime, , next_primenext_prime, , gcd_factorsgcd_factors and and lcm_factorslcm_factors are not are not in in ops.hops.h

► they are not they are not accessible from accessible from other source filesother source files

► header file is the header file is the interface of the interface of the source filesource file

...#include “ops.h”...void gcd_factors(...);void lcm_factors(...);

int gcd() ...int lcm() ...bool is_prime() ...int next_prime() ...void factorize() ...void gcd_factors() ...void lcm_factors() ...

Page 234: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Header FilesHeader Files

► what to put in what to put in header files?header files? function declarationsfunction declarations type definitionstype definitions global variables: global variables:

externextern constant and macro constant and macro

definitionsdefinitions including other filesincluding other files

► what what NOTNOT to put in to put in header files?header files? variable definitionsvariable definitions function definitions function definitions

(bodies)(bodies)

Page 235: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Multiple InclusionMultiple Inclusion

► to prevent an include to prevent an include file from being included file from being included more than once: more than once: #ifndef#ifndef

► on first inclusion:on first inclusion: OPS_HOPS_H is not defined is not defined OPS_HOPS_H gets defined gets defined

(value not important)(value not important) make other declarationsmake other declarations

► on second inclusion:on second inclusion: OPS_HOPS_H is defined, skip is defined, skip

the restthe rest

#ifndef OPS_H#define OPS_H

#define MAXFACTOR 50...int gcd(int number1, int number2);int lcm(int number1, int number2);

#endif

Page 236: Sunum

RecursionRecursion

Page 237: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

RecursionRecursion

►the problem is expressed in terms of the problem is expressed in terms of itself:itself: the gcd of a and b is equal to the gcd of b and the gcd of a and b is equal to the gcd of b and

a % ba % b the factorial of x is x times the factorial of x – the factorial of x is x times the factorial of x –

11

► for this approach to work:for this approach to work: the subproblem must be of smaller sizethe subproblem must be of smaller size there has to be a base case where the there has to be a base case where the

solution is knownsolution is known

Page 238: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Recursive FactorialRecursive Factorial

► x – 1 is smaller than x – 1 is smaller than xx gets smaller at each gets smaller at each

stepstep

► the factorial of 0 is the factorial of 0 is 11

► using iteration is using iteration is faster and cheaperfaster and cheaper

int factorial(int x){ if (x == 0) return 1; else return x * factor(x - 1);}

Page 239: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Recursive GCDRecursive GCD

► b is smaller than ab is smaller than a► a % b is smaller a % b is smaller

than bthan b► if b is 0 the gcd is aif b is 0 the gcd is a► using iteration is using iteration is

faster and cheaperfaster and cheaper

int gcd(int a, int b){ if (b == 0) return a; else return gcd(b, a % b);}

Page 240: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Towers of HanoiTowers of Hanoi

► 3 golden needles, 3 golden needles, 64 marble discs64 marble discs

► each disk is on a each disk is on a larger disklarger disk

► move all disks one move all disks one by one from needle by one from needle 1 to needle 31 to needle 3

► never put a disk on never put a disk on a smaller diska smaller disk

Page 241: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Towers of HanoiTowers of Hanoi

► consider the largest disk:consider the largest disk: all of the other disks must all of the other disks must

be on needle 2 and needle be on needle 2 and needle 3 must be empty3 must be empty

► move 64 disks from 1 to move 64 disks from 1 to 3:3: move 63 disks from 1 to 2move 63 disks from 1 to 2 move a disk from 1 to 3move a disk from 1 to 3 move 63 disks from 2 to 3move 63 disks from 2 to 3

► same problem with 63 same problem with 63 disks instead of 64disks instead of 64

Page 242: Sunum

Bu sunumlar sınavlara hazırlık amaçlı değildir.© 2002-2004 H. Turgut Uyar

Towers of HanoiTowers of Hanoi

► move n disks from a to move n disks from a to b using c:b using c: move n – 1 disks from a move n – 1 disks from a

to c using bto c using b move a disk from a to bmove a disk from a to b move n – 1 disks from c move n – 1 disks from c

to b using ato b using a

► base case: base case: n = 0n = 0► very elegant solution: very elegant solution:

no unnecessary move!no unnecessary move!

void move(int n, int a, int b, int c){ if (n 0) { move(n – 1, a, c, b); cout << “Move a disk from “ << a << “ to “ << b << endl; move(n – 1, c, b, a); }}

main: move(64, 1, 3, 2);