Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems 1
Chapter 2 Topics Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation Output Statements C++ Program Comments 2
Shortest C++ Program type of returned value name of function parameters int main( ) { return 0; } 3
Directives Directives provide instructions to the pre-processor, which "edits" your C++ language code before it is read by the C++ compiler. Directives are most commonly used to incorporate standard header files into your program: #include <iostream> // embed the file "iostream" here Directives may also be used to declare identifiers: #define NUMBER 100 // replace every occurrence of NUMBER // with the value 100 4
What Does a Variable Declaration Do? int ageofdog; float taxrate; char middleinitial; A declaration tells the compiler to allocate enough memory to hold a value of this data type and to associate the identifier with this location 4 bytes for taxratey2k 1 byte for middleinitial 5
Initialization Declaring a variable does not (usually) automatically provide it with a specific starting value. A variable is just a name for a location in the computer's memory. Memory cannot be "empty", it always stores some value. For all practical purposes, the variable declarations on the previous slide create variables whose initial values are random garbage, whatever happens to be at the corresponding location in memory when the program is executed. Using the value of a variable that has not yet been properly set is one of the most common sources of errors in programs. Therefore, it is good practice to always give every newly declared variable a specific initial value. This can be combined with the declaration or accomplished via a later assignment: int Weight = 0, Height = 0, Length = 0; double ClassAverage = 0.0, GPA = 0.0; string Major; 6 Major = "Computer Science";
What is a Named Constant? A named constant is a location in memory that can be referred to by an identifier and in which a data value that cannot be changed is stored Valid constant declarations const string STARS = **** ; const float NORMAL_TEMP = 98.6; const char BLANK = ; const int VOTING_AGE = 18; const float MAX_HOURS = 40.0; 7
Giving a Value to a Variable Assign(give)a value to a variable by using the assignment operator = Variable declarations string firstname; char middleinitial; char letter; int ageofdog; Valid assignment statements firstname = Fido ; middleinitial = X ; letter = middleinitial; ageofdog = 12; 8
Comments It is good practice to include descriptive comments in code. Comments may explain the purpose of a declared identifier, or of a statement or group of statements that perform some calculation, or input or output. int quizscore; int numquizzes = 0; int totalpoints; double quizaverage; // score on a quiz // number of quizzes given // sum of all quiz scores // average of all quiz scores /* Read in quiz scores until the user enters one that's negative. */ cin >> quizscore; while (quizscore >= 0) { totalpoints = totalpoints + quizscore; numquizzes = numquizzes + 1; cin >> quizscore; } // Calculate average quiz score: quizaverage = double(totalpoints) / numquizzes; 9
C++ Program // ****************************************************** // PrintName program // This program prints a name in two different formats // ****************************************************** #include <iostream> #include <string> // for cout and endl // for data type string using namespace std; // Declaring and Initializing Person s first name, last name, middle initial const string FIRST = "Herman"; const string LAST = "Smith"; const char MIDDLE = G ; 10
C++ Code Continued int main() { string firstlast; // Name in first-last format string lastfirst; // Name in last-first format firstlast = FIRST + + LAST; cout << "Name in first-last format is " << endl; cout << firstlast << endl; lastfirst = LAST + ", " + FIRST + " "; cout << "Name in first-last format is " << endl << lastfirst << MIDDLE <<. << endl; } return 0; 11
Output of Program Name in first-last format is Herman Smith Name in last-first-initial format is Smith, Herman G. 12
Categories of Programming Errors Language syntax (compilation) errors: - Error is in the form of the statement: misspelled word, unmatched parenthesis, comma out of place, etc. - Error is detected by the compiler (at compile time). - Compiler cannot correct error. - Compiler prints error messages, but usually continues to compile. 13
Categories of Programming Errors Linking errors: - Error is typically in the form of the declaration or implementation or call of a function. - Error may also result from including the wrong header file. - Error is detected by the linker (after the compiler has produced an object file). - Linker cannot correct error, so no executable file is generated. 14
Categories of Programming Errors Execution (runtime) errors: - Error occurs while the program is running, causing the program to "crash" (terminate abnormally. - Frequently an illegal operation of some sort. Arithmetic errors like an attempt to divide by zero, Access violations: try to use some resource like a memory address that is not allocated to it. - Code compiles and links without errors. - Unfortunately, some operating systems do not reliably detect and respond to some kinds of execution errors. In that case, an incorrect program may appear to function correctly on one computer but not on 15 another.
Categories of Programming Errors Logic errors: - Error occurs while the program is running, causing the production of incorrect results, but not necessarily a runtime "crash". - Program source code compiles and links without errors no help there. - Logic errors are detected by checking results computed by the program. - The cause(s) of the error must be determined by a logical analysis of the error and the source code. This must be done by the developer. This is the hardest type of error to deal with. 16
Analyze the problem statement Design a solution Enter/edit source code Find error in source code check syntax Compile/link source code Compiler/Linker errors? no yes Find cause of runtime error check code check input data rethink analysis/design or Test the program Execution errors? no Results incorrect? yes yes no Find cause of logic error check code check input data rethink analysis/design Success! At least with this input. or 17
Creating a Chessboard Problem Your college is hosting a chess tournament, and the people running the tournament want to record the final positions of the pieces in each game on a sheet of paper with a chessboard preprinted on it. Your job is to write a program to preprint these pieces of paper. The chessboard is an eight-by-eight pattern of squares that alternate between black and white, with the upper left square being white. You need to print out squares of light characters(spaces)and dark characters(such as *)in this pattern to form the chessboard. 18
Chessboard Constants NameValue Function BLACK '********' Characters forming one line of a black square WHITE ' ' Characters forming one line of a white square Variables Name Data Type Description whiterow string A row beginning with a white square blackrow string A row beginning with a black square 19
Algorithm Repeat four times Output five whiterows Output five blackrows 20
C++ Program //***************************************************** // Chessboard program // This program prints a chessboard pattern that is // built up from basic strings of white and black // characters. //***************************************************** #include <iostream> #include <string> using namespace std; const string BLACK = "********"; // Define black square line const string WHITE = " "; // Define white square line 21
C++ Program int main() { string whiterow; // White square beginning row string blackrow; // Black square beginning row // Create a white-black row whiterow = WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK; // Create a black-white row blackrow = BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE; 22
C++ Program } // Print five white-black rows cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; cout << whiterow << endl; // Print five black-white rows cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; cout << blackrow << endl; // Print rest of the rows... return 0; 23
Is a year a leap year? Problem You need to write a set of instructions that can be used to determine whether a year is a leap year. The instructions must be very clear because they are to be used by a class of fourth graders, who have just learned about multiplication and division. They plan to use the instructions as part of an assignment to determine whether any of their relatives were born in a leap year. 24
Leap Year Algorithm Prompt the user to enter a four-digit year Read the year If IsLeapYear Write Year is a leap year Otherwise Write Year is not a leap year 25
What is a Leap Year? Every year whose number is divisible by four without a remainder is a leap year Except the full centuries, which, to be leap years, must be divisible by 400 without a remainder. If not so divisible they are common years. 1900, therefore, is not a leap year 26
IsLeapYear Algorithm Divide the year by 4 If the remainder isn't zero, Return false(the year is not a leap year) Otherwise divide the year by 10 and If the remainder isn't 0, Return true(the year is a leap year) Otherwise, divide the year by 400 and If the remainder isn't 0 Return false(the year is not a leap year) Otherwise, Return true(the year is a leap year) 27
C++ Program //****************************************************** // LeapYear program // This program inputs a year and prints whether the year // is a leap year or not //****************************************************** #include <iostream> // Access output stream using namespace std; bool IsLeapYear(int); // Access cout, endl, cin // Prototype for subalgorithm int main() 28
Body of Main { } int year; // Year to be tested cout << "Enter a year AD, for example, 1997." << endl; // Prompt for input cin >> year; // Read year if(isleapyear(year)) // Test for leap year cout << year << " is a leap year." << endl; else cout << year << " is not a leap year." << endl; return 0; // Indicates successful // completion 29
IsLeapYear bool IsLeapYear(int year) // IsLeapYear returns true if year is a leap year and // false otherwise { if(year % 4!= 0) // Is year not divisible by 4? return false; // If so, can't be a leap year else if(year % 100!= 0) // Is year not a multiple of 100? return true; // If so, is a leap year else if(year % 400!= 0) // Is year not a multiple of 400? return false; // If so, then is not a leap year else return true; // Is a leap year } 30