chapter 2 c++ syntax and semantics, and the program...
TRANSCRIPT
1
Chapter 2
C++ Syntax and
Semantics, and the
Program
Development
Process
Dale/Weems
2
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
3
Shortest C++ Program
int main( )
{
return 0;
}
type of returned value name of functionparameters
4
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
5
What Does a
Variable Declaration Do?
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
int ageOfDog;
float taxRate;
char middleInitial;
4 bytes for taxRateY2K 1 byte for
middleInitial
6
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.
int Weight = 0,
Height = 0,
Length = 0;
double ClassAverage = 0.0, GPA = 0.0;
string Major;
Major = "Computer Science";
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:
7
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;
8
Giving a Value to a VariableAssign(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;
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.
9
int quizScore; // score on a quiz
int numQuizzes = 0; // number of quizzes given
int totalPoints; // sum of all quiz scores
double quizAverage; // 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;
10
// ******************************************************
// PrintName program
// This program prints a name in two different formats
// ******************************************************
#include <iostream> // for cout and endl
#include <string> // 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‟;
C++ Program
11
C++ Code Continuedint 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;
}
12
Output of Program
Name in first-last format is
Herman Smith
Name in last-first-initial format is
Smith, Herman G.
13
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 compiletime).
- Compiler cannot correct error.
- Compiler prints error messages, but usuallycontinues to compile.
14
Categories of Programming Errors
Linking errors:
- Error is typically in the form of the declarationor implementation or call of a function.
- Error may also result from including thewrong header file.
- Error is detected by the linker (after thecompiler has produced an object file).
- Linker cannot correct error, so no executablefile is generated.
15
Categories of Programming Errors Execution (runtime) errors:
- Error occurs while the program is running, causingthe 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 amemory address that is not allocated to it.
- Code compiles and links without errors.
- Unfortunately, some operating systems do not reliablydetect and respond to some kinds of execution errors.In that case, an incorrect program may appear tofunction correctly on one computer but not onanother.
16
Categories of Programming Errors Logic errors:
- Error occurs while the program is running, causingthe production of incorrect results, but notnecessarily a runtime "crash".
- Program source code compiles and links withouterrors – no help there.
- Logic errors are detected by checking resultscomputed by the program.
- The cause(s) of the error must be determined by alogical analysis of the error and the source code.This must be done by the developer. This is thehardest type of error to deal with.
17
Analyze the problem statement
Design a solution
Enter/edit source code
Compile/link source code
Compiler/Linker errors?
Test the program
Results incorrect?
Execution errors?
Find error in source code
check syntax
Find cause of runtime error
check code
check input data
rethink analysis/design
Find cause of logic error
check code
check input data
rethink analysis/design
Success!
At least with this input.
yesno
no
no
yes
yes
or
or
18
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.
19
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
20
Algorithm
Repeat four times
Output five whiteRows
Output five blackRows
21
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
22
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;
23
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;
}
24
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.
25
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”
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
27
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)
28
//******************************************************
// 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; // Access cout, endl, cin
bool IsLeapYear(int); // Prototype for subalgorithm
int main()
C++ Program
29
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
}
30
IsLeapYearbool 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
}