Download - 1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Programming in C++
1
Chapter 2C++ Syntax and Semantics, and the
Program Development Process
Programming in C++
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 TaxRate98PrintHeading 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_ZooAge_Of_This_Old_Rhinoceros_At_My_Safari
What about these?
Age_Of_This_Old_Rhinoceros_At_My_ZooAgE_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
C++ Data TypesC++ Data Types
Structured
array struct union class
Address
pointer reference
Simple
Integral Floating
char short int long enum
float double long double
10
C++ Simple Data TypesC++ Simple Data Types
Simple types
Integral Floating
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 , or long
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
double sample values95.274 95. .2659521E-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 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.
19
What Does a Variable Declaration Do?
A declaration tells the compiler toallocate enough memory to hold a value of this data type,and to associate the identifier with this location.
int Age_Of_Dog;float TaxRate98;char MiddleInitial;
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 constant is a location in memory which 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
Simplest C++ Program
int main (void)
{
return 0;
}
type of returned value name of function says no parameters
23
A block is a sequence of zero or more statements enclosed by a pair of curly braces { }.
SYNTAX
{
Statement (optional)...
}
A Block (or Compound Statement)
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 waterconst 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 preprocessor to 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 partsInterface (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 Continuedconst float AMT1 = 11.7 ; // Number of gallons for fillup 1const 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 mileageconst 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.
Examples11 / 4 has value 211.0 / 4.0 has value 2.7511 / 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 type remainder of an integer division.
EXAMPLE11 % 4 has value 3 because
)4 11R = ?
34
More C++ Operators
8
int Age;
Age = 8;
Age = Age + 1;
Age
9
Age
35
PREFIX FORMIncrement Operator
8int Age;
Age = 8;
++Age;
Age
9
Age
36
POSTFIX FORM Increment Operator
8int Age;
Age = 8;
Age++;
Age
9
Age
37
Decrement Operator
100
int Dogs;
Dogs = 100;
Dogs--;
Dogs
99
Dogs
38
Which form to use??
When the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form.
Dogs-- ; --Dogs ;
USE EITHER
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 ( << ) Variable cout is 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 StatementsSYNTAX
These examples yield the same output.
cout << “The answer is “ ;cout << 3 * 4 ;
cout << “The answer is “ << 3 * 4 ;
cout << ExprOrString << ExprOrString . . . ;
42
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.
Name of functionParameter of function
Function definition
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 functionsint 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 729The 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