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

Preview:

Citation preview

CHAPTER 2

C++ SYNTAX &

SEMANTICS

#include <iostream>using namespace std;

int main() {

cout << “Hello World!!”;

return 0;}

See \cp1\cpp\skeleton.cpp

C++ Hello World Program

Syntax vs. Semantics Syntax

language rules how valid instructions are written in a

programming language

GRAMMAR

English

Semantics rules determining MEANING of instructions in programming language

Identifiers

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

What are rules for valid identifiers?

Identifiers are made of letters digits underscore

The first character must be a letter underscore

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)

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

Compare

printtopportionPRINTTOPPORTIONPrintTopPortion

Last is best

Case Sensitive C++ identifiers with different

capitalization are entirely distinct.

Total total

Two different identifiers.

Data Types

What is a data type?

A specific set of data valueswith operations on those values

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

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

C++ Simple Data TypesC++ Simple Data Types

simple types

integral floating

char short int long bool enum float double long double

unsigned

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

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

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

A number is actually stored (ASCII code)

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

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)

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;}

Variable Declarations

What is a declaration? Associating identifier with

data object function data type

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

What is a variable? A location in

memory referenced by an

identifier

in which a data value is stored value can change

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

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

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

Assignment Statements

What is an assignment statement?

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

Valid Assignment Statements Variable = Expression;

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

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

Valid Expressions constant variable constant and/or variables combined

with operators

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

Unary and Binary Operators Unary Operator

an operator that has just one operand + -

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

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

Modulo Arithmetic (%) % operator

yields remainder of integer division

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

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

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

Valid Assignment Statements Variable = Expression;

int num = i; int alpha = j;

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

Named Constants

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”

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;

const char BLANK = ' ';

const float INTEREST_RATE = 0.12;

const int MAX = 20;

const float PI = 3.14159;

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

Change tax rates in a program only once.

Output

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

cout special variable representing std output an output stream

<< insertion operator direction from string to output stream

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

cout << ExprOrString << ExprOrString …;

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!

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

cout << "x = ";

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

<< z;

cout << " ***";

Output:

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

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

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.

Assignment Statement not equality

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

num = num + alpha;

Increment and Decrement ++ --

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

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

Use as standalone statements.

Strings

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 “”

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

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

Concatenation Example

const string WHEN = “Tomorrow” ;

const char EXCLAMATION = ‘!’ ;

string message1 ;

string message2 ;

message1 = “Yesterday “ ;

message2 = “and “ ;

message1 = message1 + message2 +

WHEN + EXCLAMATION ;

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

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;

}

C++ Preprocessor #include <iostream>

Preprocessor handles include

iostream.h file is inserted into source iostream defines

cout endl <<