1 / 49

Chapter 2 C++ Syntax and Semantics, and the Program Development Process

Programming in C++. Chapter 2 C++ Syntax and Semantics, and the Program Development Process. End of Line Manipulator. Two ways of doing this cout &lt;&lt;“The State of Pennsylvania<br>” &lt;&lt; “is where Penn State University is located.<br>”;

jessemorgan
Download Presentation

Chapter 2 C++ Syntax and Semantics, and the Program Development Process

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming in C++ Chapter 2 C++ Syntax and Semantics, and the Program Development Process

  2. End of Line Manipulator • Two ways of doing this • cout <<“The State of Pennsylvania\n” << “is where Penn State University is located.\n”; • cout <<“The State of Pennsylvania” << endl <<“is where Penn State University is located.” << endl; • Good programming is to always end your program with a \n or endl

  3. Identifiers • Identifiers (i.e. variables) are the very core of programming languages • Programs are constructed so as to manipulate numbers, letter, and characters • Identifiers (variables) hold numbers usually

  4. Identifiers • The strength of a identifier is that its value is easily changed • Identifiers are case sensitive • forest is different from forEst • Good programming uses identifiers that relate to the data and the program • Goof programming uses a consistent method of creating identifiers

  5. Identifiers • 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. • VALID age_of_dog TaxRate98 PrintHeading AgeOfHorse • NOT VALID (Why?) age# 98TaxRate Age-Of-Cat

  6. More about Identifiers • Some C++ compilers recognize only the first 32 characters of an identifier as significant. • Then these identifiers are considered the same: Age_Of_This_Old_Rhinoceros_At_My_Zoo Age_Of_This_Old_Rhinoceros_At_My_Safari • What about these? Age_Of_This_Old_Rhinoceros_At_My_Zoo AgE_Of_This_Old_Rhinoceros_At_My_Zoo

  7. More about Identifiers • C++ has certain reserved words that have a predetermined meaning and are not be be used as identifiers • e.g. int, long, float, return, short • see Appendix A of text for a list of these reserved words • “do not” use reserved words as identifiers, else there will be a programming problem

  8. Identifiers • Every identifier (variable) in a C++ program must be declared before it is used • before being used • at the start of the “main” part of the program • Separate declarations of variables by a comma when they are in the same statement

  9. Address pointer reference C++ Data Types Simple Structured Integral Floating array struct union class char short int long enum float double long double

  10. C++ Simple Data Types Simple types Floating Integral char short int long enum float double long double unsigned

  11. Fundamental Data Types in C++ • Integral Types • represent whole numbers and their negatives • declared as int, short, orlong • Floating Types • represent real numbers with a decimal point • declared as float, or double • Character Type • can be letters, single digits, symbols, punctuation • declared as char

  12. Samples of C++ Data Values int sample values 4578 -4578 0 doublesample values 95.274 95. .265 9521E-3 -95E-1 95.213E2 char sample values ‘B’‘d’ ‘4’‘?’‘*’

  13. Scientific Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.00027

  14. Size of Varibles • Program to calculate size of allowed variables • short int 2 bytes -32,768 to 32,767 • long int 4 bytes -2,147,483,648 to 2,147,483,648 • float 4 bytes 1.2e-38 to 3.4e38 • double 8 bytes 2.2e-308 to 1.8e308

  15. Program Variable Sizes • //Finding the size of varible types used by your computer • #include <iostream.h> • int main() • { • cout << "The size of an int is:\t\t" << sizeof(int) • << " bytes.\n"; • cout << "The size of a short int is:\t\t" << sizeof(short) • << " bytes.\n"; • cout << "The size of a long int is:\t\t" << sizeof(long) • << " bytes.\n"; • cout << "The size of a char is:\t\t" << sizeof(char) • << " bytes.\n"; • cout << "The size of a float is:\t\t" << sizeof(float) • << " bytes.\n"; • cout << "The size of a double is:\t\t" << sizeof(double) • << " bytes.\n"; • return 0;

  16. More About Floating Point Values • Floating point numbers have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing. EXAMPLES 18.4 500. .8 -127.358 • Alternatively, floating point values can have an exponent, as in scientific notation. The number preceding the letter E doesn’t need to include a decimal point. EXAMPLES 1.84E1 5E2 8E-1 -.127358E3

  17. Understanding Types • Is 5,123 a valid integer constant? • No, commas are not allowed • Is 5.8e24 a valid floating point constant? • Yes • Is 0.0 a valid floating point constant? • Yes • Is “Float” a reserved word? • No, but “float” is

  18. What is a Variable? • A variableis a location in memorywhich we can refer to by an identifier, and in which a data value that can be changed is stored.

  19. What Does a Variable Declaration Do? int Age_Of_Dog; float TaxRate98; char MiddleInitial; A declaration tells the compiler to allocate enough memoryto hold a value of this data type, and to associate the identifierwith this location. 4 bytes for TaxRate98 1 byte for MiddleInitial

  20. Giving a value to a variable In your program you can assign (give) a value to the variable by using the assignment operator = Age_Of_Dog = 12; or by another method, such as cout << “How old is your dog?”; cin >> Age_Of_Dog;

  21. What is a Named Constant? • A named constantis a location in memorywhich we can refer to by an identifier, and in which a data value that cannot be changed is stored. VALID CONSTANT DECLARATIONS const char STAR = ‘*’ ; const float NORMAL_TEMP = 98.6 ; const float PI = 3.14159 ; const float TAX_RATE = 0.0725 ; const int MAX_SIZE = 50 ; const int VOTING_AGE = 18 ;

  22. says no parameters type of returned value name of function Simplest C++ Program int main (void) { return 0; }

  23. A Block (or Compound Statement) • A block is a sequence of zero or more statements enclosed by a pair of curly braces { }. SYNTAX { Statement(optional) . . . }

  24. main Returns an Integer to the Operating System //*************************************************************************** // FreezeBoil program // This program computes the midpoint between // the freezing and boiling points of water //*************************************************************************** #include < iostream.h> const float FREEZE_PT = 32.0 ; // Freezing point of water const float BOIL_PT = 212.0 ; // Boiling point of water int main ( void ) { float avgTemp ; // Holds the result of averaging // FREEZE_PT and BOIL_PT

  25. Function main Continued 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 ; }

  26. Is compilation the first step? • No. Before your source program is compiled, it is first examined by the preprocessorto • Remove all comments from source code • Handle all preprocessor directives. They begin with the # character such as #include <iostream.h> • Tells preprocessor to look in the standard include directory for the header file called iostream.h and insert its contents into your source code.

  27. Using Libraries • 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. • #include <iostream.h> Refers to the header file for the iostream library needed for use of cin and cout.

  28. Mileage Program /* This program computes miles per gallon given four amounts for gallons used, and starting and ending mileage. Constants: The gallon amounts for four fillups. The starting mileage. The ending mileage. Output (screen) The calculated miles per gallon. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ #include <iostream.h>

  29. C++ Code Continued const float AMT1 = 11.7 ; // Number of gallons for fillup 1 const float AMT2 = 14.3 ; // Number of gallons for fillup 2 const float AMT3 = 12.2 ; // Number of gallons for fillup 3 const float AMT4 = 8.5 ; // Number of gallons for fillup 4 const float START_MILES = 67308.0 ; // Starting mileage const float END_MILES = 68750.5 ; // Ending mileage int main(void) { float mpg ; // Computed miles per gallon mpg = (END_MILES - START_MILES) / (AMT1 + AMT2 + AMT3 + AMT4) ;

  30. main Returns an Integer Value to the Operating System cout << “For the gallon amounts “ << endl ; cout << AMT1 << ‘ ‘ << AMT2 << ‘ ‘ << AMT3 << ‘ ‘ << AMT4 << endl ; cout << “and a starting mileage of “ << START_MILES << endl ; cout << “and an ending mileage of “ << END_MILES << endl ; cout << “the mileage per gallon is “ << mpg << endl ; return 0; }

  31. What is an Expression in C++? • An expression is any valid combination of operators and operands. • In C++ each expression has a value. • The value of the expression 9.3 * 4.5 is 41.85

  32. Division Operator • The result of the division operator depends on the type of its operands. • If one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type. • Examples 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75

  33. Modulus Operator • The modulus operator % can only be used with integer type operands and always has an integer type result. • Its result is the integer typeremainderof an integer division. • EXAMPLE 11 % 4 has value 3 because R = ? ) 4 11

  34. More C++ Operators int Age; Age = 8; Age = Age + 1; 8 Age 9 Age

  35. PREFIX FORMIncrement Operator int Age; Age = 8; ++Age; 8 Age 9 Age

  36. POSTFIX FORM Increment Operator int Age; Age = 8; Age++; 8 Age 9 Age

  37. Decrement Operator int Dogs; Dogs = 100; Dogs--; 100 Dogs 99 Dogs

  38. Which form to use?? • When the increment (or decrement) operator is used in a “stand alone” statementsolely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form. USE EITHER Dogs--;--Dogs ;

  39. BUT... • When the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results. WE’LL SEE HOW LATER . . .

  40. Insertion Operator ( << ) • Variablecoutis predefined to denote an output stream that goes to the standard output device (display screen). • The insertion operator << called “put to” takes 2 operands. • The left operand is a stream expression, such as cout. The right operand is an expression of simple type or a string constant.

  41. Output Statements SYNTAX These examples yield the same output. cout << “The answer is “ ; cout << 3 * 4 ; cout << “The answer is “ << 3 * 4 ; cout << ExprOrString << ExprOrString . . . ;

  42. Function definition Parameter of function Name of function Function Concept in Math f ( x ) = 5 x - 3 When x = 1, f ( x ) = 2 is the returned value. When x = 4, f ( x ) = 17 is the returned value. Returned value is determined by the function definition and by the values of any parameters.

  43. A C++ program is a collection of one or more functions • There must be a function called main( ) • Execution begins with the first statement in function main( ) • Any other functions in your program are subprograms and are not executed until they are called.

  44. Program with several functions main( ) function Square( ) function Cube( ) function

  45. Program with Three Functions #include <iostream.h> int Square ( int ) ; // declares these 2 functions int Cube ( int ) ; int main ( void ) { cout << “The square of 27 is “ << Square (27) << endl ; // function call cout << “The cube of 27 is “ << Cube (27) << endl ; // function call return 0 ; }

  46. Rest of Program int Square ( int n ) { return n * n ; } int Cube ( int n ) { return n * n * n ; }

  47. Output of program The square of 27 is 729 The cube of 27 is 19683

  48. Before Next Class • Go to a computer lab and type in and run mileage program on page 49 of text • Try programming and running program exercise 3 on page 58 of text

  49. What Next Class Will Cover • Any questions from last class session • Complete chapter 2 • Class discussion of review questions for better understanding of chapter 2 • Programming examples provided • Recommended Chapter 2 practice questions

More Related