chapter 2 c++ syntax & semantics #include using namespace std; int main() { cout

59
CHAPTER 2 C++ SYNTAX & SEMANTICS

Upload: edwin-mckenzie

Post on 17-Jan-2016

239 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

CHAPTER 2

C++ SYNTAX &

SEMANTICS

Page 2: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

#include <iostream>using namespace std;

int main() {

cout << “Hello World!!”;

return 0;}

See \cp1\cpp\skeleton.cpp

C++ Hello World Program

Page 3: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Syntax vs. Semantics Syntax

language rules how valid instructions are written in a

programming language

GRAMMAR

English

Page 4: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Semantics rules determining MEANING of instructions in programming language

Page 5: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Identifiers

Page 6: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is an identifier?

A name associated with a process or object

used to refer to that process or object

John, Sue, Larry mass, volume, pay

Page 7: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What are rules for valid identifiers?

Identifiers are made of letters digits underscore

The first character must be a letter underscore

Page 8: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

VALID IDENTIFIERS sum_of_squares J9 GetData box_22A count Bin3D4

INVALID 40Hours Get Data Box-22 cost_in_$ int return

RESERVED WORDS word that has special meaning in C++ cannot be used as identifier (if)

Page 9: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Why is it important to use meaningful identifier names? Easier to understand Self documenting

Compare

printtopportionPRINTTOPPORTIONPrintTopPortion

Last is best

Page 10: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Case Sensitive C++ identifiers with different

capitalization are entirely distinct.

Total total

Two different identifiers.

Page 11: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Data Types

Page 12: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a data type?

A specific set of data valueswith operations on those values

C++ has a number of built-in data types.

Page 13: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 14: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

C++ Simple Data TypesC++ Simple Data Types

simple types

integral floating

char short int long bool enum float double long double

unsigned

Page 15: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Standard Data Types in C++

Integral Types represent whole numbers and their negatives declared as int, short, or long

Floating Types represent real numbers with a decimal point declared as float, or double

Character Types represent single characters declared as char

Page 16: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Integral Constants Positive or negative whole numbers 22 16 1 498 0 4600 -378 -912

Commas are NOT allowed

Value ranges char -128 to +127 short -32,768 to +32,767 int +/-2,147,483,648 long +/-2,147,483,648

Page 17: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

char One alphanumeric character letter, number, special symbol 'A' 'q' '8' '@'

A number is actually stored (ASCII code)

Page 18: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Unsigned Integral Types You may prepend "unsigned” before any

integral type

Value ranges unsigned char 0 to 256 unsigned short 0 to 65535 unsigned int 0 to

4,294,967,295 unsigned long 0 to 4,294,967,295

Page 19: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Floating integer and fraction scientific notation

18.0 127.54 0.57 4. .8 1.7536E-12 -3.652442E4 72E0

Types float double (double precision) long double(more significant digits)

Page 20: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Sample Program//****************************************************************// FreezeBoil program// This program computes the midpoint between// the freezing and boiling points of water//****************************************************************#include <iostream.h>

int main(){

const float FREEZE_PT = 32.0; // Freezing point of waterconst float BOIL_PT = 212.0; // Boiling point of waterfloat avgTemp; // Holds the result of averaging

// FREEZE_PT and BOIL_PT

cout << "Water freezes at " << FREEZE_PT << endl;cout << " and boils at " << BOIL_PT << " degrees." << endl;

avgTemp = FREEZE_PT + BOIL_PT;avgTemp = avgTemp / 2.0;

cout << "Halfway between is ";cout << avgTemp << " degrees." << endl;

return 0;}

Page 21: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Variable Declarations

Page 22: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a declaration? Associating identifier with

data object function data type

So programmer can refer to that item by name (naming object)

Page 23: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a variable? A location in

memory referenced by an

identifier

in which a data value is stored value can change

Page 24: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Example Declarations DataType Identifier [, Identifier, …]; int empNum;

int studentCount, maxScore, sumOfScores; or better

int studentCount; // Description int maxScore; // Description 2 int sumOfScores; // etc.

best, declare when needed

Page 25: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What Does a Variable Declaration Do?

Tells the compiler to • allocate enough memory to hold value of this type• associate the identifier with this location.

int ageOfDog;float taxRateY2K;char middleInitial;

4 bytes for taxRateY2K 1 byte for middleInitial

Page 26: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

When to Declare? Declare vars when needed NOT at top of the main block

Page 27: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Assignment Statements

Page 28: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is an assignment statement?

A statement gives the value of an expression to a variable.

Page 29: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Valid Assignment Statements Variable = Expression;

int num; int alpha; double rate; char ch;

alpha = 2856; rate = 0.36; ch = ‘B’; num = alpha;

Page 30: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Valid Expressions constant variable constant and/or variables combined

with operators

Examples alpha + 2 rate - 6.0 4 - alpha rate alpha * num 12

Page 31: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Unary and Binary Operators Unary Operator

an operator that has just one operand + -

Binary Operator an operator that has two operands + - * / %

Page 32: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Division Floating point division

when two real float values are divided the result is a float 5.0 / 3.0 = 1.66666

Integer division when two integer values are divided the result is an integer 5 / 3 = 1

Page 33: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Modulo Arithmetic (%) % operator

yields remainder of integer division

5 % 3 = 2 9 % 4 = 1 8 % 2 = 0 3 % 5 = 3

Page 34: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

3 + 6 = ? 9 3.4 - 6.1 = ? -2.7 2 * 3 = ? 6 8 / 2 = ? 4 8.0 / 2.0 = ? 4.0 8 / 8 = ? 1

Page 35: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

8 / 9 = ? 0 8 / 7 = ? 1 8 % 8 = ? 0 8 % 9 = ? 8 8 % 7 = ? 1 0 % 7 = ? 0

Page 36: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Valid Assignment Statements Variable = Expression;

int num = i; int alpha = j;

alpha = num + 6; alpha = num / 2; num = alpha * 2; num = 6 % alpha;

Page 37: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Named Constants

Page 38: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a literal value? Any constant value written in a

program.

Integers, real numbers, characters, strings of characters:

34 921.2196 'D' "Hi There”

Page 39: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a named constant? A location in memory

referenced by an identifier

in which a data value is stored value cannot change

const DataType Identifier = LiteralValue;

Page 40: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

const char BLANK = ' ';

const float INTEREST_RATE = 0.12;

const int MAX = 20;

const float PI = 3.14159;

Page 41: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Named constants make program more readable documents expressions program easier to modify

Change tax rates in a program only once.

Page 42: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Output

Page 43: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

How do you output data? cout << "Hello”;

cout special variable representing std output an output stream

<< insertion operator direction from string to output stream

Page 44: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Items are separated by << literals are in quotes, variable names or expressions allowed.

cout << ExprOrString << ExprOrString …;

Page 45: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Examples: int x; double y; char z;

x = 1; y = 2.3; z = ‘A’; cout << "x ="; cout << x << "y =" << y << "z =" << z; cout << "***";

Output: x =1y =2.3z =A***

Insert white spaces in the output where needed!

Page 46: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

x = 1; y = 2.3; z = ‘A’;

cout << "x = ";

cout << x << " y = " << y << " z = "

<< z;

cout << " ***";

Output:

x = 1 y = 2.3 z = A ***

Page 47: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

x = 1; y = 2.3; z = ‘A’; cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl;

Output:

x = 1

y = 2.3

z = A

x = -12345; y = 1.23456789; z = ‘B’; cout << x << " " << y << " " << z;

Output:

-12345 1.23457 B

Page 48: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

The assignment statement is not an equality. Var = Expr;

The assignment statement takes the value of the expression and assigns it to the variable. It does NOT determine if the values are

equal.

Page 49: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Assignment Statement not equality

alpha = alpha + 1; --Legal assignment, not equality

num = num + alpha;

Page 50: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Increment and Decrement ++ --

num++; ++num; ===> num = num + 1;

num--; --num; ===> num = num - 1;

Use as standalone statements.

Page 51: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Strings

Page 52: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

C++ Data Type String

a string is a sequence of characters enclosed in double quotes

string sample values

“Hello” “Year 2000” “1234”

the empty string (null string) contains no characters and is written as “”

Page 53: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

More About Type String

string is not a built-in (standard) type it is a programmer-defined data type it is provided in the C++ standard library #include <string>

string operations include comparing 2 string values searching a string for a particular character joining one string to another

Page 54: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

String Concatenation (+)

concatenation is a binary operation that uses the + operator

at least one of the operands must be a string variable or named constant--the other operand can be string type or char type

Page 55: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

Concatenation Example

const string WHEN = “Tomorrow” ;

const char EXCLAMATION = ‘!’ ;

string message1 ;

string message2 ;

message1 = “Yesterday “ ;

message2 = “and “ ;

message1 = message1 + message2 +

WHEN + EXCLAMATION ;

Page 56: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

How does one add comments to a program?

Comments giving explanatory notes

They may appear anywhere in a program.

/* */ around text. // Comment the rest of a line

It is good programming style to add descriptive comments to your program.

Paste document.cpp to top of program

Page 57: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

What is a block (compound statement)? Group of statements enclosed in { } separated by semicolons

Used anywhere a statement is used

{stmt 1;

stmt 2;

:

stmt n;

}

Page 58: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout

C++ Preprocessor #include <iostream>

Preprocessor handles include

iostream.h file is inserted into source iostream defines

cout endl <<

Page 59: CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout