1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process
2 A C++ program is a collection of one or more functions l there must be a function called main( ) l execution always begins with the first statement in function main( ) l any other functions in your program are subprograms and are not executed until they are called
3 Shortest C++ Program int main ( ) { return 0; } type of returned value name of function
What is in a heading? int main ( ) type of returned value name of function says no parameters 4
Every C++ function has 2 parts int main ( ) heading { body block return 0; } 5
6 l a block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { Statement (optional). } Block (Compound Statement)
7 Program With Several Functions main function square function cube function
8 Program With Three Functions #include int Square( int ); // declares these two int Cube( int ); // value-returning functions using namespace std ; int main( ) { cout << “The square of 27 is “ << Square(27) << endl;// function call cout << “The cube of 27 is “ << Cube(27) << endl; // function call return 0; }
9 Rest of Program int Square( int n ) { return n * n; } int Cube( int n ) { return n * n * n; }
10 Functions l Functions are used to: l Organize your program and make it easier to understand (the CalcPay function in chapter 1) l Allow code to be called and executed multiple times (Square, Cube functions can be called many times as needed)
11 Functions l Functions are passed data: Square(27) 27 is passed l Functions can return data: The Square and Cube functions return the respective results l Functions must be defined before they are used
12 Output of program The square of 27 is 729 The cube of 27 is 19683
13 What is an Identifier? l An identifier is the name used for a data object (a variable or a constant), or for a function, in a C++ program. l C++ is a case-sensitive language. using meaningful identifiers is a good programming practice
14 Identifiers l an identifier must start with a letter or underscore, and be followed by zero or more letters (A-Z, a-z), digits (0-9), or underscores l VALID age_of_dogtaxRateY2K PrintHeading ageOfHorse NOT VALID (Why?) age# 2000TaxRate Age-Of-Cat
15 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
16 C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned
17 Standard Data Types in C++ l Integral Types n represent whole numbers and their negatives n declared as int, short, or long l Floating Types n represent real numbers with a decimal point n declared as float, or double l Character Types n represent single characters n declared as char
18 Samples of C++ Data Values int sample values float sample values char sample values ‘ B ’ ‘ d ’ ‘ 4 ’ ‘ ? ’‘ * ’
19 What is a Variable? l A variable is a location in memory which we can refer to by an identifier, and in which a data value that can be changed is stored. l declaring a variable means specifying both its name and its data type
20 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 taxRateY2K; char middleInitial ; 4 bytes for taxRateY2K And ageOfDog 1 byte for middleInitial
21 C++ Data Type String l a string is a sequence of characters enclosed in double quotes l string sample values “Hello” “Year 2000” “1234” the empty string (null string) contains no characters and is written as “”
22 More About Type String l 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 l string operations include n comparing 2 string values n searching a string for a particular character n joining one string to another
23 What is a Named Constant? l A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed is stored. l 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 ;
24 Constant Names l Constant names are usually capitalized l This is not required, but a very good idea that is an industry standard
25 Giving a Value to a Variable You can assign (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 ;
26 What is an Expression in C++? l An expression is a valid arrangement of variables, constants, and operators. l in C++ each expression can be evaluated to compute a value of a given type l the value of the expression is 14
Variable = Expression First, Expression on right is evaluated. Then the resulting value is stored in the memory location of Variable on left. Assignment Operator Syntax 27
28 Assignment l Assignment (=) is NOT the same as a mathematical equal operation l a = a+c; is legal (add the value of variable c to the current value of the variable a, and replace a with this)
29 String Concatenation (+) l concatenation is a binary operation that uses the + operator l at least one of the operands must be a string variable or named constant--the other operand can be string type or char type
30 Concatenation Example const string WHEN = “Tomorrow” ; const char EXCLAMATION = ‘!’ ; string message1 ; string message2 ; message1 = “Yesterday “ ; message2 = “and “ ; message1 = message1 + message2 + WHEN + EXCLAMATION ;
31 Insertion Operator ( << ) l variable cout is predefined to denote an output stream that goes to the standard output device (display screen) l the insertion operator << called “put to” takes 2 operands l the left operand is a stream expression, such as cout. The right operand is an expression of simple type or a string constant
32 Output Statements SYNTAX These examples yield the same output: cout << “The answer is “ ; cout << 3 * 4 ; cout << “The answer is “ << 3 * 4 ; cout << Expression << Expression... ;
33 Preporcessor Before your source program is compiled, it is first examined by the preprocessor to n remove all comments from source code n handle all preprocessor directives--they begin with the # character such as #include –tells preprocessor to look in the standard include directory for the header file called iostream and insert its contents into your source code
No I/O is built into C++ l Instead, a library provides an output stream Screen executing program iostream 34
35 Using Libraries l A library has 2 parts Interface (stored in a header file) tells what items are in the library and how to use them. Implementation (stored in another file) contains the definitions of the items in the library. l #include Refers to the header file for the iostream library needed for use of cout and endl.
36 Using Libraries l Header file: You must put the include statement at the top of your program for I/O that you use (#include for display, keyboard operations for example) l The implementation file is included automatically for you by the compiler
37 // ****************************************************** // PrintName program // This program prints a name in two different formats // ****************************************************** #include // for cout and endl #include // for data type string using namespace std; const string FIRST = “Herman”; // Person’s first name const string LAST = “Smith”; // Person’s last name const char MIDDLE = ‘G’; // Person’s middle initial C++ Program
38 C++ Code Continued int 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 << firstLast << endl; lastFirst = LAST + “, “ + FIRST + ’ ’ ; cout << “Name in first-last format is “ << endl << lastFirst << MIDDLE << ’.’ << endl; return 0; }
39 Output of Program Name in first-last format is Herman Smith Name in last-first-initial format is Smith, Herman G.
40 Namespaces l C++ has the ability to use the same variable name for different variables in different namespaces l This is an advanced feature you do not need to use (and can be confusing)
41 using namespace std l For your programs: l Put the system includes (like #include at the top (after the prolog comments) l Follow the system includes with the statement: using namespace std;