Download presentation
Presentation is loading. Please wait.
Published byEdwin McKenzie Modified over 9 years ago
2
CHAPTER 2 C++ SYNTAX & SEMANTICS
3
#include using namespace std; int main() { cout << “Hello World!!”; return 0; } See \cp1\cpp\skeleton.cpp C++ Hello World Program
4
Syntax vs. Semantics n Syntax n language rules n how valid instructions are written in a programming language n GRAMMAR English
5
n Semantics n rules determining MEANING of instructions in programming language
6
Identifiers
7
What is an identifier? n A name associated with a process or object used to refer to that process or object n John, Sue, Larry n mass, volume, pay
8
What are rules for valid identifiers? n Identifiers are made of n letters n digits n underscore n The first character must be a n letter n underscore
9
n VALID IDENTIFIERS n sum_of_squaresJ9GetData n box_22AcountBin3D4 n INVALID n 40HoursGet DataBox-22 n cost_in_$intreturn n RESERVED WORDS n word that has special meaning in C++ n cannot be used as identifier (if)
10
Why is it important to use meaningful identifier names? n Easier to understand n Self documenting n Compare printtopportion PRINTTOPPORTION PrintTopPortion n Last is best
11
Case Sensitive n C++ identifiers with different capitalization are entirely distinct. n Total total n Two different identifiers.
12
Data Types
13
What is a data type? n A specific set of data values with operations on those values n C++ has a number of built-in data types.
14
C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
15
C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned
16
Standard Data Types in C++ n Integral Types n represent whole numbers and their negatives n declared as int, short, or long n Floating Types n represent real numbers with a decimal point n declared as float, or double n Character Types n represent single characters n declared as char
17
n Integral Constants n Positive or negative whole numbers n 2216149804600 n -378-912 n Commas are NOT allowed n Value ranges n char-128 to +127 n short-32,768 to +32,767 n int +/-2,147,483,648 n long+/-2,147,483,648
18
n char n One alphanumeric character n letter, number, special symbol n 'A' 'q' '8' '@' n A number is actually stored (ASCII code)
19
Unsigned Integral Types n You may prepend "unsigned” before any integral type n Value ranges n unsigned char0 to 256 n unsigned short0 to 65535 n unsigned int0 to 4,294,967,295 unsigned long0 to 4,294,967,295
20
n Floating n integer and fraction n scientific notation n 18.0 127.54 0.574..8 n 1.7536E-12 -3.652442E4 72E0 n Types n float n double(double precision) n long double(more significant digits)
21
Sample Program //**************************************************************** // FreezeBoil program // This program computes the midpoint between // the freezing and boiling points of water //**************************************************************** #include int main() { const float FREEZE_PT = 32.0; // Freezing point of water const float BOIL_PT = 212.0; // Boiling point of water float 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; }
22
Variable Declarations
23
What is a declaration? n Associating identifier with n data object n function n data type n So programmer n can refer to that item n by name (naming object)
24
What is a variable? n A location in memory n referenced by an identifier n in which a data value is stored n value can change
25
Example Declarations n DataType Identifier [, Identifier, …]; n int empNum; int studentCount, maxScore, sumOfScores ; n or better n int studentCount;// Description n int maxScore; // Description 2 n int sumOfScores;// etc. n best, declare when needed
26
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 taxRateY2K1 byte for middleInitial
27
When to Declare? n Declare vars when needed n NOT at top of the main block
28
Assignment Statements
29
What is an assignment statement? n A statement n gives the value of an expression n to a variable.
30
Valid Assignment Statements n Variable = Expression; n int num;int alpha; n double rate;char ch; n alpha = 2856; n rate = 0.36; n ch = ‘B’; n num = alpha;
31
Valid Expressions n constantvariable n constant and/or variables combined with operators n Examples n alpha + 2rate - 6.0 n 4 - alpharate n alpha * num12
32
Unary and Binary Operators n Unary Operator n an operator that has just one operand n +- n Binary Operator n an operator that has two operands n +-*/%
33
Division n Floating point division n when two real float values are divided n the result is a float n 5.0 / 3.0 = 1.66666 n Integer division n when two integer values are divided n the result is an integer n 5 / 3 = 1
34
Modulo Arithmetic (%) n % operator n yields remainder of integer division n 5 % 3 = 2 n 9 % 4 = 1 n 8 % 2 = 0 n 3 % 5 = 3
35
n 3 + 6 = ? n 9n 9 n 3.4 - 6.1 = ? n -2.7 n 2 * 3 = ? n 6n 6 n 8 / 2 = ? n 4n 4 n 8.0 / 2.0 = ? n 4.0 n 8 / 8 = ? n1n1
36
n 8 / 9 = ? n0n0 n 8 / 7 = ? n1n1 n 8 % 8 = ? n0n0 n 8 % 9 = ? n8n8 n 8 % 7 = ? n1n1 n 0 % 7 = ? n0n0
37
Valid Assignment Statements n Variable = Expression; n int num = i; int alpha = j; n alpha = num + 6; n alpha = num / 2; n num = alpha * 2; n num = 6 % alpha;
38
Named Constants
39
What is a literal value? n Any constant value written in a program. n Integers, real numbers, characters, strings of characters: n 34921.2196 n 'D'"Hi There”
40
What is a named constant? n A location in memory n referenced by an identifier n in which a data value is stored n value cannot change n const DataType Identifier = LiteralValue;
41
n const char BLANK = ' '; n const float INTEREST_RATE = 0.12; n const int MAX = 20; n const float PI = 3.14159;
42
n Named constants n make program more readable n documents expressions n program easier to modify n Change tax rates in a program only once.
43
Output
44
How do you output data? n cout << "Hello”; n cout n special variable representing std output n an output stream n << n insertion operator n direction from string to output stream
45
n Items are separated by << n literals are in quotes, n variable names or expressions allowed. n cout << ExprOrString << ExprOrString …;
46
n Examples: n int x; double y; char z; n x = 1; y = 2.3; z = ‘A’; n cout << "x ="; n cout << x << "y =" << y << "z =" << z; n cout << "***"; n Output: n x =1y =2.3z =A*** n Insert white spaces in the output where needed!
47
x = 1; y = 2.3; z = ‘A’; cout << "x = "; cout << x << " y = " << y << " z = " << z; cout << " ***"; Output: x = 1 y = 2.3 z = A ***
48
n x = 1; y = 2.3; z = ‘A’; n cout << "x = " << x << endl << "y = " << y n << endl << "z = " << z << endl; Output: x = 1 y = 2.3 z = A n x = -12345; y = 1.23456789; z = ‘B’; n cout << x << " " << y << " " << z; n Output: -12345 1.23457 B
49
The assignment statement is not an equality. n Var = Expr; n The assignment statement n takes the value of the expression n and assigns it to the variable. n It does NOT determine if the values are equal.
50
Assignment Statement not equality n alpha = alpha + 1; n --Legal assignment, not equality n num = num + alpha;
51
Increment and Decrement n ++-- n num++; n ++num;===> num = num + 1; n num--; n --num;===> num = num - 1; n Use as standalone statements.
52
Strings
53
C++ Data Type String n a string is a sequence of characters enclosed in double quotes n string sample values “Hello” “Year 2000” “1234” the empty string (null string) contains no characters and is written as “”
54
More About Type String n string is not a built-in (standard) type n it is a programmer-defined data type n it is provided in the C++ standard library n #include n string operations include n comparing 2 string values n searching a string for a particular character n joining one string to another
55
String Concatenation (+) n concatenation is a binary operation that uses the + operator n at least one of the operands must be a string variable or named constant--the other operand can be string type or char type
56
Concatenation Example const string WHEN = “Tomorrow” ; const char EXCLAMATION = ‘!’ ; string message1 ; string message2 ; message1 = “Yesterday “ ; message2 = “and “ ; message1 = message1 + message2 + WHEN + EXCLAMATION ;
57
How does one add comments to a program? n Comments giving explanatory notes n They may appear anywhere in a program. n /* */ around text. n // Comment the rest of a line n It is good programming style to add descriptive comments to your program. n Paste document.cpp to top of program
58
What is a block (compound statement)? n Group of statements enclosed in { } n separated by semicolons n Used anywhere a statement is used { stmt 1; stmt 2; : stmt n; }
59
C++ Preprocessor n #include n Preprocessor handles include n iostream.h file is inserted into source n iostream defines n cout n endl n <<
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.