240 likes | 351 Views
01/28/11. Basic Elements of a C ++ Program. Quiz 1. Monday Chapter 1, Linux and vim On your own p. 24 #1-8, 13, 14, 16 odd answers in text Define Memory address Memory contents Machine language. Objectives. State the basic parts of a C++ program. Create legal C++ names.
E N D
01/28/11 Basic Elements of a C ++ Program
Quiz 1 • Monday • Chapter 1, Linux and vim • On your own • p. 24 #1-8, 13, 14, 16 • odd answers in text • Define • Memory address • Memory contents • Machine language
Objectives • State the basic parts of a C++ program. • Create legal C++ names. • Write statements to output strings.
A Sample C++ Program • travel.cpp
A Sample C++ Program #include <iostream> • Preprocessor directive • Must have to do input/output • cout, cin, <<, >> using namespace std; • Required • Used to prevent name conflicts in large projects
travel.cpp int main() • Beginning of first function executed • Only one main • Must be in every program { } • Brackets delimit executable statements
travel.cpp double dist, time, speed; • Declare variables • Set aside locations in memory • Gives the locations names • double tells the data's type
travel.cpp cout<< "Miles traveled?"; cin >>dist; //input • cout puts message on monitor • cin inputs data and stores it in variable, dist. • // begins a comment
travel.cpp speed = dist/time; //find speed • Assignment Statement • speed gets dist/time • Does computation, stores answer in "speed"
travel.cpp cout << speed << " mph\n"; • Outputs result to monitor • \n is newline character return 0; • Ends program
Names • Examples: • rate, time, distance • R2D2, k9, K9, _acceration_gravity • Contain letters, digits, underscore • Start with letter or underscore
Names • Are these legal? Yr2007, 10_year_average, Y2K, form-99, M_PI
Keywords • Names C++ reserves • Cannot as use variable names. • E.G. double, return, namespace • See appendix F
Output • Example -- out.cpp • cout • Console output • Output stream • destination for stream of characters • Goes to standard output, usually monitor screen
Output • << • insertion operator • inserts characters in output stream • String • "September 7th is" • inserted into stream
Output cout << “Fire”; //Leaves cursor after “e” cout << “fighter”; Output : Firefighter
Output cout << “Fire\n”; //Cursor on new line cout << “fighter”; Output : Fire fighter • \n is an escape sequence
Output • Program out1.cpp • several \n's
Output • endl • stream manipulator function. • Another way to output a newline character. • out2.cpp
Next • Algorithms • Data Types 2.4 • Input 2.3