Title: arrays
1arrays
- An array is a collection of data, all of the same
data type, that is accessed with an index - If a variable is like a "mailbox", an array is
like the mailboxes at a post office or an
apartment building a row of otherwise identical
boxes with different numbers. - We tell C we want to make an array by using
(square brackets)
2arrays
- int naNums3
- naNums0 5
- naNums1 -4
- naNums2 17
naNums
garbage
garbage
garbage
0 1 2
5
-4
17
naNums
0 1 2
3arrays
- May be declared and initialized in one line
- int naNums 5,-4,17
- Are "zero-based" First index is 0
- coutltltnaNums1 //displays -4
- You can make an array of any data type
- char caLetters a, b, c
- string saAnswers yes, no
- Good Style The first letter should show data
type, followed by a for array
4A Simple Program using an array
- include ltiostream.hgt
- include ltstdlib.hgt
- int main()
-
- double daNums 5, 1.5, 7, 3.2
- for(int nIndex 3 nIndex gt 0 nIndex--)
- coutltltdaNumsnIndexltlt", "
- system("PAUSE")
- return 0
5Don't confuse the index with the value that is
stored there
- double daNums 5, 1.5, 7, 3.2
- daNums2
- 2 is the index (think apartment number)
- 7 is the value that is stored at index 2
6Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltstringgt
- using namespace std
- int main()
-
- string saWords "The", "Quick", "Brown",
"Fox", - "Jumped", "Over", "The", "Lazy", "Red",
"Dog" - for(int nIndex 0 nIndex lt 10
nIndexnIndex2) - coutltltnIndexltlt" "ltltsaWordsnIndexltltendl
- system("PAUSE")
- return 0
7Practice Quiz Questions
- For the following function
- void TripleIt(int nNum)
-
- coutltlt3nNumltltendl
-
- (T/F) TripleIt(int nNum) is a correct function
call - (T/F) void TripleIt(int nNum) is a correct
function call - (T/F) TripleIt(3) is a correct function call
- (T/F) int nI3 TripleIt(nI) is a correct
function call - (T/F) void TripleIt(int nNum) is a correct
function prototype - (T/F) void TripleIt(int nNum) is a correct
function header - What is the output of the following program?
- void Mystery(int nNum1, int nNum2)
- int main()
-
- int nA 5, nB 6
- Mystery(nA,nB)
- coutltltnAltlt", "ltltnBltltendl
8Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- const int nNUM_MAILBOXES 5
- int main()
-
- int naNumsnNUM_MAILBOXES
- for (int nIndex 0 nIndex lt nNUM_MAILBOXES
nIndex) - if(nIndex 2 0) //if nIndex is even
- naNumsnIndex nIndex
- else if (nIndex 3 0) //if nIndex is a
multiple of 3 - naNumsnIndex 17
- else
- naNumsnIndex 3
- for(int nIndex 0 nIndex lt nNUM_MAILBOXES
nIndex) - coutltltnaNumsnIndexltlt", "
- system("PAUSE")
- return 0
9strings and outtextxy
- outtextxy was written before the new style C
strings, so it expects an "old-fashioned" C
string - There is a conversion function .c_str() converts
an C string to an "old-fashioned" C string. - string sString "Hello World!"
- outtextxy(30,240,sString.c_str())
10A string is an array
- You can use with a string, just like with an
array - string sWord "Hello World"
- coutltltsWord0ltltendl
- //displays 'H'
11A string is an array
- You can use with a string, just like with an
array - string sWord "Hello World"
- coutltltsWord0ltltendl
- //displays 'H'
- coutltltsWord.length()ltltendl
- //displays 11
12A string is an array
- You can use with a string, just like with an
array - string sWord "Hello World"
- coutltltsWord0ltltendl
- //displays 'H'
- coutltltsWord.length()ltltendl
- //displays 11
- coutltltsWordsWord.length()-1
- ltltendl
- //displays 'd'
13bool
- A data type, just like int, double, char
- A bool mailbox can only hold one of two values
true or false - bool bState true
- bState (nNum gt 3)
- You can use a bool anywhere you would use a
condition - if(bState)
- coutltltnNum is greater than 3
14Problem Write a function that determines if a
student will graduate
- bool IsGraduating(int nCredits,
- bool bPassedExam)
-
- if(nCredits gt 230 bPassedExam)
- return true
- else
- return false
-
15Problem Write a function that determines if a
student will graduate
- Here's the same function in one line of code!
- bool IsGraduating(int nCredits,
- bool bPassedExam)
-
- return(nCredits gt 230 bPassedExam)
-
16What is the output of this program?
bool IsMatch(string sWord)
if(sWord.length()gt3) return sWord0
sWord2 else return false
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltstringgt
- using namespace std
- bool IsMatch(string sWord)
- int main()
-
- if(IsMatch("elephant"))
- coutltlt"Match 1"ltltendl
- if(IsMatch("alligator"))
- coutltlt"Match 2"ltltendl
- if(IsMatch("ox"))
- coutltlt"Match 3"ltltendl
- if(IsMatch("pup fish"))
- coutltlt"Match 4"ltltendl
- system("PAUSE")
- return 0
-
17getline()
- string sName
- coutltlt"Please enter your name "
- getline(cin,sName)
- //user enters Mr. Simon
- coutltlt"You entered "ltltsNameltltendl
- //displays You entered Mr. Simon
- Stores the entire line, including spaces
18getline()
- Rule Don't use cin and getline in the same
program if you can avoid it. - If you really must use both cin and getline in
the same program, it is a good idea to use a
cin.ignore(80,\n) after each cin to flush the
input stream of any extra end of line
characters.
19What is the output of this program?
- bool Mystery (string sWord, char cLetter)
- int main()
-
- if(Mystery("antelope", 'e'))
- coutltlt"One"ltltendl
- else
- coutltlt"Two"ltltendl
- if(Mystery("aardvark", 'a'))
- coutltlt"Three"ltltendl
- else
- coutltlt"Four"ltltendl
- system("PAUSE")
- return 0
-
- bool Mystery(string sWord, char cLetter)
-
- int nSum 0
- for(int nI 0 nI lt sWord.length() nI)
- if(sWordnI cLetter)
20"Adding" strings
- What would this code display?
- string sWord
- "Hello " "there"
- coutltltsWordltltendl
21"Adding" strings
- What would this code display?
- string sWord
- "Hello " "there"
- coutltltsWordltltendl
- /Sample Output
- Hello there/
22"Adding" strings
- What would this code display?
- string sWord
- "Hello " "there"
- coutltltsWordltltendl
- /Sample Output
- Hello there/
23"Adding" strings
- When you use the operator with strings, it's
called "Concatenation" - That just means "adding on to the end"
- string sWord
- "Hello " "there"
- coutltltsWordltltendl
- /Sample Output
- Hello there/
24ctype.h
- bool isalpha(char cChar)
- returns true if cChar is a letter of the
alphabet, false otherwise - bool isalnum(char cChar)
- returns true if cChar is a letter or number,
false otherwise - char tolower(char cChar)
- returns the lowercase of cChar
- char toupper(char cChar)
- returns the uppercase of cChar
25Problem Write a function that returns an upper
case version of a string
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltstringgt
- using namespace std
- string MakeUpper(string sWord)
- int main()
-
- string sWord "hello"
- coutltltMakeUpper(sWord)ltltendl //HELLO
- system("PAUSE")
- return 0
-
- string MakeUpper(string sWord)
-
- ???
26Problem Write a function that returns an upper
case version of a string
- int main()
-
- string sWord "hello"
- coutltltMakeUpper(sWord)ltltendl //HELLO
- system("PAUSE")
- return 0
-
- string MakeUpper(string sWord)
-
- string sNewWord
- ???
- return sNewWord
27Problem Write a function that returns an upper
case version of a string
- int main()
-
- string sWord "hello"
- coutltltMakeUpper(sWord)ltltendl //HELLO
- system("PAUSE")
- return 0
-
- string MakeUpper(string sWord)
-
- string sNewWord ""
- for(int nI 0 nI lt sWord.length() nI)
- sNewWord (char)toupper(sWordnI)
- return sNewWord
28What is the output?
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltctype.hgt
- include ltstringgt
- using namespace std
- string Mystery(string sText)
- int main()
-
- coutltltMystery("Testing, 1,2,3")ltltendl
- system("PAUSE")
- return 0
-
- string Mystery(string sText)
-
- string sNew ""
- for(int nI 0 nI lt sText.length() nI)
- if(!isalpha(sTextnI))
- sNew sNew "x"
- else if(tolower(sTextnI)sTextnI)
29More string functions
- Comparison
- !
- lt lt gt gt //same case alphabetically
- Input cin
- string sName
- coutltlt"Please enter your name "
- cingtgtsName
- //user enters Mr. Simon
- coutltlt"You entered "ltltsNameltltendl
- //displays You entered Mr.
- Input with cin is delimited by whitespace
30More string functions
- Concatenation (the operator)
- string sString1 "Hello "
- string sString2 "World!"
- string sString3 sString1 sString2
- coutltltsString3ltltendl //Hello World!
- Substrings
- coutltltsString1.substr(3,2)ltltendl // lo
- Indexing
- coutltltsString11ltltendl //e
- Length
- coutltltsString1.length()ltltendl //6
- Find
- coutltltsString1.find('l')ltltendl //2
31What is the output of this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltstringgt
- using namespace std
- int main()
-
- string sOne "abccba"
- string sTwo "xyzzyx"
- string sThree sOne sTwo
- coutltltsThreeltltendl
- coutltltsThree.length()ltltendl
- coutltltsThree11ltltendl
- coutltltsThree.find('c')ltltendl
- coutltltsThree.substr(4,3)ltltendl
- system("PAUSE")
- return 0
32The Palindrome Algorithm
- An Algorithm is the steps you take to solve a
problem - What steps would you take to see if the following
word is a palindrome? - rewriter
-
33The Palindrome Algorithm
34The Palindrome Algorithm
35The Palindrome Algorithm
36The Palindrome Algorithm
- Start by comparing the first and last letters
- If they are the same, does that mean the word is
a palindrome? - If they are different, does that mean the word is
NOT a palindrome? - rewriter
- 01234567
37The Palindrome Algorithm
- Start by comparing the first and last letters
- If they are the same, does that mean the word is
a palindrome? - If they are different, does that mean the word is
NOT a palindrome? - rewriter
- 01234567
- int nFirst 0
- int nLast sWord.length() 1
- if(sWordnFirst!sWordnLast)
- ????
38The Palindrome Algorithm
- Start by comparing the first and last letters
- If they are the same, does that mean the word is
a palindrome? - If they are different, does that mean the word is
NOT a palindrome? - rewriter
- 01234567
- int nFirst 0
- int nLast sWord.length() 1
- if(sWordnFirst!sWordnLast)
- return false
39The Palindrome Algorithm
- rewriter
- 01234567
- int nFirst 0
- int nLast sWord.length() 1
- if(sWordnFirst!sWordnLast)
- return false
- else
- ???
40The Palindrome Algorithm
- rewriter
- 01234567
- int nFirst 0
- int nLast sWord.length() 1
- while(???)
-
- if(sWordnFirst!sWordnLast)
- ???
- else
- ???
-
- ???
41Getting data in and out of functions
- Arguments allow data to passed into a function
- There are two ways to data out of a function
- Pass by reference arguments
- return statements
42An Add function with a return statement
- include ltiostream.hgt
- include ltstdlib.hgt
- int Add(int nNum1, int nNum2)
- int main()
-
- coutltltAdd(2,2)ltltendl
- system("PAUSE")
- return 0
-
- int Add(int nNum1, int nNum2)
-
- return nNum1 nNum2
43You could write an Add function with pass by
reference arguments, but it would be uglier
- include ltiostream.hgt
- include ltstdlib.hgt
- void Add(int nNum1, int nNum2, int nAnswer)
- int main()
-
- int nSum
- Add(2,2,nSum)
- coutltltnSumltltendl
- system("PAUSE")
- return 0
-
- void Add(int nNum1, int nNum2, int nAnswer)
-
- nAnswer nNum1 nNum2
44Good Style
- Always use a return statement to get data out of
a function, unless - You need to get more than one piece of data out
of the function (then use pass by reference
arguments) - Avoid using both pass by reference and return
statements
45Practice Quiz Question Find the output
- int Mystery(int nNum)
- int main()
-
- coutltltMystery(2)ltltendl
- coutltltMystery(3)ltltendl
- coutltltMystery(Mystery(2))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery(int nNum)
-
- int nSum 0
- while(nNum gt 0)
-
- nSum nSum nNum
- nNum--
-
- return nSum
46Functions can be used for value or effect
- An effect might be to display something on the
screen, make a noise, or stop the program - Functions that have an effect usually have void
as the return type - Here are some prototypes
- void circle (int nX, int nY, int nRadius)
- void line (int nX1, int nY1, int nX2, int nY2)
- void delay (int nMillisec)
- void cleardevice ()
- void closegraph ()
47Functions can be used for value or effect
- A value could be an int, char, string, bool or
any other data type - Functions that return a value have a return type
other than void - bool kbhit ()
- char getch ()
- bool Palindrome (string sText)
- bool isalpha(char cChar)
- char tolower(char cChar)
48A common mistake
- Beginning programmers often forget to use the
value a function returns -
- coutltlt"Please enter a word"ltltendl
- getline(cin,sWord)
- Palindrome(sWord) //oops!
49A common mistake
- Palindrome is returning a true or false, but this
program isn't using it -
- coutltlt"Please enter a word"ltltendl
- getline(cin,sWord)
- Palindrome(sWord) //oops!
- true
50A common mistake
- the returning true or false should be stored in
a variable or used in a condition -
- coutltlt"Please enter a word"ltltendl
- getline(cin,sWord)
- if(Palindrome(sWord)) //better!
- coutltlt" is a palindrome"ltltendl
51A common mistake
- the returning true or false should be stored in
a variable or used in a condition -
- coutltlt"Please enter a word"ltltendl
- getline(cin,sWord)
- bool bAnswer Palindrome(sWord)
- if(bAnswer) //this is also better!
- coutltlt" is a palindrome"ltltendl
52What is the output?
- int main()
-
- char caChars 'x', '1', '?', ' ', 'X',
'' - for(int nI 0 nI lt 6 nI)
-
- char cChar caCharsnI
- coutltltcChar
- if(isalpha(cChar))
-
- if(toupper(cChar) cChar)
- coutltlt"p"
- if(tolower(cChar) cChar)
- coutltlt"w"
-
- if(isalnum(cChar))
- coutltlt"t"
- if(!isalnum(cChar))
- coutltlt"o"
- coutltltendl
532 dimensional arrays
- Can be thought of as a grid with rows and
columns
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
542 dimensional arrays
- int naNums23 -3, -1, 5,
- 7, 12, 13
- //Note rows first, then columns
- coutltltnaNums12 //displays 13
- coutltltnaNums21 //Crash!
column 0 1 2
-3
-1
5
row 0
7
12
13
row 1
55A 2 dimensional array of SAT words
- string saSAT32
- "accomplish", "To bring to pass.",
- "adhere", "To stick fast or together.",
- "amity", "Friendship."
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
56A 2 dimensional array of SAT words
- int nCorrect rand()??
- coutltlt"Which word has the definition "
- ltltsaSAT????ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
57A 2 dimensional array of SAT words
- int nCorrect rand()3
- coutltlt"Which word has the definition "
- ltltsaSAT????ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
58A 2 dimensional array of SAT words
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
59A 2 dimensional array of SAT words
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- //Let's make A the correct answer
- coutltlt"A "ltltsaSAT????ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
60A 2 dimensional array of SAT words
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- //Let's make A the correct answer
- coutltlt"A "ltltsaSATnCorrect0ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
61A 2 dimensional array of SAT words
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- //Now choose a random wrong answer
- coutltlt"B "ltltsaSAT????ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
62A 2 dimensional array of SAT words
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- coutltlt"B "ltltsaSATrand()30ltltendl
column 0 1
accomplish
To bring to pass
row 0
adhere
To stick fast or together
row 1
amity
Friendship
row 2
63Problem There's a chance that the wrong answer
and the corrrect answer could be the same!
- int nCorrect rand()3 //let's say 1
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- coutltlt"B "ltltsaSATrand()30ltltendl
64Problem There's a chance that the wrong answer
and the corrrect answer could be the same!
- int nCorrect rand()3
- int nWrong
- do
-
- nWrong ??
- while(??)
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- coutltlt"B "ltltsaSATnWrong0ltltendl
65Problem There's a chance that the wrong answer
and the corrrect answer could be the same!
- int nCorrect rand()3
- int nWrong
- do
-
- nWrong rand()3
- while(??)
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- coutltlt"B "ltltsaSATnWrong0ltltendl
66Problem There's a chance that the wrong answer
and the corrrect answer could be the same!
- int nCorrect rand()3
- int nWrong
- do
-
- nWrong rand()3
- while(nWrong nCorrect)
- coutltlt"Which word has the definition "
- ltltsaSATnCorrect1ltltendl
- coutltlt"A "ltltsaSATnCorrect0ltltendl
- coutltlt"B "ltltsaSATnWrong0ltltendl
67Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
68Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
3
4
4
3
nA
4
nB
3
69Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
7
nA
4
nB
3
70Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
"Nested" function call
3
4
4
3
nA
3
nB
4
71Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
7
nA
nB
72Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
7
7
5
nA
5
nB
7
73Practice Quiz Question What is the output of
this program?
- include ltiostream.hgt
- include ltstdlib.hgt
- int Mystery(int nA, int nB)
- int main (void)
-
- int nY4, nZ3
- coutltltMystery(nY,nZ)ltltendl
- coutltltMystery(5,Mystery(nZ,nY))ltltendl
- system("PAUSE")
- return 0
-
- int Mystery (int nA, int nB)
-
- coutltlt"Hello"ltltendl
- return nAnB
-
12
7
5
nA
5
nB
7
74Pong
75Pong
76Pong
- For many people, Pong was the first time they
used a computer - Brought the first computers into people's homes
- Written by Alan Alcorn (a Lowell grad) for Atari
- First Pong game was installed in a Sunnyvale bar
in September 1972 - Two weeks later the machine stopped
workingbecause all the quarters had jammed it - Original Paddles had eight segmentsdifferent
segments gave different angles
77The original arcade Pong game was basically some
logic chips hooked up to an actual TV set with an
added coin mechanism.
78Pong was not the first computer game
- 10 years before Pong, there was another, much
more sophisticated computer game
79Spacewar!
80Spacewar!
- Written by members of the MIT model railroad club
beginning in 1961 - They also coined the word "hack"
- Code was kept in an unlocked draweranyone was
free to modify it - Programmed on the Digital Equipment PDP-1, one of
the first computers with a monitor - Club members built the world's first joysticks
- Later modified by Atari (stolen?) to become
Asteroids
81Pong Spin-offs
82Pong Spin-offs
83Pong Spin-offs
84Pong Spin-offs
85Pong Spin-offs
86Pong Spin-offs
87Pong Spin-offs
88Pong Spin-offs
89Pong Spin-offs
90Pong Spin-offs
91Pong Spin-offs
92Pong Spin-offs
93Pong Spin-offs
94Pong Spin-offs
- and many, many others. . .
95And from these humble beginnings
- Computer gaming is now a huge industry with
revenue over 7 billion dollars in 2005 - 'Mario' has made twice the revenue of all the
'Star Wars' movies combined - Computer Games and entertainment software are the
fastest growing area of the computer software
industry (which is itself one of the fastest
growing areas of the economy)
96Programming Pong
- To keep things simple we'll write a single player
pong game - The main function will have the animation loop
- There will be additional functions for moving,
drawing and erasing the paddle and ball
97Starting with a "Bouncing Ball"
- We'll build the program "Bottom Up"
- Start with the "Bouncing Ball" and add the paddle
later
98The "Bouncing Ball" Algorithm The Universal
Animation Loop
- First, we want the ball to continue to move, even
if no key is pressed. The loop is - while(no key is pressed)
-
- Erase the ball
- Move the ball
- Bounce the ball
- Draw the ball
- Wait
99The Pong Ball Functions
- void DrawBall(int nX,int nY)
- void EraseBall(int nX,int nY)
- void Move(int nX,int nY,
- bool bGoingRight,bool bGoingDown)
- void Bounce(int nX,int nY,
- bool bGoingRight,bool bGoingDown)
- Notice that nX, and nY are reference arguments in
Move, because they change - Likewise, bGoingRight, and bGoingDown are
reference arguments in Bounce
100Adding a Paddle A loop inside of another loop
- First, we'll keep the ball loop. . .and add
another loop around it - while(no key is pressed)
-
- Erase the ball
- Move the ball
- Bounce the ball
- Draw the ball
- Wait
101Adding a Paddle A loop inside of another loop
- Then, if a key is pressed, we stop moving the
ball just long enough to take care of the paddle,
and then go back to moving the ball - do
-
- while(no key is pressed)
-
- Ball moving
-
- Get the key pressed by the user
- Erase the paddle
- if the key pressed means "right"
- Move the paddle to the right
- else if it means "left"
- Move the paddle to the left
- Draw the paddle
- while( key pressed does NOT mean "quit")
102The Pong Paddle Functions
- void DrawPaddle (int nX, int nY)
- void ErasePaddle (int nX, int nY)
103BallMasterwww.blueteagames.com
by Steven Zhao class of 2001 In BallMaster, you
guide a flying ball through dangerous adventures.
With the aid of your computerized assistant, you
fend off a variety of beasts that attack you as
you float through the air. Other Games Cactus
Bruce and the Corporate Monkeys, Meeklits and
HeliumMan-X
104Using file input output to store the high score
- Earlier in the course, we used redirection to
tell Windows (the OS) that input would come from
a data file - There is another technique where we can use C
to accomplish the same thing - If we are keeping score in Pong, we can store the
high score in a file
105A program that gets a number and displays it to
the screen
- include ltiostream.hgt
- include ltstdlib.hgt
- int main()
-
- int nNum
- cingtgtnNum
- coutltlt"The number is "ltltnNumltltendl
- system("PAUSE")
- return 0
106The same program modified to use file input
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltfstream.hgt
- int main()
-
- ifstream fin("input.txt")
- if(!fin)
- coutltlt"Error! file not found"ltltendl
- else
-
- int nNum
- fingtgtnNum
- coutltlt"The number is "ltltnNumltltendl
-
- system("PAUSE")
- return 0
107file input
- include ltfstream.hgt
- Include the "file stream" library
- ifstream fin("input.txt")
- Declare the "input stream" and name it fin
- Associate it with the file input.txt in the
Dev-C folder - if(!fin)
- coutltlt"Error! file not found"ltltendl
- Check to see if the file is there. The most
common problem in file input is a non-existent or
misplaced file. -
108Let's go back to our simple program that gets a
number and displays it to the screenNow we'll
modify it to use file output
- include ltiostream.hgt
- include ltstdlib.hgt
- int main()
-
- int nNum
- cingtgtnNum
- coutltlt"The number is "ltltnNumltltendl
- system("PAUSE")
- return 0
109Let's go back to our simple program that gets a
number and displays it to the screenNow will
modify it to use file output
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltfstream.hgt
- int main()
-
- ofstream fout ("output.txt")
- int nNum
- cingtgtnNum
- foutltlt"The number is "ltltnNumltltendl
- system("PAUSE")
- return 0
110If we look inside the Dev-C folder after we run
the program, we should now see a file output.txt
with our output
111file output
- ofstream fout ("output.txt")
- Declare an "output file stream" and call it fout
- Associate it with a file called output.txt
- Note output.txt will be created if it doesn't
already exist -
- foutltlt"The number is "ltltnNumltltendl
- Use fout just like cout
112A program that reads in the high score and
compares it with the current score
- include ltiostream.hgt
- include ltstdlib.hgt
- include ltfstream.hgt
- int main()
-
- ifstream fin ("highscore.txt")
- if(!fin)
- coutltlt"Error! file not found"ltltendl
- else
-
- int nHighScore
- int nScore 1000
- fingtgtnHighScore
- fin.close() //note that fin must be
closed - //before we can use the
same - //file for fout
- if(nScore gt nHighScore)
-
113Practice Quiz Questions
- 1. True/false The following is a correct
bounce function for Pong - if(nX gt 0)
- bRight true
- if(nX lt 640)
- bRight false
- if(nY gt 0)
- bUp false
- if(nY lt 480)
- bUp true
- 2. If the function prototype is
- void Bounce(int nX, int nY, bool bUp, bool
bRight) - then a correct call would be Bounce(nX,nY,bUp,bR
ight) - 3.For
- int naArray32 56, -17,
- 23, 45
- 22, 45
- naArray12 is -17.
- 4. In the following code, nRand1 and nRand2 will
always be different - int nRand1 rand()100 1
114What will be displayed?
- void RandomNumber()
- int main()
-
- RandomNumber()
- system("PAUSE")
- return 0
-
- void RandomNumber()
-
- coutltltrand()ltltendl
-
115What will be displayed now?
- void RandomNumber()
- int main()
-
- RandomNumber()
- system("PAUSE")
- return 0
-
- void RandomNumber()
-
- coutltltrand()ltltendl
- RandomNumber()
116The program will repeatedly display random
numbersproblem is it won't stop!
- void RandomNumber()
- int main()
-
- RandomNumber()
- system("PAUSE")
- return 0
-
- void RandomNumber()
-
- coutltltrand()ltltendl
- RandomNumber()
117Recursion A function that calls itself
- void RandomNumber()
-
- coutltltrand()ltltendl
- RandomNumber()
-
- Recursion is another way of making a loop
- Recursion is hard to controlit's very easy to
create an infinite loop that never stops
118In recursion, the "stopping point" is called the
base case
- void RandomNumber(int nTimes)
-
- if(nTimes 0)
- coutltlt"Stop!"ltltendl
- else
-
- coutltltrand()ltltendl
- RandomNumber(nTimes-1)
-
-
- The base case stops the recursive calls
119- include ltiostream.hgt
- include ltstdlib.hgt
- void RandomNumber(int nTimes)
- int main()
-
- RandomNumber(5)
- system("PAUSE")
- return 0
-
- void RandomNumber(int nTimes)
-
- if(nTimes 0)
- coutltlt"Stop!"ltltendl
- else
-
- coutltltrand()ltltendl
- RandomNumber(nTimes-1)
-
120Recursion
- There are two basic ways to make things happen
"over and over again" in programming - Loops
- Recursion
- In theory, anything you can do with loops, you
can do with recursion ( vice versa)
121A loop that "counts" from 1 to 10
- int main()
-
- for(int nI 1 nI lt 10 nI)
- coutltltnIltltendl
- system("PAUSE")
- return 0
122A Recursive Function that "counts" from 1 to 10
- void RecursiveFunction(int nNum)
- int main()
-
- RecursiveFunction(1)
- system("PAUSE")
- return 0
-
- void RecursiveFunction(int nNum)
-
- if(nNum 10)
- coutltltnNumltlt" and stop"ltltendl
- else
-
- coutltltnNumltltendl
- RecursiveFunction(nNum1)
-
123A Recursive Function calls itself
- void RecursiveFunction(int nNum)
-
- if(nNum 10)
- coutltltnNumltlt" and stop"ltltendl
- else
-
- coutltltnNumltltendl
- RecursiveFunction(nNum1)
-
124Just like a loop, it has a starting point, a
stopping point, and a way to get from one to the
other
- void RecursiveFunction(int nNum)
- int main()
-
- RecursiveFunction(1)//start at one
- system("PAUSE")
- return 0
-
- void RecursiveFunction(int nNum)
-
- if(nNum 10)//stop at 10
- coutltltnNumltlt" and stop"ltltendl
- else
-
- coutltltnNumltltendl
- RecursiveFunction(nNum1)//increment by 1
-
125Recursion
- Just like a loop, if recursion doesn't stop,
we'll crash the computer - void RecursiveFunction(int nNum)
-
- if(nNum 10)
- coutltltnNumltlt" and stop"ltltendl
- else
-
- coutltltnNumltltendl
- RecursiveFunction(nNum1)
-
-
- The if statement is called the base case
- In the base case there is no recursive call, and
the recursion stops
126What is the output?
- int Mystery(int nNum)
- int main()
-
- coutltltMystery(4)ltltendl
- system("PAUSE")
- return 0
-
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
127To understand, start with the base case
- What would Mystery(1) return?
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
128To understand, start with the base case
- What would Mystery(1) return?
- 1
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
129To understand, start with the base case
- What would Mystery(1) return?
- 1
- What would Mystery(2) return?
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
130To understand, start with the base case
- What would Mystery(1) return?
- 1
- What would Mystery(2) return?
- 2 Mystery(1) 2 1 2
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
131To understand, start with the base case
- What would Mystery(1) return? 1
- What would Mystery(2) return?
- 2 Mystery(1) 2 1 2
- What would Mystery(3) return?
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
132To understand, start with the base case
- What would Mystery(1) return? 1
- What would Mystery(2) return?
- 2 Mystery(1) 2 1 2
- What would Mystery(3) return?
- 3 Mystery(2) 3 2 6
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
133To understand, start with the base case
- What would Mystery(4) return?
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
134To understand, start with the base case
- What would Mystery(4) return?
- 4 Mystery(3) 4 6 24
- int Mystery(int nNum)
-
- if(nNum lt 1)
- return 1
- else
- return nNum Mystery(nNum - 1)
135Recursion in the real world
- Recursion is best used to model problems that can
be described recursively - Example Trees
136Tree
- A tree isn't made of just one branch or trunk
137Tree
- Each branch has smaller and smaller branches
138Tree
- Each branch has smaller and smaller branches
139Tree
- If you keep putting branches in at a smaller and
smaller scale, you can get a very interesting
tree (Broccoli?)
140Recursion in Fern Leaves
141This process of repeating the same design at a
continually decreasing scale is an example of a
Fractal
142Problem write a program to display the first 20
fibonacci numbers
- 0,1,1,2,3,5,8,13,21,. . .
143Problem write a program to display the first 20
Fibonacci numbers
- 0,1,1,2,3,5,8,13,21,. . .
- after 0 and 1, each successive Fibonacci number
is the sum of the two previous Fibonacci numbers
144Problem write a program to display the first 20
Fibonacci numbers
- 0,1,1,2,3,5,8,13,21,. . .
- after 0 and 1, each successive Fibonacci number
is the sum of the two previous Fibonacci numbers
145Problem write a program to display the first 20
Fibonacci numbers
- int Fibonacci(int nNum)
- int main()
-
- for(int nI 0 nI lt 20nI)
- coutltltFibonacci(nI)ltlt", "
- system("PAUSE")
- return 0
-
- int Fibonacci(int nNum)
-
- ???
146Problem write a program to display the first 20
Fibonacci numbers
- What's the base case?
- int Fibonacci(int nNum)
-
- ???
147Problem write a program to display the first 20
Fibonacci numbers
- What's the base case?
- int Fibonacci(int nNum)
-
- if(nNum 0)
- return ??
148Problem write a program to display the first 20
Fibonacci numbers
- What's the base case?
- int Fibonacci(int nNum)
-
- if(nNum 0)
- return 0
- else if(nNum 1)
- return ??
149Problem write a program to display the first 20
Fibonacci numbers
- From now on, add the two previous numbers
- int Fibonacci(int nNum)
-
- if(nNum 0)
- return 0
- else if(nNum 1)
- return 1
- else
- return ??
150Problem write a program to display the first 20
Fibonacci numbers
- From now on, add the two previous numbers
- int Fibonacci(int nNum)
-
- if(nNum 0)
- return 0
- else if(nNum 1)
- return 1
- else
- return Fibonacci(??)
151Problem write a program to display the first 20
Fibonacci numbers
- From now on, add the two previous numbers int
Fibonacci(int nNum) -
- if(nNum 0)
- return 0
- else if(nNum 1)
- return 1
- else
- return Fibonacci(nNum - 1)
- Fibonacci(nNum 2)
152Problem write a program to display the first 20
Fibonacci numbers
- include ltiostream.hgt
- include ltstdlib.hgt
- int Fibonacci(int nNum)
- int main()
-
- for(int nI 0 nI lt 20nI)
- coutltltFibonacci(nI)ltlt", "
- system("PAUSE")
- return 0
-
- int Fibonacci(int nNum)
-
- if(nNum 0)
- return 0
- else if(nNum 1)
- return 1
- else
- return Fibonacci(nNum-1)
Fibonacci(nNum-2)
153Recursive Functions
- A Recursive Function is a Function that calls
itself - int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
154Recursive Functions
- A Recursive Function is a Function that calls
itself - int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
Recursion
155Recursive Functions
- What would be returned by the call Mystery(0)?
- int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
0
0
156Recursive Functions
- What would be returned by the call Mystery(1)?
- int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
1
1
157Recursive Functions
- Mystery(1) 2 Mystery(0) 20
- int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
1
1
158Recursive Functions
- What would be returned by the call Mystery(2)?
- int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
2
2
159Recursive Functions
- Mystery(2) 2 Mystery(1)
- 2 2 Mystery(0) 2 2 0
- int Mystery(int nNum)
-
- if(nNum 0)
- return 0
- else
- return 2 Mystery(nNum - 1)
-
2
2
160Recursive Functions
- What would be returned by the call Mystery(10)?
161Recursive Functions
- What would be returned by the call Mystery(10)?
- Mystery(10) 2 Mystery(9)
- 22Mystery(8)
- 222Mystery(7)
- 2222Mystery(6)
- 22222Mystery(5)
- 222222Mystery(4)
- 2222222Mystery(3)
- 22222222Mystery(2)
- 222222222Mystery(1)
- 2222222222Mystery(0)20
162Recursive Functions
- Let's remove some code from Mystery
- Now what would be returned by the call
Mystery(10)? - int Mystery(int nNum)
-
- if(nNum 0) //delete 3 lines
- return 0
- else
- return 2 Mystery(nNum - 1)
-
163Recursive Functions
- Mystery(10) 2 Mystery(9)
- 22Mystery(8)
- 222Mystery(7)
- 2222Mystery(6)
- 22222Mystery(5)
- 222222Mystery(4)
- 2222222Mystery(3)
- 22222222Mystery(2)
- 222222222Mystery(1)
- 2222222222Mystery(0)
- 22222222222Mystery(-1)
- 222222222222Mystery(-2)
- and so on, and so on
- Infinite Recursion! Stack Overflow!
- CRASH!
164The Base Case
- Every recursive Function must have a base case
- The base case is where the recursion stops
- int Mystery(int nNum)
-
- if(nNum 0) //base case
- return 0
- else
- return 2 Mystery(nNum - 1)
165More on break and continue
- break and continue can be used to modify a loop
- break immediately exits a loop
- continue is somewhat the opposite, it "goes back
to the top" of the loop, skipping any remaining
code - Good Style whenever possible, avoid break and
continue, as they make code hard to understand
166break
- for(int nI 1 nI lt 100 nI )
-
- coutltlt"nI is "ltlt nIltltendl
- if(nI 3)
- break
- coutltlt"Bottom of block"ltltendl
-
- coutltlt"Finished"ltltendl
- / Sample Output
- nI is 1
- Bottom of block
- nI is 2
- Bottom of block
- nI is 3
- Finished
- Press any key to continue . . . /
167continue
- for(int nI 1 nI lt 3 nI )
-
- coutltlt"nI is "ltlt nIltltendl
- if(nI 2)
- continue
- coutltlt"Bottom of block"ltltendl
-
- coutltlt"Finished"ltltendl
- / Sample Output
- nI is 1
- Bottom of block
- nI is 2
- nI is 3
- Bottom of block
- Finished
- Press any key to continue . . ./
168What is the output?
- int main()
-
- for(int nI 1 nI lt 10 nI )
-
- coutltlt"nI is "ltlt nIltltendl
- if(nI 2)
- continue
- else if (nI 4)
- break
- coutltlt"Bottom of block"ltltendl
-
- coutltlt"Finished"ltltendl
- system("PAUSE")
- return 0