chapter 7
DESCRIPTION
Chapter 7. Introduction to High-Level Language Programming. Where Do We Stand?. Machine language Assembly language LOAD X ADD ONE STORE X . ONE: .DATA 1 Equivalent to INCREMENT X Fine-tuning. Disadvantages of Assembly Language. - PowerPoint PPT PresentationTRANSCRIPT
Chapter 7
Introduction to High-Level Language Programming
Where Do We Stand?Machine languageAssembly language
LOAD XADD ONESTORE X.
ONE: .DATA 1
Equivalent to INCREMENT X
Fine-tuning
Disadvantages of Assembly Language
Manually manage the movement of data items between and among memory locations.Must take a microscopic view of a taskMachine-specificStatements are not English-like
High-level Programming Language
Data management is much easier.Take a macroscopic view of tasks. High-level languages are more portable. Closer to standard English, use standard mathematical notation.High-level programming languages are often called third-generation language.
Program Translation
Need a translator to convert high-level language instructions into machine languages.Such a system software is called a compiler.Code libraryLinker
Translations of High-Level Language
Refer to Figure 7.1.Source program translation(compiler) intermediate program (assembly language code) translation (assembler) object program(object code in machine language) Linker (links with library object code)complete object code(executable) loader complete object code loaded into memory hardware (execution) results
The C++ Language
Developed in the 1980s by Bjarne Stroustrup at AT&T Bell labs.Extension of CObject-oriented (more on this topic later)
1 // Fig. 1.2: fig01_02.cpp
2 // A first program in C++
3 #include <iostream>
4
5 int main()
6 {
7 std::cout << "Welcome to C++!\n";
8
9 return 0; // indicate that program ended successfully
10 }
Welcome to C++!
preprocessor directive
Message to the C++ preprocessor.
Lines beginning with # are preprocessor directives.
#include <iostream> tells the preprocessor to include the contents of the file <iostream>, which includes input/output operations (such as printing to the screen).
Comments
Written between /* and */ or following a //.
Improve program readability and do not cause the computer to perform any action.
C++ programs contain one or more functions, one of which must be main
Parenthesis are used to indicate a function
int means that main "returns" an integer value. More in Chapter 3.
A left brace { begins the body of every function and a right brace } ends it.
Prints the string of characters contained between the quotation marks.
The entire line, including std::cout, the << operator, the string "Welcome to C++!\n" and the semicolon (;), is called a statement.
All statements must end with a semicolon.
return is a way to exit a function from a function.
return 0, in this case, means that the program terminated normally.
Overall Form of a C++ Program
Prologue comment [optional]Include derivatives [optional]Functions [optional]Main function {
declarations [optional]main function body
}
Virtual Data Storage
Can associate data with a more meaningful name called identifier.In C++, an identifier can be any combination of letters,digits and the underscore symbol (_), as long as it does not begin with a digit.Cannot use keywords for identifiers, either.C++ is a case-sensitive language.Constants vs. variables
C++ Keywords Cannot be used as identifiers or
variable names.C++ Keywords
Keywords common to the C and C++ programming languages
auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while C++ only keywords
asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t
Declaration
Tells whether the data item is a constant or a variable.Tells the identifier that will be used throughout the program to name the item.Tells the data type for that item.e.g. double Radius;
C++ Syntax
Syntax: the correct form for each component of the language.C++ is a free-format language, it does not matter where things are placed on a line.const double PI = 3.1416;int grades[50];int image[256][256];
2-D Array
[0][0]=14.3, [0][1]=15.2, [0][2]=16.4[1][0]=13.9, [1][1]=14.2, [1][2]=12.7 Data structure
Site 1 Site 2 Site 3
Final reading
14.3 15.2 16.4
Initial reading
13.9 14.2 12.7
Statement Types
Input/output statementsAssignment statementsControl statements
Input/output Statements
Get the value for radius:cin >> Radius; extraction operator >>iostream library #include <iostream.h>Print the value of circumferencecout << Circumference;insertion operation <<
Output format
Fixed-point format: 84.8232Scientific notation (floating-point format): 8.482320e+001 #include <iomanip.h> cout.setf(ios::fixed); cout.setf(ios::scientific);
cout.precision(2);
setw(8);
The Assignment Statement
Set the value of “variable” to “arithmetic expression” variable=expression;B=2;C=5;A=B+C;A=A+1;+,-,*,/,% (mod)Changing data type: type casting
Control Statements
Sequential (default, no action required)ConditionalLooping
C++ Comparison and Boolean Operators
Comparison operators: ==, < , <=, > , >=, != Boolean operators && (AND), || (OR), ! (NOT)
Conditional Statements
if-elseifNested-if
1 // Fig. 1.14: fig01_14.cpp2 // Using if statements, relational3 // operators, and equality operators4 #include <iostream>56 using std::cout; // program uses cout7 using std::cin; // program uses cin8 using std::endl; // program uses endl910 int main()11 {12 int num1, num2;1314 cout << "Enter two integers, and I will tell you\n"15 << "the relationships they satisfy: ";16 cin >> num1 >> num2; // read two integers1718 if ( num1 == num2 )19 cout << num1 << " is equal to " << num2 << endl;2021 if ( num1 != num2 )22 cout << num1 << " is not equal to " << num2 << endl;2324 if ( num1 < num2 )25 cout << num1 << " is less than " << num2 << endl;2627 if ( num1 > num2 )28 cout << num1 << " is greater than " << num2 << endl;2930 if ( num1 <= num2 )31 cout << num1 << " is less than or equal to "32 << num2 << endl;33
The if statements test the truth of the condition. If it is true, body of if statement is executed. If not, body is skipped.
To include multiple statements in a body, delineate them with braces {}.
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7
Notice the using statements.
34 if ( num1 >= num2 )
35 cout << num1 << " is greater than or equal to "
36 << num2 << endl;
37
38 return 0; // indicate that program ended successfully
39 }
Enter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7
Enter two integers, and I will tell you the relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12
Enter two integers, and I will tell you the relationships they satisfy: 7 77 is equal to 77 is less than or equal to 77 is greater than or equal to 7
Nested if/else StructuresTest for multiple cases by placing if/else selection structures inside if/else selection structures.
if student’s grade is greater than or equal to 90 Print “A”else if student’s grade is greater than or equal to 80
Print “B”else
if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or
equal to 60 Print “D”
else Print “F”
Once a condition is met, the rest of the statements are skipped
Looping
while (Boolean condition)S1;
Initialization of variables.Sentinel value: to signal that there are no more data.Infinite loop
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-controlled repetition3 #include <iostream>45 using std::cout;6 using std::cin;7 using std::endl;89 int main()10 {11 int total, // sum of grades 12 gradeCounter, // number of grades entered13 grade, // one grade14 average; // average of grades1516 // initialization phase17 total = 0; // clear total18 gradeCounter = 1; // prepare to loop1920 // processing phase21 while ( gradeCounter <= 10 ) { // loop 10 times22 cout << "Enter grade: "; // prompt for input23 cin >> grade; // input grade24 total = total + grade; // add grade to total25 gradeCounter = gradeCounter + 1; // increment counter26 }2728 // termination phase29 average = total / 10; // integer division30 cout << "Class average is " << average << endl;3132 return 0; // indicate program ended successfully33 }
The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.
Enter grade: 98Enter grade: 76Enter grade: 71Enter grade: 87Enter grade: 83Enter grade: 90Enter grade: 57Enter grade: 79Enter grade: 82Enter grade: 94Class average is 81
1 // Fig. 2.9: fig02_09.cpp
2 // Class average program with sentinel-controlled repetition.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::ios;
9
10 #include <iomanip>
11
12 using std::setprecision;
13 using std::setiosflags;
14
15 int main()
16 {
17 int total, // sum of grades
18 gradeCounter, // number of grades entered
19 grade; // one grade
20 double average; // number with decimal point for average
21
22 // initialization phase
23 total = 0;
24 gradeCounter = 0;
25
26 // processing phase
27 cout << "Enter grade, -1 to end: ";
28 cin >> grade;
29
30 while ( grade != -1 ) {
Data type double used to represent decimal numbers.
31 total = total + grade; 32 gradeCounter = gradeCounter + 1; 33 cout << "Enter grade, -1 to end: "; 34 cin >> grade; 35 }3637 // termination phase38 if ( gradeCounter != 0 ) { 39 average = static_cast< double >( total ) / gradeCounter;40 cout << "Class average is " << setprecision( 2 )41 << setiosflags( ios::fixed | ios::showpoint )42 << average << endl;43 }44 else45 cout << "No grades were entered" << endl;4647 return 0; // indicate program ended successfully48 }
Enter grade, -1 to end: 75Enter grade, -1 to end: 94Enter grade, -1 to end: 97Enter grade, -1 to end: 88Enter grade, -1 to end: 70Enter grade, -1 to end: 64Enter grade, -1 to end: 83Enter grade, -1 to end: 89Enter grade, -1 to end: -1Class average is 82.50
setiosflags(ios::fixed | ios::showpoint) - stream manipulator
ios::fixed - output numbers with a fixed number of decimal points.
ios::showpoint - forces decimal point and trailing zeros, even if unnecessary: 66 printed as 66.00
| - separates multiple option.
setprecision(2) - prints only two digits past decimal point.
Programs that use this must include <iomanip>
static_cast<double>() - treats total as a double temporarily.
Required because dividing two integers truncates the remainder.
gradeCounter is an int, but it gets promoted to double.
Meeting Expectations
Data management issueMacroscopic viewPortability: ANSI standardCloser to human-language
Keeping the Pieces ApartDivide and conquerUsing functions Function name (identifier) Argument list: what to pass, what
gets returned(return indicator) Local vs. global variables Pass by value vs. pass by reference
1 // Fig. 3.12: fig03_12.cpp2 // A scoping example3 #include <iostream>45 using std::cout;6 using std::endl;78 void a( void ); // function prototype9 void b( void ); // function prototype10 void c( void ); // function prototype1112 int x = 1; // global variable1314 int main()15 {16 int x = 5; // local variable to main1718 cout << "local x in outer scope of main is " << x << endl;1920 { // start new scope21 int x = 7;2223 cout << "local x in inner scope of main is " << x << endl;24 } // end new scope2526 cout << "local x in outer scope of main is " << x << endl;2728 a(); // a has automatic local x29 b(); // b has static local x30 c(); // c uses global x31 a(); // a reinitializes automatic local x32 b(); // static local x retains its previous value33 c(); // global x also retains its value34
x is different inside and outside the block.
local x in outer scope of main is 5local x in inner scope of main is 7local x in outer scope of main is 5
3.1 Define Functions
35 cout << "local x in main is " << x << endl;3637 return 0;38 }3940 void a( void )41 {42 int x = 25; // initialized each time a is called4344 cout << endl << "local x in a is " << x 45 << " after entering a" << endl;46 ++x;47 cout << "local x in a is " << x 48 << " before exiting a" << endl;49 }5051 void b( void )52 {53 static int x = 50; // Static initialization only54 // first time b is called.55 cout << endl << "local static x is " << x 56 << " on entering b" << endl;57 ++x;58 cout << "local static x is " << x 59 << " on exiting b" << endl;60 }6162 void c( void )63 {64 cout << endl << "global x is " << x 65 << " on entering c" << endl;66 x *= 10;67 cout << "global x is " << x << " on exiting c" << endl;68 }
Local automatic variables are created and destroyed each time a is called.
Local static variables are not destroyed when the function ends.
Global variables are always accessible. Function c references the global x.
local x in a is 25 after entering a
local x in a is 26 before exiting a
local static x is 50 on entering b
local static x is 51 on exiting b
global x is 1 on entering c
global x is 10 on exiting c
local x in outer scope of main is 5local x in inner scope of main is 7local x in outer scope of main is 5 local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 50 on entering blocal static x is 51 on exiting b global x is 1 on entering cglobal x is 10 on exiting c local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 51 on entering blocal static x is 52 on exiting b global x is 10 on entering cglobal x is 100 on exiting clocal x in main is 5
1 // Fig. 3.20: fig03_20.cpp
2 // Comparing call-by-value and call-by-reference
3 // with references.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 int squareByValue( int );
10 void squareByReference( int & );
11
12 int main()
13 {
14 int x = 2, z = 4;
15
16 cout << "x = " << x << " before squareByValue\n"
17 << "Value returned by squareByValue: "
18 << squareByValue( x ) << endl
19 << "x = " << x << " after squareByValue\n" << endl;
20
21 cout << "z = " << z << " before squareByReference" << endl;
22 squareByReference( z );
23 cout << "z = " << z << " after squareByReference" << endl;
24
25 return 0;
26 }
27
28 int squareByValue( int a )
29 {
30 return a *= a; // caller's argument not modified
31 }
Notice the use of the & operator
x = 2 before squareByValueValue returned by squareByValue: 4x = 2 after squareByValue z = 4 before squareByReferencez = 16 after squareByReference
32
33 void squareByReference( int &cRef )
34 {
35 cRef *= cRef; // caller's argument modified
36 }