360 likes | 554 Views
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.
E N D
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 • Manually manage the movement of data items between and among memory locations. • Must take a microscopic view of a task • Machine-specific • Statements 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 library • Linker
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 C • Object-oriented (more on this topic later)
1 // Fig. 1.2: fig01_02.cpp Comments Written between /* and */ or following a //. Improve program readability and do not cause the computer to perform any action. 2 // A first program in C++ 3 #include <iostream> 4 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). 5 int main() 6 { 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. 7 std::cout << "Welcome to C++!\n"; 8 Prints the string of characters contained between the quotation marks. The entire line, including std::cout, the <<operator, the string"WelcometoC++!\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. 9 return 0; // indicate that program ended successfully A left brace {begins the body of every function and a right brace } ends it. 10 } Welcome to C++!
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.
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
Statement Types • Input/output statements • Assignment statements • Control 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.8232 • Scientific 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) • Conditional • Looping
C++ Comparison and Boolean Operators • Comparison operators: ==, < , <=, > , >=, != • Boolean operators && (AND), || (OR), ! (NOT)
Conditional Statements • if-else • if • Nested-if
1 // Fig. 1.14: fig01_14.cpp 2 // Using if statements, relational 3 // operators, and equality operators Notice the using statements. 4 #include <iostream> 5 6 using std::cout; // program uses cout 7 using std::cin; // program uses cin 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 {}. 8 using std::endl; // program uses endl 9 10 int main() 11 { 12 int num1, num2; 13 14 cout << "Enter two integers, and I will tell you\n" 15 << "the relationships they satisfy: "; 16 cin >> num1 >> num2; // read two integers 17 18 if ( num1 == num2 ) 19 cout << num1 << " is equal to " << num2 << endl; 20 21 if ( num1 != num2 ) 22 cout << num1 << " is not equal to " << num2 << endl; 23 24 if ( num1 < num2 ) 25 cout << num1 << " is less than " << num2 << endl; 26 27 if ( num1 > num2 ) 28 cout << num1 << " is greater than " << num2 << endl; 29 30 if ( num1 <= num2 ) 31 cout << num1 << " is less than or equal to " 32 << num2 << endl; 33 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
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 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7
Nested if/else Structures • Test 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 repetition 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end. 8 9 int main() 10 { 11 int total, // sum of grades 12 gradeCounter, // number of grades entered 13 grade, // one grade 14 average; // average of grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 1; // prepare to loop 19 20 // processing phase 21 while ( gradeCounter <= 10 ) { // loop 10 times 22 cout << "Enter grade: "; // prompt for input 23 cin >> grade; // input grade 24 total = total + grade; // add grade to total 25 gradeCounter = gradeCounter + 1; // increment counter 26 } 27 28 // termination phase 29 average = total / 10; // integer division 30 cout << "Class average is " << average << endl; 31 32 return 0; // indicate program ended successfully 33 }
Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81
1 // Fig. 2.9: fig02_09.cpp 2 // Class average program with sentinel-controlled repetition. Data type double used to represent decimal numbers. 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 ) {
31 total = total + grade; 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. 32 gradeCounter = gradeCounter + 1; 33 cout << "Enter grade, -1 to end: "; 34 cin >> grade; 35 } 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. 36 37 // termination phase 38 if ( gradeCounter != 0 ) { setprecision(2) - prints only two digits past decimal point. Programs that use this must include <iomanip> 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 else 45 cout << "No grades were entered" << endl; 46 47 return 0; // indicate program ended successfully 48 } Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50
Meeting Expectations • Data management issue • Macroscopic view • Portability: ANSI standard • Closer to human-language
Keeping the Pieces Apart • Divide and conquer • Using 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.cpp 2 // A scoping example 3 #include <iostream> 4 x is different inside and outside the block. 5 using std::cout; 6 using std::endl; 7 8 void a( void ); // function prototype 9 void b( void ); // function prototype 10 void c( void ); // function prototype local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 11 12 int x = 1; // global variable 13 14 int main() 15 { 16 int x = 5; // local variable to main 17 18 cout << "local x in outer scope of main is " << x << endl; 19 20 { // start new scope 21 int x = 7; 22 23 cout << "local x in inner scope of main is " << x << endl; 24 } // end new scope 25 26 cout << "local x in outer scope of main is " << x << endl; 27 28 a(); // a has automatic local x 29 b(); // b has static local x 30 c(); // c uses global x 31 a(); // a reinitializes automatic local x 32 b(); // static local x retains its previous value 33 c(); // global x also retains its value 34
35 cout << "local x in main is " << x << endl; 36 37 return 0; Local automatic variables are created and destroyed each time a is called. 38 } local x in a is 25 after entering a local x in a is 26 before exiting a 39 Local static variables are not destroyed when the function ends. 40 void a( void ) 41 { 42 int x = 25; // initialized each time a is called local static x is 50 on entering b local static x is 51 on exiting b 43 Global variables are always accessible. Function creferences the globalx. 44 cout << endl << "local x in a is " << x 45 << " after entering a" << endl; global x is 1 on entering c global x is 10 on exiting c 46 ++x; 47 cout << "local x in a is " << x 48 << " before exiting a" << endl; 49 } 50 51 void b( void ) 52 { 53 static int x = 50; // Static initialization only 54 // 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 } 61 62 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 } 3.1 Define Functions
local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 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 a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5
1 // Fig. 3.20: fig03_20.cpp 2 // Comparing call-by-value and call-by-reference Notice the use of the & operator 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 }
32 33 void squareByReference( int &cRef ) 34 { 35 cRef *= cRef; // caller's argument modified 36 } x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue z = 4 before squareByReference z = 16 after squareByReference