more c++ and ubuntu linux review and practice 2 data structures and algorithms cs 244 brent m....
TRANSCRIPT
More C++ and Ubuntu LinuxReview and Practice 2
Data Structures and Algorithms
CS 244
Brent M. Dingle, Ph.D.
Department of Mathematics, Statistics, and Computer Science
University of Wisconsin – Stout
Based on the book: Data Structures and Algorithms in C++ (Goodrich, Tamassia, Mount)Some content derived/taken from: http://www.stroustrup.com/Programming/ and some from C++ Through Game Programming (Dawson)
From Last Time• Installed VMware Player and Ubuntu Linux
• First graded In-Class Assignment completed– Hello Game Over
• Reviewed basic programming idea– Related to C++
• If you missed the first classes you will want to speak with me after this one is over
Things to Note
• Homework– Homework 1 is due – SOON (tonight?)– Homework 2 should also be online– Quiz 1 is online– Do not delay working on these
Today’s Plan• More review of programming skills– Applying them to C++
• Continue with Game Stats 2.0– Modifying variable values in C++
• Examine Game Stats 3.0– Constants and enumerated types in C++– Includes an in-class activity quiz (not a quiz grade)
• Create a “game” called Lost Gold– intro to std::string in C++, plus some
• Some fun stuff with– C++’s comparison operators, branching, and looping
Repeat Class Activity – Game Stats 2.0• If you have not already done so…• In 5 to 10 minutes
• On D2L• Go to the Examples content• Download the file
– EX002_GS2example.tar.gz• In Ubuntu Linux place it in the folder
– Documents/ExamplePrograms• Extract, compile, and run the GS2 program
• This activity is very similar to the first GameStats activity
GS2 – What does it show?
• This program begin with comments
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• Includes the iostream file
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• Uses the namespace std– Recall:• this is so we don’t have to keep typing std::cout• recall std:: is like the area code for cout
– meaning cout is declared and defined in the file iostream and belongs to the namespace std
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• And the program has only one function– main() that returns an integer value
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• It declares and sets a local variable– score is an unsigned integer with value 5000
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• And it uses – the cout object – and the operator <<
• to output information to the screen
// GS2.cpp -- GameStats 2.0// Another example program// Demonstrates various ways to modify values of variables// and more on input and output
#include <iostream>using namespace std;
int main(){ unsigned int score = 5000; cout << "score: " << score << endl;
GS2 – What does it show?
• So what is new here?
// alter the value of a variable
score += 100; cout << "score: " << score << endl; // increment operators
int lives = 3; ++lives; cout << "lives: " << lives << endl; lives = 3; lives++; cout << "lives: " << lives << endl;
GS2 – What does it show?
• score += 100;– same as: score = score + 100;
• also have -= , *=, /=, and %=
// alter the value of a variable
score += 100; cout << "score: " << score << endl; // increment operators
int lives = 3; ++lives; cout << "lives: " << lives << endl; lives = 3; lives++; cout << "lives: " << lives << endl;
GS2 – What does it show?
• ++lives;– a PRE-incrementor– same as: lives = ( lives + 1 )– with guarantee that happens “first”
• before lives is used in any other calculation or comparison
// alter the value of a variable
score += 100; cout << "score: " << score << endl; // increment operators
int lives = 3; ++lives; cout << "lives: " << lives << endl; lives = 3; lives++; cout << "lives: " << lives << endl;
GS2 – What does it show?
• ++lives;– a POST-incrementor– same as: lives = ( lives + 1 )– with guarantee that happens “last”
• after lives is used in any other calculation or comparison
// alter the value of a variable
score += 100; cout << "score: " << score << endl; // increment operators
int lives = 3; ++lives; cout << "lives: " << lives << endl; lives = 3; lives++; cout << "lives: " << lives << endl;
GS2 – What does it show?
• ++lives * 10– lives is incremented FIRST– so bonus is set to 4 * 10
lives = 3; int bonus = ++lives * 10; cout << "lives, bonus = " << lives << ", " << bonus << endl; lives = 3; bonus = lives++ * 10; cout << "lives, bonus = " << lives << ", " << bonus << endl; // integer wrap around score = 4294967295;
GS2 – What does it show?
• lives++ * 10– lives is incremented LAST– so bonus is set to 3 * 10– and AFTER that lives is set to 4
lives = 3; int bonus = ++lives * 10; cout << "lives, bonus = " << lives << ", " << bonus << endl; lives = 3; bonus = lives++ * 10; cout << "lives, bonus = " << lives << ", " << bonus << endl; // integer wrap around score = 4294967295;
GS2 – What does it show?
• Shows score set to the maximum value for an unsigned integer
• Adding 1 to it will make it’s value “wrap around” and become 0– Caused early video game players frustration when their high score
suddenly went to zero
// integer wrap around score = 4294967295; cout << "\nscore: " << score << endl; ++score; cout << "\nscore: " << score << endl; return 0;}
Value Altering Operators – Summary
PRE-Incrementer: ++lives;
POST-Incrementer: lives++;
End GS2
• Next up is an examination of constants and enumerated types
• Any questions about – pre-incrementers – or post-incrementers – or value changing assignment operators• +=, -=, *=, /=, %=
Graded Class Activity – Game Stats 3.0• In Ubuntu Linux• Create a file
GS3.cppas shown to the right
• Compile it
• Run it
• When donetake the online in-class activity quiz about it on D2L
// GS3.cpp -- GameStats 3.0// Example to demonstrate the use of constants and enumerated types
#include <iostream>using namespace std;
int main(){ const int ALIEN_POINTS = 150; int aliensKilled = 10; int score = aliensKilled * ALIEN_POINTS; cout << "score: " << score << endl; enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE }; difficulty myDifficulty = NORMAL; cout << "myDifficulty = " << myDifficulty << endl; enum shipCost { FIGHTER_COST=25, BOMBER_COST, CRUISER_COST=50 }; shipCost myShipCost = BOMBER_COST; cout << "\nTo upgrade my ship to a Cruiser will cost " << (CRUISER_COST - myShipCost) << " Resource Points.\n";
return 0;}
Looking at GS 3.0
• Be sure you have taken the online IN-CLASS Activity Quiz before class ends today
• Now what does the program show us?
Constants• A constant is an unchangeable value that you give
a name.
– Useful if you have an unchanging value that shows up often in your program
– For example say the points for destroying an alien is always 150• Use a const int ALIEN_POINTS = 150;• Instead of writing 150 in a bunch of places
– This also makes it easier to change if you need to
GS3 Examination
• Example of using a a C++ constant
• Once set to a value, can use them like any other variable – except on the left hand side of an assignment– i.e. no changing the value of constants
• Notice they ARE set to a specific type of number
:int main(){ const int ALIEN_POINTS = 150; int aliensKilled = 10; int score = aliensKilled * ALIEN_POINTS; cout << "score: " << score << endl; enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
GS3 Examination
• C++ allows enumerated types to be used• Enumerated types are effectively
– a named set of integer constants
• If no values are specified the first constant is assigned the value 0– NOVICE == 0
• Unless specified otherwise– Each constant after the first has a value of +1 of the previous
• EASY = 1, NORMAL = 2, HARD = 3, UNBEATABLE = 4
enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE }; difficulty myDifficulty = NORMAL; cout << "myDifficulty = " << myDifficulty << endl; enum shipCost { FIGHTER_COST=25, BOMBER_COST, CRUISER_COST=50 }; :
GS3 Examination
• In this case FIGHTER is given the value of 25
enum shipCost { FIGHTER_COST=25, BOMBER_COST, CRUISER_COST=50 }; shipCost myShipCost = BOMBER_COST; cout << "\nTo upgrade my ship to a Cruiser will cost " << (CRUISER_COST - myShipCost) << " Resource Points.\n";
return 0;}
GS3 Examination
• In this case FIGHTER is given the value of 25• BOMBER_COST is thus 25 + 1 = 26
enum shipCost { FIGHTER_COST=25, BOMBER_COST, CRUISER_COST=50 }; shipCost myShipCost = BOMBER_COST; cout << "\nTo upgrade my ship to a Cruiser will cost " << (CRUISER_COST - myShipCost) << " Resource Points.\n";
return 0;}
GS3 Examination
• In this case FIGHTER is given the value of 25
• BOMBER_COST is thus 25 + 1 = 26
• and• CRUSIER_COST is specified to have a value of 50
enum shipCost { FIGHTER_COST=25, BOMBER_COST, CRUISER_COST=50 }; shipCost myShipCost = BOMBER_COST; cout << "\nTo upgrade my ship to a Cruiser will cost " << (CRUISER_COST - myShipCost) << " Resource Points.\n";
return 0;}
Constants – Summary Example• Constants improve the readability and modifiability
of a program– Typically constants are written as all upper case
• To declare a constant in C++ use constconst char SOME_CHAR = 'a';
const int MY_INTEGER = 1234;
const float YOUR_FLOAT = 54.89f;
const double MY_DOUBLE = 100.0;
const double USE_EXPONENTIAL = 2.345e8;
End GS3
• Next up is the creation of a very simple game• With a very brief introduction to std::string
• Any questions about – constants– or enumerated types
Quick String and Integer Input Example// Code segment to read name and age
int main(){ string firstName; // string variable
int age; // integer variable
cout << “Enter your first name and age\n"; cin >> firstName >> age; // read a string then an integer
cout << "Hello, " << firstName << " of age " << age << '\n';}
// Note: examples shown in class may leave out includes and using namespace // lines to save space and reduce clutter.// But you should not forget such things in real code.
std::string• std::string is a Standard Template Library class type
– as is cout and cin– to use it requires: #include <string>
• Not surprising it is useful for storing string data– This is an huge improvement of C’s arrays of characters
• A couple other STL classes are shown in the below tableType Description Literal Examples
string A string of characters "qwerty" "To market, to market"
complex Complex number, single or double precision
complex<double>(20.4, 12.9);complex<float>(23.4f);
vector Sequence containers representing arrays that can change in size
vector<double> scores(100);vector<char> buffer(500);
Group Class Activity – Lost Gold• Using 10 to 15 minutes
• Form into groups of 2 to 4 people
• Select a leader for controlling source code– On D2L in the In Class Examples locate the file EX004_LostGold.tar.gz– Decompress it and attempt to build it (compile and link)– Open it in gedit and attempt to fix it– When fixed and running (or time expires)
• submit the CPP file to the Group Activities: EX004 Lost Gold Folder on D2L
• Be certain ALL team member names are clearly indicated in the comments at the top of the file
End Lost Gold
• Next up are– Summary review of stuff so far– Moving onto• If statements and other conditional stuff• Some looping
• Any questions about – std::string• you will see more of it and other STL classes later
– or the Lost Gold Program and how it works
Good To Know• On D2L in the Content section under Presentations/Unit 1
– a Meta Info Summary section
• This Meta Info Section contains files that offer– an overview of various information that goes with all the code and activities
done so far– For Unit 1 they will be useful for the test (and maybe quizzes)
• Looking forward towards expectations– Be able to do the activities
• Application Stuff
– Be able to remember the Meta Info that goes with them• Theory Stuff
• Example of the Meta Info content follows
Summary of META-Stuff 1• A program is a series of
– C++ statements
• When creating a program its lifecycle is– idea– plan– source code– object file and executable
• Three Categories of Programming Errors– Through work so far probably saw all 3 types– compile errors– link errors– run time errors
Summary of META-Stuff 2
• A function is a– group of programming statements (code) that can• do some work and• return a value
• Every C++ program must contain the function– int main()– Which is the• entry (or starting) point of the program
Summary of META-Stuff 3• The #include tells the– preprocessor
• to• include another file in the current one
• The std namespace includes elements from– the standard (template) library– To access an element from the namespace you need to
prefix the element with• std::
– OR before the main function have the line• using namespace std;
Meta Talk• Go look at the files
• Comments in the slides like this likely identify where one meta file ends and another begins
• The Meta Info is NOT all inclusive– They are there to help summarize and organize info– They are not everything you need to know– They may offer “additional” info
• Usually covering/recalling small details of stuff that was (or should have been) said in passing
– See the slides, assignments, and book too
End Meta Talk
• Next up– Moving onto• If statements and other conditional stuff• Some looping
• Any questions about – Meta Info Files on D2L ?
Truth in C++• Recall type bool:
– bool fact = true, fiction = false;
– keyword true is true,– and keyword false is false – and that is simple
• However, Due to C++’s origins from Cany expression or value can be interpreted as true or false
• In C++– true is any NON-zero value– false is zero
Relational Operators• C++ relational operators are viewed as always evaluating to true or
false• Examples:
Logical Operators• C++ allows you to combine simple expression
using logical operators• These work as you would logically expect =)
If Statement• Works as expected– with options of
• else if• else
• Example Structure– if (expression)
• statement
– else if (expression 2)• statement 2
– else• statement 3
If Statement Examples
if (true){ cout << "This line is always printed\n";}
if (false){ cout << "This line is never printed\n";}
If Statement – Watch semi-colons
• The above code will print the line:This line is never printed
• Do you see why?
if (false) ;{ cout << "This line is never printed\n";}
If-Else Statement Examples
if (score >= 100){ cout << “You scored 100 or more. Well done! \n";}else{ cout << “You scored less than 100\n";}
Switch Statement• Tests if choice equals value1,
value2, … valueN– and executes the corresponding
statement
• When the program hits a break statement it exits the switch structure
• If choice does not match any of the values the statement following the default: is executed
• The use of break and default are optional
switch (choice){ case value1: stmt1; break; case value2: stmt2; break; : : case valueN: stmtN; break; default: stmtN+1;}
Class Activity – Menu Chooser• In 10 to 15 minutes
• On D2L• Go to the In Class Assignments/Examples content• Download the file– EX005_MenuChooser.tar.gz
• In Ubuntu Linux place it in the folder– Documents/ExamplePrograms
• Extract, compile, and run the program– Explore what it does
End Conditionals
• Next up– Moving onto• Looping
• Any questions about – Conditionals• If Statements• Switch Statements• Relational operators• Logical Operators
While Loops
• While loops allow the repetition of code as long as an expression is true
• Generic form– while (expression)• statement;
• If expression is false the program moves on to the statement after the loop
While Loop Example
• If time you (the student) may want to explore the program to the right
• It’s a simple example of a while loop
Do Loops
• do-loops are similar to while-loops – but a do-loop always executes at least one time
• structure:– do• statement
– while (expression)
Do Loop example
• If time you (the student) may want to explore the program to the right
• It’s a simple example of ado-loop
break and continue
• C++ does allow the use of break and continue in loops– Use the sparingly
and only when absolutely necessary– They disrupt loop flow• making it difficult to read and debug code
End Looping (for now)
• Next up– Random Numbers
• Any questions about – Looping• yes there are for-loops too
– we will get to them in the not so distant future
(Pseudo) Random Numbers• There are many reasons to want to use random
numbers
• The C standard library provides us the functions to do so– it requires the files
• cstdlib and ctime to be included
– using the functions• srand(), time(), and rand()
• Do you sense an activity coming?
In Class Activity – Die Roller• In 10 minutes or less
• Write up the program as shown to the right.
• Compile and run it• Observe the output
• Submit the CPP file (compressed or not) to the appropriate drop box on D2L– In Class Assignments– Die Roller
Die Roller – Items of Note
• srand seeds the random number generator– which is really a pseudo-random generator
• so it really works like a table look up
– the seed is the index to start pulling numbers from– To make it generate different numbers each time we
want to send it a different starting index each time• thus we use the time() function
Die Roller – Items of Note
• time(0) returns a number based on the current system date and time of the computer
• Thus most likely a different starting index each time the program is run
Die Roller – Items of Note
• static_cast<unsigned int>– forces the return value of time(0) to be treated as
an unsigned integer
Die Roller – Items of Note
• After seeding the generator• You can call rand() as many times as desired to
get a random integer value
Die Roller – Items of Note
• mod 6– reduces the number to be 0, 1, 2, 3, 4, or 5
Die Roller – Items of Note
• mod 6– reduces the number to be 0, 1, 2, 3, 4, or 5
• plus 1– gives moves each up 1,– so final result is a number from 1 to 6
End Random Numbers
• Next up– Game Loop (aka simulation loop)• or other infinite loop to process user actions
• Any questions about – Random Numbers
The “Game” Loop is More than Gaming• The “Game” loop actually shows up in a variety of applications
you may work on
• It also provides a context – to understand how to design a program system
• to wait for events, • process user input, • update the state of the program accordingly
– based on user input and other active program objects and rules
• output the updated state to the user
• Many Engineering Companies use this type of framework to perform large scale simulations
• The “game” loop is more than just for games
The Game Loop
• Setup– Initialize and load things– Provide Instructions/Background
to the user
The Game Loop
• Get Player Input– Keyboard, Mouse, Touch, etc
The Game Loop
• Update Game Internals– Update the STATE of the program– Update the STATE of the objects• Apply Physics or other rule systems
The Game Loop
• Update Display– Typically this is a graphical display
update– But not always, text works too– In essence it is outputting the
current state of the program• which was just updated in the
previous step
The Game Loop
• Game Over– Check for things such as:• Has the program state become such
that the program can no longer continue• i.e. player has lost (or won)• Has the user requested to quit the
program
The Game Loop
• Shutdown– Display final results of the program– Cycle down (turn off) any external
peripherals as needed– Perform memory clean up
Applying the Game Loop• Say you wanted to
create a game for guessing numbers.
– The planning flow chart might look something like that to the right
• Note it’s relationship to the Game Loop
Applying the Game Loop
• First you must setup (select) a random number
Applying the Game Loop
• NextGet input from the player
Applying the Game Loop
• Update the game state– increment the
number of guesses made so far
Applying the Game Loop
• Display the results of the guess
Applying the Game Loop
• Check if the game is over– if the player
guessed the number
Applying the Game Loop
• Perform final messages to the player and end the program gracefully
Number Guesser Code
• For those interested– Source code for the Number Guesser Game can be
found in D2L in the • In-Class Assignments/Example folder
End Game Loop• Any questions about – Game Loop
• (aka Simulation Loop)
• Any general questions?
• Next up– Free Play
• Open Time For Working on Homework• homework one or two• and/or finish out the in-class stuff
Free Play – Things to Work On
• Take the In-Class Activity Quiz online for GS3– ICA002
• Turn in the Lost Gold In-Class Group Activity– EX004
• Turn in the In-Class Activity Die Roller– ICA003
• Homework 1 – Money Change• Homework 2 – Best Guess
The End
• Or is it?