Sei sulla pagina 1di 37

IntroductiontoBasicProceduralProgramming(with

C++)

Trytosimulate compilation and execution inyourhead


Trydifferentvariationsonatheme- simplyeditth

C++Basics

eexamples

Easiestwaytolearnprogrammingistoexperiment
Thecomputerisalaboratory
Ifyoudontknowsomethingthenwriteaprogramto
ifyoucan

giveyouthe answer

Otherwise,trylookinginabook(orontheweb)
Youcanalwaysasksomeone(doesnthavetobeme)

RosemaryMonahan
CS613OO&C++
September2002

September2002

CS613:OO&C+:BasicC++

Example1Variations- whatwillhappenineachcase?
// Example 1
/* Rosemary Monahan
CS613 C++ Code
*/
main ()// does nothing!!
{}

/* Example 1A
CS613 C++ Code
*/

/* Example 1B
CS613 C++ Code
*/

int main ()// does nothing!!


{return 0;}

int main ()
{}

/* Example 1C
CS613 C++ Code
*/

// Example 1D
int main () {return 7}

Onelinecomment
Multiplelinecomment
Endoflinecomment
mainprogram

> gxx -oExample1.exeExample1.cc


>Example1

Compilation
Execution
Input/Output

>

// Example 1E
int main (){return 0.7;;}

main ()// does nothing!!


{return 0;}

MSDOSCommandLineWindow

// Example 1F
float main (){return 0.7;}
September2002

CS613:OO&C+:BasicC++

September2002

CS613:OO&C+:BasicC++

ExampleVariations- somenotes

Trytolearnsomethingnewfromeachvariation- see
Trynottochangemorethanonethingatonce- see
Trytointroducedifferentcompilererrors- syntax

Example2:outputtothescreen
// Example 2

1B

#include <iostream.h>
int main (){cout<<"Hello World!";}

1C
andsemantics- see1D

Writes(outputs)HelloWorld!
Tothescreen

Trytodistinguisherrorsfromwarnings- see1E
Trytorememberthatthecompilercanbesneaky- se

e1F

Question - whatsortofvariationsmightbeuseful?
removethe include
changetheoutput Hello World!
addina return
September2002

CS613:OO&C+:BasicC++

September2002

CS613:OO&C+:BasicC++

Variation2A:removetheinclude

Variation2B:changetheoutput

// Example 2

// Example 2B

//#include <iostream.h>
int main (){cout<<"Hello World!";}

#include <iostream.h>
int main (){
cout<<"Hello Universe, ";
cout <<"how are"<<" you"<<"?";}

Writes(outputs)Example2A.cc:Infunction`int main()':
Example2A.cc:4:`cout' undeclared(firstusethisfu nction)
Example2A.cc:4:(Eachundeclaredidentifierisrepo rtedonlyonce
Example2A.cc:4:foreachfunctionitappearsin.)

Program
contains2
instructions

Youcan
stream strings
together

Writes(outputs)HelloUniverse,howareyou?
Note:thisisnot

anerroritistheresultofthecodebeingexecute

Tothescreen
Note:thisisasemantic
September2002

errorreportedbythecompiler
CS613:OO&C+:BasicC++

September2002

CS613:OO&C+:BasicC++

Variation2C:changetheoutput

Variation2D:changetheoutput
String,in
doublequotes,
containsspecial
character \n

//Example2C
#include<iostream.h>
int main(){
cout<<"HelloUniverse, \n";
cout <<"howare"<< endl<<"you"<< '?';}
Writes(outputs)HelloUniverse,
howare
you?

A ? characterbetween
singlequotes
Notetheuseof
endl - astream
manipulator
object!

Note:theformat - spacesandnewlines

September2002

#include <iostream.h>
int main (){
cout<<"7 + 8 = \n";
cout <<7+8;}

Writes(outputs)7+8=
15

An integer
expression which
needstobe
evaluated

Note:theadditioniscorrect(inbase10)

CS613:OO&C+:BasicC++

September2002

CS613:OO&C+:BasicC++

10

Example3- introducingvariables

Variation2E:addinareturn
Returnatthe
beginningof
themainbody

// Example 2E

String,in
doublequotes,
containsspecial
character \n

// Example 2D

// Example 3
#include <iostream.h>
int main (){
int x = 7+8; cout <<x;
}

#include <iostream.h>
int main (){return 0;
cout<<"7 + 8 = \n";
cout <<7+8;}

Thevariable x isidentifiedbythe
sequenceofcharactersx.
Ithastype int (aninteger)

x is declared tobean int and initialised tovalue15


inthesamestatement.

Writes(outputs)absolutelynothingtothescreen
ThisoutputsNote: ifweputthereturninasthelastlinethenwege
behaviourasbefore

tthesame
15
QUESTION: whatvariationstotry?

September2002

CS613:OO&C+:BasicC++

11

September2002

CS613:OO&C+:BasicC++

12

Variation3A:Whatifthevariableisnotinitialis

ed?

Variation3C:Whatifthevariableisinitialisedt

// Example 3A

// Example 3C

#include <iostream.h>
int main (){
int x; cout <<x;
}

#include <iostream.h>
int main (){
int x; int x; cout <<x;
}

Output:
686796

Variation3A:Whatifthevariableischanged?

Output:
Example3C.cc:Infunction`int main()':
Example3C.cc:5: redeclaration of`int x'
Example3C.cc:5:`int x'previouslydeclaredhere

Variation3D:Whatifthevariableischanged?

// Example 3B

// Example 3D

#include <iostream.h>
int main (){
int x; cout <<x; x = 0;
cout <<x;
}

#include <iostream.h>
int main (){
int x = 1;
x = x+x;cout<<x*x;
}

September2002

CS613:OO&C+:BasicC++

wice?

Output:
6867960
13

September2002

Wecanchangethevalueof

x using x

Thisdoesnotchangethevalueof

Output:
4

CS613:OO&C+:BasicC++

14

AlreadysomesimplerulestolearnIdentifiers

variables
identifiers

Anidentifiermuststartwithaletterorundersco
zeroormoreletters
C++iscasesensitive

re,andbefollowedby

types

values
constants

VALID
age_of_dog
PrintHeading

TaxRate98
AgeOfHorse

keywords

September2002

CS613:OO&C+:BasicC++

15

INVALIDexamples- trytofindthemyourselvesusin

September2002

CS613:OO&C+:BasicC++

gthecompiler

16

Typicalsizeofdatatypes

C++ Data Types

Simple
Structured
Integral

Floating
array struct union class

char short int long enum


float double longdouble

Address

Type
NumberofBytes
char
1
short (short int)
2
int
4
unsigned int
4
enum
2
long (long int)
4
float
4
double
8
long double
12

pointer reference
September2002

CS613:OO&C+:BasicC++

17

September2002

Findingsizeofdatatype- systemdependentresults

CS613:OO&C+:BasicC++

18

Enumeratedtypes: enum
Usedtodefineconstantvalues

Use

sizeof

tofindthesizeofatype

enum days
{ Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday
} yesterday, today;
days tomorrow;

e.g.
cout << sizeof(int)

QUESTION:whatarethevaluesof
tomorrow, yesterday?

Tuesday, today,

Defaultvaluesmaybeoverriddenintheenum list.
September2002

CS613:OO&C+:BasicC++

19

September2002

CS613:OO&C+:BasicC++

20

Enumeratedtypes

Booleantype
C++hasabuilt-inlogicalorBooleantype

// Example 4
#include <iostream.h>

// Example 5

int main (){


enum days {Sunday, Monday, Tuesday,Wednesday,
Thursday, Friday, Saturday} yesterday, today;
days tomorrow;
cout << Tuesday<<endl;
cout<< yesterday<<endl<<today<<endl<<tomorrow;
}

Outputs:

2
686796
143896
117208

September2002

#include <iostream.h>
int main (){
bool flag = true;
cout << flag<< endl<<!flag}

Thisoutputs:
1
0
CS613:OO&C+:BasicC++

21

September2002

CS613:OO&C+:BasicC++

22

Givingavaluetoavariable

Variation5a- booleansarereallyintegers?

true isanynonzero int

// Example 5a
#include <iostream.h>

false iszero

int main (){


bool flag1 = 100, flag2 = false, flag3;
cout << flag1<< endl<<flag2<<endl<<flag3;}

In your program you can assign (give) a value to the variable by using
the assignment operator =
Age_Of_Dog = 12;

or by another standard method, such as


cout << How old is your dog?;
cin >> Age_Of_Dog;

true isoutputas1
false isoutputas0

Thisoutputs:
1
0

Thiswasnotinitialised

122
September2002

CS613:OO&C+:BasicC++

23

September2002

CS613:OO&C+:BasicC++

24

keywords:wordsreservedtoC++

WhatisaNamedConstant?

A namedconstant isalocationinmemory whichwecanrefertobyan


identifier,andinwhicha datavaluethatcannotbechanged isstored.

VALIDCONSTANTDECLARATIONS
const
char
STAR = * ;
const
float
PI = 3.14159 ;
const
int
MAX_SIZE = 50 ;

bool, true, false,


char, float, int, unsigned, double, long
if, else, for, while, switch, case, break,
class, public, private, protected, new,
delete, template, this, virtual,

try, catch, throw.

Note:therearemanymoreyoumayseethemintheexam

September2002

CS613:OO&C+:BasicC++

25

September2002

plesthatfollow

CS613:OO&C+:BasicC++

26

Example7:aC+ternaryoperator

Example6:prefixandpostfix

// Example 7
Output:
// Example 6

#include <iostream.h>
++ (prefix)isa unary operator

#include <iostream.h>
int main (){
int x =3, y=3;
cout <<++x<<endl;
cout <<y++<<endl;}

Output:
3
4

<< isa binary operator

int main (){


int x =3, y=4;
cout <<"The max. of x and y is: "
<< (x>y?x:y);
}

Themax.ofxandyis:4

++ (postfix)isa unary operator


expression1?expression2:expression3
Means: ifexpression1thenexpression2elseexpression3

September2002

CS613:OO&C+:BasicC++

27

September2002

CS613:OO&C+:BasicC++

28

ProgramwithThreeFunctions

PrecedenceofSomeC++Operators

// Example 8
#include <iostream.h>
// declares these 2 functions
int Square ( int );
int Cube ( int ) ;
int main ( void ){
cout << "The square of 27 is "
<<
Square (27) << endl ;// function call
cout << "The cube of 27 is "
<< Cube (27) << endl ;// function call
return 0 ;
}
int Square ( int n ){return
n * n ;}
int Cube ( int n ){return n * n * n ;}
Output:
September2002

Precedence
Higher

Lower

Operator
()
+
*
/
%
+
=

NOTE:Writesomeprogramstotestyourunderstandin

Thesquareof27is729
Thecubeof27is19683
CS613:OO&C+:BasicC++

29

September2002

// Example 9
#include <iostream.h>

September2002

CS613:OO&C+:BasicC++

CS613:OO&C+:BasicC++

30

Everyfunctionhas2parts

int main ( void ){


cout << "int(4.8) ="<<int(4.8)<<endl;
cout << "float(5) ="<<float(5)<<endl;
cout <<float(2/4)="<<float(2/4)<<endl;
cout<<"float(2)/float(4)="<<float(2)/float(4)<<endl;
}
int(4.8)=4
float(5)=5
float(2/4)=0
float(2)/float(4)=0.5

gofprecedence

PartsofaFunction

TypeCastingisExplicitConversionofType

Output:

Description
Functioncall
Positive
Negative
Multiplication
Division
Modulus(remainder)
Addition
Subtraction
Assignment

signature
int main (void)
{
return 0;

body

Outputof float
maylooklikean int

31

September2002

CS613:OO&C+:BasicC++

32

C++I/OBasics
HEADERFILE FUNCTION EXAMPLE

<stdlib.h>

VALUE
OFCALL

abs(i)

abs(-6)

fabs(x)

fabs(-6.4)

pow(x,y)

pow(2.0,3.0)

I/O- Input/Outputisoneofthefirstaspectsofpr
mastered:

ogrammingthatneedstobe

formatting

<math.h>

6.4

whitespace

8.0

structuredinputs- gettingdataintothecorrecti

nternalform

However,donotfallintothebeginnerstraps:
sqrt(x)

sqrt(100.0)
sqrt(2.0)

10.0

brilliantI/Owithincorrectfunctionality

1.41421

thinkingfunctionalityiswrongbecauseI/Oistoo
forgettingthatrandomtestsareoftenbetterthan

log(x)
<iomanip.h>
September2002

log(2.0)

complicatedtogetright
userdependentI/O

0.693147

setprecision(n) setprecision(3)
CS613:OO&C+:BasicC++

33

34

Explicitprecisionmanipulation

scientificnotation

// Example 10
#include <iomanip.h>
#include <iostream.h>
int main ( void){
float
myNumber = 123.4587 ;
cout.setf ( ios::fixed , ios::floatfield );// decimal format
cout.setf ( ios::showpoint ) ; // print decimal point

#include<iostream.h>
#include<iomanip.h>
main(){
floatz=123456789.12335;
cout <<z<< endl;
}

cout
return
}

<<

CS613:OO&C+:BasicC++

35

<< setprecision ( 3 )
<< endl ;

0 ;

Output:

September2002

"Number is "
<< myNumber

September2002

Numberis123.459

CS613:OO&C+:BasicC++

36

setw example

setw(n)
requires#include<iomanip.h>andappearsinanexp
operator(<<)

ressionusinginsertion

affectsonlytheverynextitemdisplayed
setwidthspecifiesnasthenumberoftotalcolu
Thenumberofcolumnsusedisexpandedifnistoo

//Example
#include
#include
int main
{
float
float

11
<iomanip.h>
<iostream.h>
( void)
myNumber
yourNumber

narrow.

Output:

CS613:OO&C+:BasicC++

37

September2002

Whitespace CharactersInclude...

123.4 ;
3.14159;

cout.setf ( ios::fixed , ios::floatfield ) ;


cout.setf ( ios::showpoint ) ;
cout << "Numbers are: " << setprecision (4) << endl
<<
setw ( 10 )
<< myNumber
<<
endl
<<
setw ( 10 )
<< yourNumber
<<
endl ;
return 0 ;

mnstodisplayanumber.

Usefultoaligncolumnsofoutput

September2002

=
=

Numbersare:
123.4000
3.1416
CS613:OO&C+:BasicC++

38

ExtractionOperator>>

blanks
tabs
end-of-line(newline)characters

skipsover
(actuallyreadsbutdoesnotstoreanywhere)
leadingwhitespacecharacters

The newline characteriscreatedby


hittingEnterorReturnatthekeyboard,
orbyusingthemanipulator endl or\n
inaprogram.

September2002

CS613:OO&C+:BasicC++

39

September2002

CS613:OO&C+:BasicC++

40

10

At keyboard you type:


A[space]B[space]C[Enter]

Anotherwaytoreadchardata

char first;
char middle;
char last;

The get() functioncanbeusedtoreadasingle


character.

cin.get(first);
cin.get(middle);
cin.get(last);

Itobtainstheverynextcharacterfromtheinput
streamwithoutskippinganyleadingwhitespace
characters.

first

middle

first

middle

NOTE: Thefilereadingmarkerisleftpointingto
spaceaftertheBintheinputstream.
September2002

CS613:OO&C+:BasicC++

41

September2002

CS613:OO&C+:BasicC++

last

B
last

the

42

C++ControlFlowBasics
C++controlstructures
Selection

Howtotakedecisions

if
if . . . else
switch

Useful boolean operations


Looping- fixed/non-fixednumberoftimes
Breaking
Repetition

Switching

for loop
while loop
do . . . while loop

FunctionCallsandRecursion

September2002

CS613:OO&C+:BasicC++

43

September2002

CS613:OO&C+:BasicC++

44

11

Operator

CONTROLSTRUCTURES

!
*,/,%
+,<
<=
>
>=
==
!=
&&
||
=

Uselogicalexpressionswhichmayinclude:
6RelationalOperators

<

<=>>= ==!=

3LogicalOperators

!
September2002

&&

||

CS613:OO&C+:BasicC++

45

Meaning
NOT
Multiplication,Division,Modulus
Addition,Subtraction
Lessthan
Lessthanorequalto
Greaterthan
Greaterthanorequalto
Isequalto
Isnotequalto
AND
OR
Assignment

September2002

SHORT-CIRCUITEVALUATION

CS613:OO&C+:BasicC++

Associativity
Right
Left
Left
Left
Left
Left
Left
Left
Left
Left
Left
Right
46

Short-CircuitExample
int Age,Height;

C++usesshortcircuitevaluationoflogical
expressions

Age=25;
Height=70;
EXPRESSION

thismeansthatevaluationstopsassoonasthefinal
truthvaluecanbedetermined

(Age>50)&&(Height>60)
false
Evaluationcanstopnow

September2002

CS613:OO&C+:BasicC++

47

September2002

CS613:OO&C+:BasicC++

48

12

Betterexample

Compoundstatement
Weusebraces{}tobuildcompoundstatements
Tousebracesornottousebraces??

intNumber;
floatX;

(Number ! = 0) &&(X

September2002

< 1 / Number)

CS613:OO&C+:BasicC++

49

September2002

CS613:OO&C+:BasicC++

50

Bewareof danglingelse
Conditionalstatements
Syntax

endofoutput

if (expression)
statement1
else
statement2

September2002

CS613:OO&C+:BasicC++

//Example 12
#include <iostream.h>
int main ( void) {
int x = 7, y = 8;
if (x == 0)
if (y == 0) cout << "yes"<< endl;
else
cout << "no"<< endl;
cout << "end of output" << endl;
}

51

September2002

CS613:OO&C+:BasicC++

52

13

Iterationstatements

Iterationstatements

// compute sum = 1 + 2 + ... + n


// using a while loop

while-statementsyntax
while (expression)
statement

int sum = 0;
i = 1;
while (i <= n) {
sum += i;
i++;
}

semantics

September2002

CS613:OO&C+:BasicC++

53

September2002

CS613:OO&C+:BasicC++

54

Iterationstatements

Break
// compute sum = 1 + 2 + ... + n
// using for loop

break;

theexecutionofalooporswitchterminates
immediatelyif,initsinnerpart,the
break;
statementisexecuted.

int sum = 0;
for (int i = 1; i <= n; ++i) {
sum += i;
}

September2002

CS613:OO&C+:BasicC++

55

September2002

CS613:OO&C+:BasicC++

56

14

Combining break and for

Switch
switch (letter) {
case N: cout <
break;
case L: cout <
break;
case A: cout <
break;
default: cout <
break;
}

charch;
intcount=0;
for(;;){
cin>>ch;
if(ch==\n)break;
++count;
}
September2002

CS613:OO&C+:BasicC++

57

September2002

Switch

CS613:OO&C+:BasicC++

London\n;
Amsterdam\n;
Somewhere else\n;

CS613:OO&C+:BasicC++

58

Whatstheoutput?

switch (letter) {
case N: case n: cout < New York\n;
break;
case L: case l: cout < London\n;
break;
case A: case a: cout < Amsterdam\n;
break;
default: cout < Somewhere else\n;
break;
}
September2002

New York\n;

59

int i=0;
switch(i){
case0:i+=5;
case1:++i;
case2:++i;
case3:++i;
default++i;
}
cout<<iis:<<i<<endl;
September2002

CS613:OO&C+:BasicC++

60

15

Functions:
3parametertransmissionmodes

Simplearrays

subscriptscanbeanintegerexpression
Inthedeclaration,thedimensionmustbeaconsta

passby value(default)
passby reference(&)
passby constreference(const&)

ntexpression

const int LENGTH = 100;


...
int a[LENGTH]
...
for (int i=0; i<LENGTH; i++)
a[i] = 0; // initialize array

September2002

CS613:OO&C+:BasicC++

61

September2002

Functions:
exampleofpassbyvalue

CS613:OO&C+:BasicC++

62

TheSwapFunction
void swap(int x, int y)
{
// Create a temporary variable
int temp;

int sqr(int x) {

temp = x;
x = y;
}

y = temp;

Theswapdoesnt
happen!
Why?

}
September2002

CS613:OO&C+:BasicC++

63

September2002

CS613:OO&C+:BasicC++

64

16

Passingvaluesbyreference

TheNewSwapFunction
void swap(int& x, int& y)
{
// Create a temporary variable
int temp;

C/C++passesparametersbyvalue,i.e.a
copyofthevariableispassedtothe
function,nottheactualvalueitself.
C++canpasstheactualvariables
themselves- knownas passingparameters
byreference .
Topassaparameterbyreferenceweplace
&betweentheparameterstypenameand
theparametertag.
September2002

CS613:OO&C+:BasicC++

temp = x;
x = y;
y = temp;
}

Whataboutfunctionsandarrays/structures?
65

September2002

Functions:
exampleofpassbyreference

CS613:OO&C+:BasicC++

66

Functions:passby
constreference
Makessensewithlargestructuresorobjects

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

Address

const&
}

September2002

CS613:OO&C+:BasicC++

67

September2002

CS613:OO&C+:BasicC++

68

17

Arraysarepassedbyreference

Pointers

const int MAX = 100;


void init(int a[], int x) {
for (int i = 0, i < MAX; ++i)
a[i] = rand() % 100; // remainder
x = 99;
}

Whataretheyfor?
- Accessingarrayelements
- Passing arguments to a function when the
functionneedstomodifytheoriginalargument.
- Passingarraysandstringstofunctions
- Obtainingmemoryfromthesystem
- Creatingdatastructuresfromlinkedlists

main() {
int a[MAX], x = 7;
init(a, x);
cout << a[0] << \t << x << endl;
}

September2002

CS613:OO&C+:BasicC++

69

September2002

CS613:OO&C+:BasicC++

70

TheAddressOperator&
Pointers

Itispossibletofindouttheaddressoccupiedbya
variablebyusingtheaddressoftheoperator&.

Itis possibletodowithoutpointers:

void main()
{
int var1 = 11;
int var2 = 22;
int var3 = 33;

arrayscanbeaccessedwitharraynotation
ratherthanpointernotation
afunctioncanmodifyargumentspassed,by
reference,aswellasthosepassedbypointers.

However,inordertoobtainthemostfrom
thelanguageitisessentialtousepointers.
September2002

CS613:OO&C+:BasicC++

cout

71

September2002

<< endl << &var1


<< endl << &var2
<< endl << &var3;
CS613:OO&C+:BasicC++

72

18

Addresses

CreatingPointers

Theactualaddressesoccupiedbyvariablesina
programdependonmanyfactors,suchas
thecomputertheprogramisrunningon,
thesizeoftheoperatingsystem,
and whether any other programs are currently in
memory.

Forthesereasonsnotwocomputerswillgivethe
sameanswertotheaboveprogram.
September2002

CS613:OO&C+:BasicC++

73

Noaddresshasbeenplacedin
ptr,soits
valueisundefined.With ptr being
undefined,acomparisoninvolving p would
beanerror,althoughmostC++compilers
wouldnotflagthemistake.
Itispossibletoassignthevalueconstant
NULLtoindicatethat ptr doesnotpointto
amemoryallocation( ptr isnolonger
undefined).
CS613:OO&C+:BasicC++

int

*ptr;

As a result of this declaration, room for an


addressisallocatedto ptr.
September2002

CS613:OO&C+:BasicC++

74

Printingoutvariablesthatholdaddressvaluesare
useful.

TheNULLPointer

September2002

For creation of a pointer variable that can


hold the address of a data type
int, an
asterisk is used to write the type definition
of ptr suchas

75

void main()
{ int
var1 = 11;
int* ptr; //defines a pointer
cout <<endl <<&var1;
ptr = &var1;
cout <<endl <<ptr;
}

The*means pointerto. ptr isapointertoan


int (itcanholdtheaddressofintegervariables).
September2002

CS613:OO&C+:BasicC++

76

19

Definingpointervariables

Puttingvaluesinpointers
Before a pointer is used a specific address
mustbeplacedinit:

definingpointervariables
char* cptr;
int* iptr;
float* fptr;

ptr = &var1;

A pointer can hold the address of any


variableofthecorrecttype;
Warning!

definingmultiplepointervariables

it must be given some value, otherwise it will


point toan arbitraryaddress (becauseit has to
pointtosomething).

char* ptr1, * ptr2, * ptr3;


September2002

CS613:OO&C+:BasicC++

77

Accessingthevariablepointedto

September2002

void main()
{ int var1, var2;
int* ptr;

ptr = &var1;
cout <<endl <<*ptr;

ptr = &var1;
*ptr = 37;
var2 = *ptr;
cout <<endl<< var2;

ptr holdstheaddressofvar1
*ptr holdsthecontentsofvar1
CS613:OO&C+:BasicC++

78

UsingPointerstoModifyVariables

void main()
{int
var1 = 22;
int*
ptr;

September2002

CS613:OO&C+:BasicC++

}
79

September2002

CS613:OO&C+:BasicC++

80

20

Pointers/References

IndirectAddressing

//Pointers and references


//pointersF.cc
#include<iostream>

The*isusedindeclarationisdifferenttothe
*usedinassignment.

int main()
{

CS613:OO&C+:BasicC++

ppn=0xa88b8
*ppn=0xa88bc
**ppn=10

int n = 10;
int *pn = &n;
int** ppn = &pn;

Usingthe*toaccessthevaluestoredinan
addesss iscalled indirectaddressing ,or
sometimesdereferencing thepointer.
September2002

Output

cout<<"ppn="<<ppn<<endl;
cout<<"*ppn="<<*ppn<<endl;
cout<<"**ppn="<< **ppn<<endl;
}
81

September2002

CS613:OO&C+:BasicC++

82

InSummary...
int v;
int* p;

//defines variable v of type int


//defines p as a pointer to int

p = &v; //assigns address of variable v


//to pointer p
v = 3;
//assigns 3 to v
*p = 3; //assigns 3 to v using indirect
addressing,
referring
to the same
variable (v) using its address.
September2002

CS613:OO&C+:BasicC++

83

BeCareful!!!
Note:bydeclaringapointeras
void* ptr;
isdeclaringageneralpurposepointerthatcanpointto
anydatatypeirrespectiveofitstype.Itispossiblet
assigntheaddressofan int,float etc., tothesame
pointervariable,thiseliminatestheneedtodeclarea
separatepointervariableforeachdatatype.
September2002

CS613:OO&C+:BasicC++

84

21

UsingPointerNotation
PointerstoArrays

Accessingthesamearrayusingpointernotation
for (j=0; j < 5; j++)
cout <<endl << *(intarray+j);

void main()
{int j;
int intarray[5]={31,54,77,52,93};

Suppose j is3,theexpressionisequivalentto
*(intarray+3), i.e.accessingthe

fourthelementinthearray(52).

for (j=0; j < 5; j++)


cout <<endl <<intarray[j];
}
September2002

CS613:OO&C+:BasicC++

Rememberthatthenameofanarrayisitsaddress.
The expression intarray+j is thus the address
withsomethingaddedtoit.
85

September2002

CS613:OO&C+:BasicC++

PointerConstants

The void keyword

Theexpression intarray istheaddress


wherethesystemhasdecidedtoplacethe
array,anditwillstayatthisaddressuntil
theprogramterminates. intarray isa
constant.

September2002

CS613:OO&C+:BasicC++

86

InConemightwrite
main()

Thisisequivalentto:
int main()
not void main() andimplies return 0; attheendofthemain
function.

87

September2002

CS613:OO&C+:BasicC++

88

22

Functions:initialization

Functions:
Typesofargumentsandreturnvalues

#include <iostream.h>

Typesofreturnvalues
conversionrulesalsoapplytoreturn-statements

void f() {
static int i=1;
cout << i++ << endl;
}

int g(double x, double y) {


return x * x - y * y + 1;
}
thevaluereturnedis

int andtruncationtakesplace

Itwouldbebettertoexplicitlyacknowledgethisw

int main() {
f();
f();
return 0;
}

ithacast

int g(double x, double y) {


return int (x * x - y * y + 1);
}
September2002

CS613:OO&C+:BasicC++

89

September2002

Astaticvariablecanbeusedasaflag

CS613:OO&C+:BasicC++

90

Functions: initialization
Defaultarguments

void f() {
static bool first_time = true;
if (first_time) {
cout << f called for the first time\n;
first_time = false; // false
}
cout << f called (every time)\n;
}

September2002

CS613:OO&C+:BasicC++

C++allowsafunctiontobecalledwithfewer
argumentsthanthereareparameters
Onceaparameterisinitialized,allsubsequent
parametersmustalsobeinitialized
void f(int i, float x=0; char ch=A) {
..
}
91

September2002

CS613:OO&C+:BasicC++

92

23

Functions: initialization

Function overloading

void f(int i, float x=0; char ch=A) {


...
}
...
f(5, 1.23, E);
f(5, 1.23); // equivalent to f(5,1.23,A);
f(5);
// equivalent to f(5,0,A);

twoormorefunctionswiththesamename
Thenumberortypesofparametersmust
differ:
void writenum(int i) {
cout i is << << i << endl;
}
void writenum(float x) {
cout << x is: << x << endl;
}

September2002

CS613:OO&C+:BasicC++

93

September2002

CS613:OO&C+:BasicC++

94

Functions:
Functions:o verloading

Referencesasreturnvalues
Avaluecanbereturnedfromafunctionusing
anyofthe3transmissionmodes.
Thisisespeciallyimportantwhenpassing
objects.

int g(int n) {
...
}
float g(int n) {
...
}

September2002

CS613:OO&C+:BasicC++

95

September2002

CS613:OO&C+:BasicC++

96

24

Functions:
Inlinefunctionsandmacros

Whatsbetter:#define,or
const

Afunctioncallcauses
ajumptoaseparateanduniquecodesegment
thepassingandreturningofargumentsandfunctionvalues
savingthestate

Inlinefunctionscause

#defineisapreprocessordirective
thus,constantssodefinedarenotseenbythecom
piler,orthe
debugger.
mightgetconfusingerrormessageaboutanumberw
hereyou
usedaconstant
soln:useconst
butHOW?

nojumporparameterpassing
nostatesaving
duplicationofthecodesegmentinplaceofthefunctioncall

September2002

CS613:OO&C+:BasicC++

97

const int Game::NUM_TURNS;

September2002

CS613:OO&C+:BasicC++

CS613:OO&C+:BasicC++

98

constantsinaclass(oldstyle):

Warninginadvance-constantsinaclass:

class Game {
private:
static const int NUM_TURNS = 5;
int scores[NUM_TURNS];
};

September2002

thisisansi
compliant,
butsome
compilers
mightnot
havecaught
up.gcchas!
99

classGame{
private:
enum{NUM_TURNS=5};
intscores[NUM_TURNS];
};
affectionatelyknownas
theenumhack!
Butdonthavetodo
itthiswayanymore.
September2002

CS613:OO&C+:BasicC++

100

25

Whichissafer:macroorinline?
whichfaster?whichsmaller?

Useinliningjudiciously

#define max(a, b) (a < b) ? a : b)


inline int max(int a, int b) { return a > b ? a : b; }
template <class T>
inline const T& max(const T& a, const T& b) {
return a > b ? a : b;
}

September2002

CS613:OO&C+:BasicC++

101

<iostream>ispartoftheANSIstandardC++librar
<iostream.h>isanartifactofpre-standardC++
However,vendorsdonotwantoldcodetobreak;th
willlikelycontinuetobesupported

September2002

CS613:OO&C+:BasicC++

September2002

CS613:OO&C+:BasicC++

102

Whatsthedifferencebetween
string.handstring

Whatsthedifferencebetween<iostream.h>and
<iostream>

Inlining issafer,providesopportunityforcompilerto
optimize,frequentlysmallerandfastercode!
overzealousinlining=codebloat==>pathological
paging,reduceinstructioncachehitrate
iffunctionbodyisshort,inlinedfunctionmaybeshorter
thancodegeneratedforthecall
theinlinedirectiveisacompilerhint,notacommand.
Compilersarefreetoignore

y
us,<iostream.h>

103

similartoiostream.handiostream
<string.h>-- theoldC-strings(char*)
<string>-- C++stringsandC-strings

September2002

CS613:OO&C+:BasicC++

104

26

Preprocessorfacilities

Whatsthealgorithmforold/new
oldheadersarelikelytocontinuetobesupported,even
thoughtheyrenotintheANSIstandard
newC++headershavesamenamew/outthe.h,but
contentsareinstd
Cheaders,like<stdio.h>continue,butnotinstd
newC++headersforfunctionalityinoldClibraryhave
nameslike<cstdio>;offersamecontentbutareinstd

September2002

CS613:OO&C+:BasicC++

105

Conditionalcompilation
ausefulwaytohandlemultipleincludefiles
#ifndef SOME___HEADER___FILE
#include SOME___HEADER___FILE
#endif

September2002

CS613:OO&C+:BasicC++

106

Stringsandpointers
int main()
{
char*s=rose";
cout <<s;
cout<<"\nlength ="<<strlen(s);
cout<<"\nlength ="<<length(s);
cout<<"\nlength ="<<length2(s);
cout <<"\nhead of"<<s<<"is"<<head(s);
cout <<"\ntail of"<<s<<"is"<<tail(s);
}

//pointersA.cc

Cstrings:

#include<iostream>
#include<cstring>

C++hasthembut:artifactofC
programmermustmanagememory
terminatedwith \0
built-inc-stringlibrary:
strlen(s):returnslengthofstring
strcat(s,t):place t atendof s
strcpy(s,t):copy t intobuffer s
strcmp(s,t):0ifs==t,<0ifs<t,>0ifs>t

int length(char*s){
if(s[0]=='\0'){return0;}
else{s=&s[1];return
1+length(s);}}
int length2(char*s){
if(s[0]=='\0'){return0;}
else{s++;return1+length(s);}}

output

charhead(char*s){return*s;}
char*tail(char*s){return++s;}

September2002

CS613:OO&C+:BasicC++

107

September2002

CS613:OO&C+:BasicC++

rose
length=4
length=4
length=4
headofroseisr
tailofroseisose
108

27

Commandlineparameters

Commandlineparameters
Integerparametersmustbeconverted:

main(intargc,char*argv[])
argc isthenumberofparameters
argv isanarrayofchar*with
argv[0]thefirstparameter
argv[1]thesecondparamter
etc.

main(int argc, char * argv[]) {


if (argc < 2) {
cout << usage: << argv[0]
<< <number> << endl;
return 1;
}
int n = atoi(argv[1]);

Notethatthereisalwaysatleastoneparameter
September2002

CS613:OO&C+:BasicC++

109

September2002

CS613:OO&C+:BasicC++

110

StatementsforusingDiskI/O

Readingfromfiles

#include<fstream>

Filesrepresentapermanentmedium
mustbeopened
insideprograms,fileshavealogicalname thatmus
tbemappedtothe
physicalname onthedisk
afterreadingfromorwritingtoafile,itshould
beclosed

September2002

CS613:OO&C+:BasicC++

111

ifstreammyInfile;
ofstreammyOutfile;

//declarations

myInfile.open(A:\\myIn.dat);
//openfiles
myOutfile.open(A:\\myOut.dat);
//doyourthinghere
myInfile.close();
//closefiles
myOutfile.close();

September2002

CS613:OO&C+:BasicC++

112

28

Whatdoesopeningafiledo?

associatestheC++identifierforyourfilewitht
hephysical(disk)name
forthefile
iftheinputfiledoesnotexistondisk,openis
notsuccessful
iftheoutputfiledoesnotexistondisk,anewf
ilewiththatnameis
created
iftheoutputfilealreadyexists,itiserased
placesa filereadingmarker attheverybeginningofthefile,pointingto
thefirstcharacterinit

September2002

CS613:OO&C+:BasicC++

#include<fstream>
main(intargc,char*argv[]){
if(argc!=2){
cout<<usage:<<argv[0]<<<filename><<endl;
return1;
}
fstreaminput;
input.open(argv[1],ios::in);
if(!input){
cout<<file:<<argv[1]<<doesnotexist!<<endl;
return1;
}
intcount=0;charch;input.get(ch);
while(!input.eof()){
if(ch==\n)++count;input.get(ch);
}
cout<<thereare:<<count<<linesin<<argv[1]<
}

#include <fstream>
main (int argc, char * argv[]) {
fstream input;
input.open(argv[1], ios::in);
int count = 0;
char ch;
input.get(ch);
while ( ! input.eof() ) {
if (ch == \n) ++count;
input.get(ch);
}
cout << there are: << count
<< lines in << argv[1] << endl;
}

Therearenochecks,see
ifuserinputthefilename,
doesthefileexist,
canitbeopened!

114

113

<endl;
115

#include<fstream>
voiddouble_space(istream &f,ostream&t){
charch;
while(f.get(ch)){
t.put(ch);
if(ch ==\n)t.put(ch);
}
}
int main(intargc,char*argv[]){
if(argc!=3){
cout<<usage:<<argv[0]<<<infile><outfile>;
return1;
}
istream fin(argv[1]);ostreamfout(argv[2]);
if(!fin){cout<<cantopen<<argv[1]<<endl;retur
if(!fout){cout<<cantopen<<argv[2]<<endl;return
double_space(fin,fout);fin.close();fout.close();return0;
}

n1;}
1;}
116

29

Recursion

StaticDataStructures- structs(withoutpointers)

// Recursion - factorial & fibonacci

//structures.cc
#include<iostream>

#include<iostream>
int factorial (int x){
if (x<1) return 1; else return x*(factorial (x-1));}

int main()
{
Ratio r;
r.num = 10;
r.den = 20;
print(r);
}

int main()
{ cout << "factorial 5 =" <<factorial(5)<<endl;
cout << "fibonacci 5 =" <<fibonacci(5);
}
CS613:OO&C+:BasicC++

117

StaticDataStructures- structs(withoutpointers)

118

A)Whentheinputis22
B)Whentheinputis21

Output:
10/20
10/20

int main()
{int n;
cout <<"Enteraninteger:";
cin >>n;
if(n=22) cout <<n<<"=22"<< endl;
elsecout <<n<<"!=22"<< endl;
}

int main(){
Ratio r;r.num = 10;r.den = 20;
Ratio2 rr; rr.r1 = r;rr.r2 = r;
print(rr);
}
CS613:OO&C+:BasicC++

CS613:OO&C+:BasicC++

Question1: Whatistheoutputfromthispieceofcode?

void print(Ratio2 rr){


print(rr.r1);print(rr.r2);
}

September2002

September2002

Revisionquiz

//structuresB.cc
#include<iostream>
struct Ratio{int num, den;};
struct Ratio2{Ratio r1, r2;};
void print(Ratio r){
cout <<r.num<<"/"<<r.den<<endl;}

Output:
10/20

void print(Ratio r){


cout <<r.num<<"/"<<r.den<<endl;}

int fibonacci (int x){


if (x==1) return 1;
if (x==2) return 1;
else return (fibonacci(x-2) + fibonacci(x-1));}

September2002

struct Ratio
{int num, den;};

119

September2002

CS613:OO&C+:BasicC++

120

30

Revisionquiz
Revisionquiz

Question2: Whatistheoutputfromthispieceofcodewhen10isinput?

int main()
{ int n=44;
cout <<"n="<<n<< endl;
{ int n;
cout <<"Enteraninteger:";
cin >>n;
cout <<"n="<<n<< endl;
}
{ cout <<"n="<<n<< endl;
}
{ int n;
cout <<"n="<<n<< endl;
}
cout <<"n="<<n<< endl;
}

Question1: Whatistheoutputfromthispieceofcode?
A)Whentheinputis22

22=22

B)Whentheinputis21

22=22

int main()
{int n;
cout <<"Enteraninteger:";
cin >>n;
if(n=22) cout <<n<<"=22"<< endl;
elsecout <<n<<"!=22"<< endl;
}
September2002

CS613:OO&C+:BasicC++

121

Revisionquiz

CS613:OO&C+:BasicC++

122

Revisionquiz

Question2: Whatistheoutputfromthispieceofcodewhen10isinput?

int main()
{ int n=44;
cout <<"n="<<n<< endl;
{ int n;
cout <<"Enteraninteger:";
cin >>n;
cout <<"n="<<n<< endl;
}
{ cout <<"n="<<n<< endl;
}
{ int n;
cout <<"n="<<n<< endl;
}
cout <<"n="<<n<< endl;
}
September2002

September2002

CS613:OO&C+:BasicC++

Question3:
Whatistheoutputfromthispieceofcodewhen123isinput?

int main()
{int n1,n2,n3;
cout <<"Enterthreeintegers:";
cin >>n1>>n2>>n3;
if(n1>=n2>=n3) cout <<"max="<<n1;}

n=44
Enteraninteger:10
n=10
n=44
n=10
n=44
Question:whythe2nd10?

Enterthreeintegers:123

123

September2002

CS613:OO&C+:BasicC++

124

31

Revisionquiz

Revisionquiz

Question3:

Question4:

Whatistheoutputfromthispieceofcodewhen123isinput?

Whatistheoutputfromthispieceofcodewhen124431isinput?

int main()
{int n1,n2,n3;
cout <<"Enterthreeintegers:";
cin >>n1>>n2>>n3;
if(n1>=n2>=n3) cout <<"max="<<n1;}

int main()
{ int n,sum;
cout <<"Enterasix-digitinteger:";
cin >>n;
sum=n%10+n/10%10+n/100%10+
n/1000%10+n/10000%10+n/100000;
cout <<"Theansweris"<<sum<<endl;
}

Enterthreeintegers:123

September2002

CS613:OO&C+:BasicC++

125

Revisionquiz

September2002

CS613:OO&C+:BasicC++

Revisionquiz

Question4:

Question5:

Whatistheoutputfromthispieceofcodewhen124431isinput?

Whatistheoutputfromthispieceofcodewhen4isinput?

int main()
{cout<<Inputaninteger:;
intn;
cin >>n;
for(int x=1;x<=12;x++)
{for(int y=1;y<=12;y++)
cout << setw(4)<<x*y;
cout << endl;
}}

int main()
{ int n,sum;
cout <<"Enterasix-digitinteger:";
cin >>n;
sum=n%10+n/10%10+n/100%10+
n/1000%10+n/10000%10+n/100000;
cout <<"Theansweris"<<sum<<endl;
}
Enterasix-digitinteger:124431
Theansweris15
September2002

126

CS613:OO&C+:BasicC++

Question:whatdoesinputdo?

127

September2002

CS613:OO&C+:BasicC++

128

32

Revisionquiz

Revisionquiz

Question5:

Question6:

Whatistheoutputfromthispieceofcodewhen4isinput?

Whatistheoutputfromthispieceofcodewhen70isinput?

int main()
{cout<<Inputaninteger:;
intn;
cin >>n;
for(int x=1;x<=12;x++)
{for(int y=1;y<=12;y++)
cout << setw(4)<<x*y;
cout << endl;
}}
Question:whatdoesinputdo?

September2002

int main()
{floatx;
cout <<"Enterapositivenumber:";
cin >>x;
int n=1;
while(n*n<=x)++n;
cout <<"Theansweris"
<<n-1<< endl;
}

Inputaninteger:4
123456789101112
24681012141618202224
369121518212427303336
4812162024283236404448
51015202530354045505560
61218243036424854606672
71421283542495663707784
81624324048566472808896
918273645546372819099108
102030405060708090100110120
112233445566778899110121132
1224364860728496108120132144

CS613:OO&C+:BasicC++

129

Revisionquiz

September2002

CS613:OO&C+:BasicC++

Revisionquiz

Question6:

Question7:

Whatistheoutputfromthispieceofcodewhen70isinput?

Giventhedefinitionofthefunctiondigit,below,whatistheme
expressiondigit(24681012,4)?

int main()
{floatx;
cout <<"Enterapositivenumber:";
cin >>x;
int n=1;
while(n*n<=x)++n;
cout <<"Theansweris"
<<n-1<< endl;
}

September2002

130

CS613:OO&C+:BasicC++

Enterapositivenumber:
70
Theansweris8

131

aningofthe

int digit(longn, int k)


{for(int i=0;i<k;i++)
n/=10;
returnn%10;
}

September2002

CS613:OO&C+:BasicC++

132

33

Revisionquiz

Revisionquiz
Question8:

Question7:
Giventhedefinitionofthefunctiondigit,below,whatistheme
expressiondigit(cc,4)?

Giventhedefinitionofthefunctionmin,below,whatistheoutput
mainprogramwhichtestsit?

aningofthe

int digit(longn, int k)


{for(int i=0;i<k;i++)
n/=10;
returnn%10;
}

Question:whyistheanswer

September2002

floatmin(floata[], int n)
{
floatmin=a[0];
for(int i=1;i<n;i++)
if(a[i]<min)min=a[i];
returnmin;}
8?

CS613:OO&C+:BasicC++

133

Revisionquiz

September2002

fromthe

int main()
{//teststhemin()function:
floata[]={6.6,9.9,3.3,7.7,
5.5,2.2,8.8,4.4};
cout <<"min(a,2)="<<
min(a,2)<< endl;
cout <<"min(a,8)="<<
min(a,8)<< endl;
}

CS613:OO&C+:BasicC++

134

Revisionquiz

Question8:
Giventhedefinitionofthefunctionmin,below,whatistheoutput
mainprogramwhichtestsit?

floatmin(floata[], int n)
{
floatmin=a[0];
for(int i=1;i<n;i++)
if(a[i]<min)min=a[i];
returnmin;}
min(a,2)=6.6
min(a,8)=2.2

September2002

Question9:

fromthe

Giventhedefinitionofthefunctionssumandsquare,below,what
outputfromthemainprogramwhichteststhem?

int main()
{//teststhemin()function:
floata[]={6.6,9.9,3.3,7.7,
5.5,2.2,8.8,4.4};
cout <<"min(a,2)="<<
min(a,2)<< endl;
cout <<"min(a,8)="<<
min(a,8)<< endl;
}

CS613:OO&C+:BasicC++

135

int sum(int (*pf)(int k), int n)


{int s=0;
for(int i=1;i<=n;i++)
s+=(*pf)(i);
returns;
}

isthe

int square(int k)
{returnk*k;
}

int main()
{ cout <<sum(square,4)<<
endl;}

September2002

CS613:OO&C+:BasicC++

136

34

Revisionquiz

Revisionquiz

Question9:

Question10:

Giventhedefinitionofthefunctionssumandsquare,below,what
outputfromthemainprogramwhichteststhem?

int sum(int (*pf)(int k), int n)


{int s=0;
for(int i=1;i<=n;i++)
s+=(*pf)(i);
returns;
}

Giventhedefinitionofthecapfunction,below,whatistheout
mainprogramwhichtestsit,whentheinputisJpaul Gibson?

int square(int k)
{returnk*k;
}

int main()
{ cout <<sum(square,4)<<
endl;}

30

September2002

isthe

CS613:OO&C+:BasicC++

137

Revisionquiz

J paul Gibson
AnswerisJPAULGIBSON
September2002

int main()
{char*line=newchar[81];
cout <<"Enterlineoftext
below:"<< endl;
cin.getline(line,80);
cap(line);
cout <<Answeris<<line
<<endl;
}

CS613:OO&C+:BasicC++

138

Revisionquiz

Question10:

Question10:

Giventhedefinitionofthecapfunction,below,whatistheout
mainprogramwhichtestsit,whentheinputisJpaul Gibson?

voidcap(char*s)
{if(s==NULL)return;
for(char*p=s;*p;p++)
if(*p>='a'&&*p<='z')
*p=(char)(*p-'a'+'A');
}

September2002

voidcap(char*s)
{if(s==NULL)return;
for(char*p=s;*p;p++)
if(*p>='a'&&*p<='z')
*p=(char)(*p-'a'+'A');
}

putfromthe

putfromthe

Giventhedefinitionofthecapfunction,below,whatistheout
mainprogramwhichtestsit,whentheinputisJpaul Gibson?

int main()
{char*line=newchar[81];
cout <<"Enterlineoftext
below:"<< endl;
cin.getline(line,80);
cap(line);
cout <<Answeris<<line
<<endl;
}

CS613:OO&C+:BasicC++

139

voidcap(char*s)
{if(s==NULL)return;
for(char*p=s;*p;p++)
if(*p>='a'&&*p<='z')
*p=(char)(*p-'a'+'A');
}
jPaulGibson
AnswerisJPAULGIBSON

September2002

putfromthe

int main()
{char*line=newchar[81];
cout <<"Enterlineoftext
below:"<< endl;
cin.getline(line,80);
cap(line);
cout <<Answeris<<line
<<endl;
}

CS613:OO&C+:BasicC++

140

35

NoughtsandCrosses- puttingitalltogether

NoughtsandCrosses

The(chosen/given)datastructure:-

The(chosen/given)datastructure:-

constboardsize =3;
typedef char XOBoard [boardsize][boardsize];

constintboardsize =3;
typedef char XOBoard [boardsize][boardsize];

Exampleofuse:

Exampleofuse:

int main()
{
XOBoard board;
initialise(board);
print(board);
playX(board,1,1);
print(board);
playO(board,0,0);
print(board);
}

September2002

voidinitialise(XOBoard);
voidprint(XOBoard);
void playX(XOBoard, int, int);
void playO(XOBoard, int, int);

Questions:
good/badstructure?
functionsrequired?

CS613:OO&C+:BasicC++

int main()
{\\ Asbefore
}

141

NoughtsandCrosses

September2002

GOODPROGRAMMING:
putfunctiontypedeclarationat
beginningoffilebeforethemain
program
putfunctiondefinitionsafterthe
mainprogram

CS613:OO&C+:BasicC++

142

NoughtsandCrosses
Designandtestonefunctionatatime(ifpossible)

Designandtestonefunctionatatime(ifpossible)

print-

voidprint(XOBoard board)
{
cout << endl;
for(int i=0;i<3;i++)
{for(int j=0;j<3;j++)
{ cout <<board[i][j];
if(j<2) cout <<"|";
}
cout << endl;
if(i<2) cout <<"-----"<< endl;
}
}

initialise-

voidinitialise(XOBoard board)
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
board[i][j]='';
}

September2002

CS613:OO&C+:BasicC++

143

September2002

CS613:OO&C+:BasicC++

144

36

NoughtsandCrosses

NoughtsandCrosses

||
--------||
--------||

Designandtestonefunctionatatime(ifpossible)
playXandPlayO-

Questions:
advantages

void playX(XOBoard board, int i, int j)


{
board[i][j]='X';
}

disadavantages

void playO(XOBoard board, int i, int j)


{
board[i][j]='O';
}

September2002

CS613:OO&C+:BasicC++

145

int main()
{
XOBoard board;
initialise(board);
print(board);
playX(board,1,1);
print(board);
playO(board,0,0);
print(board);
}

September2002

||
--------|X|
--------||

Checkthatthe
outputisproperly
alignedonthe
computerscreen

O||
--------|X|
--------||

CS613:OO&C+:BasicC++

146

NoughtsandCrosses:puttingittogether
// XOBoard
//Proceduralprogramming
//2/10/2000
#include<iomanip>
#include<iostream>
constintboardsize =3;
typedef char XOBoard [boardsize][boardsize];
voidinitialise(XOBoard);
voidprint(XOBoard);
void playX(XOBoard, int, int);
void playO(XOBoard, int, int);
voidinitialise(XOBoard board)
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
board[i][j]='';
}
September2002

voidprint(XOBoard board)
{cout << endl;
for(int i=0;i<3;i++)
{for(int j=0;j<3;j++)
{ cout <<board[i][j];
if(j<2) cout <<"|";
}
cout << endl;
if(i<2) cout <<"-----"<< endl;
}}
voidplayX(XOBoard board, int i, int j)
{board[i][j]='X';}
voidplayO(XOBoard board, int i, int j)
{board[i][j]='O';}
int main()
{
XOBoard board;
initialise(board);print(board);
playX(board,1,1);print(board);
playO(board,0,0);print(board);
}

CS613:OO&C+:BasicC++

147

37

Potrebbero piacerti anche