chapter 2 c++ syntax and semantics, and the program...

30
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems

Upload: hanga

Post on 07-Jul-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

1

Chapter 2

C++ Syntax and

Semantics, and the

Program

Development

Process

Dale/Weems

Page 2: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 3: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

3

Shortest C++ Program

int main( )

{

return 0;

}

type of returned value name of functionparameters

Page 4: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 5: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 6: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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:

Page 7: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

Page 8: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

Page 9: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

Page 10: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 11: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

}

Page 12: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

12

Output of Program

Name in first-last format is

Herman Smith

Name in last-first-initial format is

Smith, Herman G.

Page 13: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 14: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 15: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 16: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 17: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 18: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 19: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 20: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

20

Algorithm

Repeat four times

Output five whiteRows

Output five blackRows

Page 21: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 22: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

Page 23: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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;

}

Page 24: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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.

Page 25: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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”

Page 26: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 27: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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)

Page 28: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

Page 29: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

}

Page 30: Chapter 2 C++ Syntax and Semantics, and the Program ...courses.cs.vt.edu/~cs1044/spring09/Lectures/Lec4-Ch 02.pdfSemantics, and the Program Development Process Dale/Weems 2 Chapter

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

}