1 Topic 3 Moving from C to C

  • Slides: 59
Download presentation
1 Topic 3 – Moving from C to C++ Outline 3. 1 3. 2

1 Topic 3 – Moving from C to C++ Outline 3. 1 3. 2 3. 3 3. 4 3. 5 3. 6 3. 7 3. 8 3. 9 3. 10 3. 11 3. 12 3. 13 3. 14 3. 15 3. 16 3. 17 3. 18 3. 19 3. 20 Introduction Tokens Keywords Identifiers & Constants Basic Data Types User Defined Data Types Derived Data Types Symbolic Constants Type Compatibility Declaration of Variables Dynamic Utilization of Variables Reference Variable Operators in C++ Scope Resolution Operator Member derefencing Operator Memory Management Operaor Manipulators Type Cast Operator Expressions and Teir Types Special Assignment Expressions

2 Chapter 2 - Control Structures Outline 3. 21 3. 22 3. 23 3.

2 Chapter 2 - Control Structures Outline 3. 21 3. 22 3. 23 3. 24 Implicit Conversions Operator Overloading Operator Precedence Control Structures

3 3. 1 Introduction • C++ Superset of C • Exceptions, Additions and Differences

3 3. 1 Introduction • C++ Superset of C • Exceptions, Additions and Differences

4 3. 2 Tokens • Smallest Individual Unit in Program – – – Keywords

4 3. 2 Tokens • Smallest Individual Unit in Program – – – Keywords Identifiers Constants Strings Operators

5 3. 3 Keywords • C++ keywords – Cannot be used as identifiers or

5 3. 3 Keywords • C++ keywords – Cannot be used as identifiers or variable names

6 3. 4 Identifiers & Constants • Names of Variables, Functions, arrays, classes etc

6 3. 4 Identifiers & Constants • Names of Variables, Functions, arrays, classes etc • Rules – No limit on lengths • Literal Constants – Int – Char – float

7 3. 5 Basic Data Types

7 3. 5 Basic Data Types

8 3. 5 Basic Data Types

8 3. 5 Basic Data Types

9 3. 6 User-defined Data Types • Structures and Classes • Enumerated Data Type

9 3. 6 User-defined Data Types • Structures and Classes • Enumerated Data Type

10 3. 7 Derived Data Types • Arrays • Functions • Pointers – –

10 3. 7 Derived Data Types • Arrays • Functions • Pointers – – – char * const ptr 1 = "Good"; //constant pointer (Address is Constant) int const *ptr 2 = &m // pointer to constant (Contents pointeed by ptr 2 are constant) const char *const cp = "Good";

11 3. 8 Symbolic Constants • Using qualifier const • Using enum keyword

11 3. 8 Symbolic Constants • Using qualifier const • Using enum keyword

12 3. 9 Type Compatiblity • Each type in C++ is differerent • sizeof(‘x’)

12 3. 9 Type Compatiblity • Each type in C++ is differerent • sizeof(‘x’) and sizeof(int) in C is same • sizeof(‘x’) equals sizeof(char) in C++

13 3. 10 Declaration of variable • Allowed anywhere

13 3. 10 Declaration of variable • Allowed anywhere

14 3. 11 Dynamic Initialization of Variables • Initialization at run time int n

14 3. 11 Dynamic Initialization of Variables • Initialization at run time int n =strlen("abc"); float a=3. 142 * r;

15 3. 12 Reference Variables • Alternative name (alias) • Must be intialized at

15 3. 12 Reference Variables • Alternative name (alias) • Must be intialized at the time of declaration int a=10; int &x = a; a++; a=11 x++; a=12 x=12

16 3. 12 Reference Variables

16 3. 12 Reference Variables

17 3. 13 Operators in C++ • Operator Overloading << Insertion >> Extraction

17 3. 13 Operators in C++ • Operator Overloading << Insertion >> Extraction

18 3. 14 Scope Resolution Operator

18 3. 14 Scope Resolution Operator

19 3. 15 Member Dereferencing Operator

19 3. 15 Member Dereferencing Operator

3. 16 Memory Management Operator Memory management in C C uses malloc(), calloc() functions

3. 16 Memory Management Operator Memory management in C C uses malloc(), calloc() functions to allocate memory dynamically. C uses free() function to delete the memory which is dynamically allocated.

Memory management in C++ There are two types of memory management operators in C++:

Memory management in C++ There are two types of memory management operators in C++: • new • delete These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways.

 • New operator: The new operator in C++ is used for dynamic storage

• New operator: The new operator in C++ is used for dynamic storage allocation. This operator can be used to create object of any type. • General syntax of new operator in C++: The general syntax of new operator in C++ is as follows: pointer variable = new datatype; • In the above statement, new is a keyword and the pointer variable is a variable of type datatype.

int *a=new int; In the above statement, new is a keyword and the pointer

int *a=new int; In the above statement, new is a keyword and the pointer variable is a variable of type datatype. For example: int *a=new int; In the above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. The pointer variable a holds the address of memory space allocated. Dynamic variables are never initialized by the compiler. Therefore, the programmer should make it a practice to first assign them a value. The assignment can be made in either of the two ways: int *a = new int; *a = 20; or int *a = new int(20);

 • delete operator: • The delete operator in C++ is used for releasing

• delete operator: • The delete operator in C++ is used for releasing memory space when the object is no longer needed. Once a new operator is used, it is efficient to use the corresponding delete operator for release of memory. • The general syntax of delete operator in C++ is as follows: delete pointer_variable;

25 • new pointer variable = new data_type; int *p=new int(25); int *p=new int[100];

25 • new pointer variable = new data_type; int *p=new int(25); int *p=new int[100]; • delete p; delete []p;

26 3. 17 Manipulators • setw • endl cout<<setw(5)<<a<<endl;

26 3. 17 Manipulators • setw • endl cout<<setw(5)<<a<<endl;

27 3. 18 The Cast Operator • Type conversion • (type-name) expression; //C notation

27 3. 18 The Cast Operator • Type conversion • (type-name) expression; //C notation • Type-name (expression) //C++ notation

28 3. 19 Expressions and Their Types • • Constant Integral Float Pointer Relational;

28 3. 19 Expressions and Their Types • • Constant Integral Float Pointer Relational; Logical Bitwise

29 3. 20 Special Assignment Expressions • Chained a=b=c=10; • Embedded a=(b=10)+c; • Compound

29 3. 20 Special Assignment Expressions • Chained a=b=c=10; • Embedded a=(b=10)+c; • Compound (short hand) x+=10;

30 3. 21 Implicit Conversion • Automatic Conversion • Smaller type is converted to

30 3. 21 Implicit Conversion • Automatic Conversion • Smaller type is converted to wider

31 3. 20 Operator Overloading • Assigning different meaning • << >>

31 3. 20 Operator Overloading • Assigning different meaning • << >>

32 3. 21 Operator Pecedence

32 3. 21 Operator Pecedence

33 3. 24 Control Structure • Sequential execution – Statements executed in order •

33 3. 24 Control Structure • Sequential execution – Statements executed in order • Transfer of control – Next statement executed not next one in sequence • 3 control structures – Sequence structure • Programs executed sequentially by default – Selection structures • if, if/else, switch – Repetition structures • while, do/while, for

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 34 // Fig. 2. 9: fig 02_09. cpp // Class average program with sentinel-controlled repetition. #include <iostream> using fig 02_09. cpp (1 of 3) std: : cout; std: : cin; std: : endl; std: : fixed; #include <iomanip> // parameterized stream manipulators using std: : setprecision; // sets numeric output precision // function main begins program execution int main() Data type double used to represent { int total; // sum of grades decimal numbers. int grade. Counter; // number of grades entered int grade; // grade value 20 21 double average; 22 23 24 25 // initialization phase total = 0; // initialize total grade. Counter = 0; // initialize loop counter // number with decimal point for average

26 27 28 29 30 31 32 33 34 35 36 37 38 39

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 35 // processing phase // get first grade from user cout << "Enter grade, -1 to end: " ; cin >> grade; // prompt for input // read grade from user // loop until sentinel value read from user treats total while ( grade != -1 )static_cast<double>() { total = total + grade; // add grade to total temporarily (casting). grade. Counter = grade. Counter + 1; // increment counter fig 02_09. cpp (2 of 3) as a double Required because dividing two integers truncates the cout << "Enter grade, -1 to end: " ; remainder. cin >> grade; } // end while // prompt for input // read next grade. Counter is an int, but it gets promoted to double. // termination phase // if user entered at least one grade. . . if ( grade. Counter != 0 ) { // calculate average of all grades entered average = static_cast< double >( total ) / grade. Counter;

49 50 51 52 53 } // end if part of if/else 54 55

49 50 51 52 53 } // end if part of if/else 54 55 56 else // if no grades were entered, output appropriate message cout << "No grades were entered" << endl; 57 58 return 0; 59 60 36 // display average with two digits of precision cout << "Class average is " << setprecision( 2 ) << fixed << average << endl; fig 02_09. cpp (3 of 3) fig 02_09. cpp output (1 of 1) // indicate program ended successfully } // end function main Enter Enter Enter Class grade, -1 to end: grade, -1 to end: grade, -1 to end: average is 82. 50 75 94 97 88 70 64 83 89 -1 setprecision(2)prints two digits past fixed forces output to print decimal in fixed point format (not point (rounded to fit precision). scientific notation). Also, that use this must include <iomanip> forces trailing zeros. Programs and decimal point to print. Include <iostream>

1 2 3 // Fig. 2. 11: fig 02_11. cpp // Analysis of examination

1 2 3 // Fig. 2. 11: fig 02_11. cpp // Analysis of examination results. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 13 14 15 16 // function main begins program execution int main() { // initialize variables in declarations int passes = 0; // number of passes int failures = 0; // number of failures int student. Counter = 1; // student counter int result; // one exam result 17 18 19 20 21 22 23 24 // process 10 students using counter-controlled loop while ( student. Counter <= 10 ) { // prompt user for input and obtain value from user cout << "Enter result (1 = pass, 2 = fail): " ; cin >> result; 37 fig 02_11. cpp (1 of 2)

25 26 27 28 29 30 else // if result not 1, increment failures

25 26 27 28 29 30 else // if result not 1, increment failures = failures + 1; 31 32 33 34 35 } // end while 36 37 38 39 // termination phase; display number of passes and failures cout << "Passed " << passes << endl; cout << "Failed " << failures << endl; 40 41 42 43 // if more than eight students passed, print "raise tuition" if ( passes > 8 ) cout << "Raise tuition " << endl; 44 45 return 0; 46 47 38 // if result 1, increment passes; if/else nested in while if ( result == 1 ) // if/else nested in while passes = passes + 1; // increment student. Counter so loop eventually terminates student. Counter = student. Counter + 1; // successful termination } // end function main fig 02_11. cpp (2 of 2)

Enter result Enter result Enter result Passed 6 Failed 4 (1 (1 (1 =

Enter result Enter result Enter result Passed 6 Failed 4 (1 (1 (1 = = = = = pass, pass, pass, 2 2 2 2 2 = = = = = fail): fail): fail): 1 2 2 1 1 1 2 Enter result (1 Enter result (1 Enter result (1 Passed 9 Failed 1 Raise tuition = = = = = pass, pass, pass, 2 2 2 2 2 = = = = = fail): fail): fail): 1 1 2 1 1 1 39 fig 02_11. cpp output (1 of 1)

1 2 3 // Fig. 2. 14: fig 02_14. cpp // Preincrementing and postincrementing.

1 2 3 // Fig. 2. 14: fig 02_14. cpp // Preincrementing and postincrementing. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 // function main begins program execution int main() { int c; // declare variable 40 fig 02_14. cpp (1 of 2) 12 13 14 15 16 17 // demonstrate postincrement c = 5; // cout << c << endl; // cout << c++ << endl; // cout << c << endl; // assign 5 to c print 5 then postincrement print 6 18 19 20 21 22 23 // demonstrate preincrement c = 5; // cout << c << endl; // cout << ++c << endl; // cout << c << endl; // assign 5 to c print 5 preincrement then print 6

24 25 26 27 5 5 6 6 41 return 0; // indicate successful

24 25 26 27 5 5 6 6 41 return 0; // indicate successful termination } // end function main fig 02_14. cpp (2 of 2) fig 02_14. cpp output (1 of 1)

1 2 3 // Fig. 2. 16: fig 02_16. cpp // Counter-controlled repetition. #include

1 2 3 // Fig. 2. 16: fig 02_16. cpp // Counter-controlled repetition. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 // function main begins program execution int main() { int counter = 1; // initialization 12 13 14 15 while ( counter <= 10 ) { cout << counter << endl; ++counter; 16 17 } // end while 18 19 return 0; 20 21 fig 02_16. cpp (1 of 1) // repetition condition // display counter // increment // indicate successful termination } // end function main 42

1 2 3 4 5 6 7 8 9 10 43 fig 02_16. cpp

1 2 3 4 5 6 7 8 9 10 43 fig 02_16. cpp output (1 of 1)

1 2 3 // Fig. 2. 17: fig 02_17. cpp // Counter-controlled repetition with

1 2 3 // Fig. 2. 17: fig 02_17. cpp // Counter-controlled repetition with the for structure. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 12 // function main begins program execution int main() { // Initialization, repetition condition and incrementing // are all included in the for structure header. 13 14 15 for ( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; 16 17 return 0; 18 19 // indicate successful termination } // end function main 44 fig 02_17. cpp (1 of 1)

1 2 3 4 5 6 7 8 9 10 45 fig 02_17. cpp

1 2 3 4 5 6 7 8 9 10 45 fig 02_17. cpp output (1 of 1)

46 1 2 3 // Fig. 2. 20: fig 02_20. cpp // Summation with

46 1 2 3 // Fig. 2. 20: fig 02_20. cpp // Summation with for. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 // function main begins program execution int main() { int sum = 0; // initialize sum fig 02_20. cpp (1 of 1) 12 13 14 15 // sum even integers from 2 through 100 for ( int number = 2; number <= 100; number += 2 ) sum += number; // add number to sum 16 17 18 cout << "Sum is " << sum << endl; return 0; 19 20 } // end function main Sum is 2550 // output sum // successful termination fig 02_20. cpp output (1 of 1)

1 2 3 // Fig. 2. 21: fig 02_21. cpp // Calculating compound interest.

1 2 3 // Fig. 2. 21: fig 02_21. cpp // Calculating compound interest. #include <iostream> 4 5 6 7 8 using 9 10 #include <iomanip> 11 12 13 using std: : setw; using std: : setprecision; 14 15 #include <cmath> 16 17 18 19 20 21 22 // function main begins program execution int main() { double amount; // amount on deposit double principal = 1000. 0; // starting principal double rate =. 05; // interest rate 23 47 fig 02_21. cpp (1 of 2) std: : cout; std: : endl; std: : ios; std: : fixed; <cmath> header needed for the pow function (program will not compile without it). // enables program to use function pow

24 25 // output table column heads cout << "Year" << setw( 21 )

24 25 // output table column heads cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; 26 27 28 // set floating-point number format cout << fixed << setprecision( 2 ); 29 30 31 // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { 32 33 34 // calculate new amount for specified year amount = principal * pow( 1. 0 + rate, year ); 35 36 37 38 // output one table row cout << setw( 4 ) << year << setw( 21 ) << amount << endl; pow(x, y) = x raised to the yth power. 39 40 } // end for 41 42 return 0; 43 44 Sets the field width to at least fig 02_21. cpp 21 characters. If output less (2 of 2) than 21, it is right-justified. // indicate successful termination } // end function main 48

Year 1 2 3 4 5 6 7 8 9 10 49 Amount on

Year 1 2 3 4 5 6 7 8 9 10 49 Amount on deposit 1050. 00 1102. 50 1157. 63 1215. 51 1276. 28 1340. 10 1407. 10 1477. 46 1551. 33 1628. 89 fig 02_21. cpp output (1 of 1) Numbers are right-justified due to setw statements (at positions 4 and 21).

1 2 3 // Fig. 2. 22: fig 02_22. cpp // Counting letter grades.

1 2 3 // Fig. 2. 22: fig 02_22. cpp // Counting letter grades. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 13 14 15 16 17 // function main begins program execution int main() { int grade; // one grade int a. Count = 0; // number of As int b. Count = 0; // number of Bs int c. Count = 0; // number of Cs int d. Count = 0; // number of Ds int f. Count = 0; // number of Fs 18 19 20 21 cout << "Enter the letter grades. " << endl << "Enter the EOF character to end input. " << endl; 50 fig 02_22. cpp (1 of 4)

22 23 switch to end and the program continues with the first grade was

22 23 switch to end and the program continues with the first grade was input statement after the switch structure. fig 02_22. cpp // switch structure nested in while (2 of 4) 24 25 26 // determine which switch ( grade ) { 27 28 29 30 31 case 'A': case 'a': ++a. Count; break; // // 32 33 34 35 36 case 'B': case 'b': ++b. Count; break; // // Compares grade (an int) to 37 representations 38 the numerical case 'C': of A and a. 39 case 'c': 40 ++c. Count; 41 break; 42 51 // loop until user types end-of-file key sequence while ( ( grade = cin. get() ) != EOF ) { break causes // // grade was uppercase A or lowercase a increment a. Count necessary to exit switch Assignment statements have a value, was which is the same grade uppercase B as thelowercase variable onb the left of the or =. The value of this statement increment b. Count exit is theswitch same as the value returned by cin. get(). grade was uppercase C or lowercase c This can also be used to increment c. Count initialize multiple variables: exit switch a = b = c = 0; cin. get() uses dot notation (explained chapter 6). This function gets 1 character from the keyboard (after Enter pressed), and it is assigned to grade. cin. get() returns EOF (end-offile) after the EOF character is input, to indicate the end of data. EOF may be ctrl-d or ctrl-z, depending on your OS.

43 44 45 46 case 'D': case 'd': ++d. Count; break; // // grade

43 44 45 46 case 'D': case 'd': ++d. Count; break; // // grade was uppercase D or lowercase d increment d. Count exit switch This test is necessary because grade was Enter uppercase F is pressed after each or lowercase f letter grade is input. This adds increment f. Count a newline character that must exit switch be removed. Likewise, we want to ignore any whitespace. ignore newlines, 47 48 49 50 51 case 'F': case 'f': ++f. Count; break; // // 52 53 54 55 56 case 'n': case 't': case ' ': break; // // tabs, // and spaces in input Notice the default // exit switch 57 58 59 60 61 default: // catch all other characters cout << "Incorrect letter grade entered. " << " Enter a new grade. " << endl; break; // optional; will exit switch anyway 62 63 64 65 66 } // end switch } // end while statement, which catches all other cases. 52 fig 02_22. cpp (3 of 4)

67 68 69 70 71 72 73 74 // output summary of results cout

67 68 69 70 71 72 73 74 // output summary of results cout << "nn. Totals for each letter grade are: " << "n. A: " << a. Count // display number of << "n. B: " << b. Count // display number of << "n. C: " << c. Count // display number of << "n. D: " << d. Count // display number of << "n. F: " << f. Count // display number of << endl; 75 76 return 0; 77 78 // indicate successful termination } // end function main 53 A B C D F grades grades fig 02_22. cpp (4 of 4)

Enter the letter grades. Enter the EOF character to end input. a B c

Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 54 fig 02_22. cpp output (1 of 1)

1 2 3 // Fig. 2. 24: fig 02_24. cpp // Using the do/while

1 2 3 // Fig. 2. 24: fig 02_24. cpp // Using the do/while repetition structure. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 // function main begins program execution int main() { int counter = 1; // initialize counter fig 02_24. cpp (1 of 1) 12 13 14 15 do { cout << counter << " "; } while ( ++counter <= 10 ); 16 17 cout << endl; 18 19 return 0; 20 21 1 3 4 5 6 Notice the preincrement in loop-continuation test. // display counter // end do/while // indicate successful termination } // end function main 2 7 55 8 9 10 fig 02_24. cpp output (1 of 1)

1 2 3 // Fig. 2. 26: fig 02_26. cpp // Using the break

1 2 3 // Fig. 2. 26: fig 02_26. cpp // Using the break statement in a for structure. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 // function main begins program execution int main() { 56 fig 02_26. cpp (1 of 2) 11 12 int x; 13 14 15 // loop 10 times for ( x = 1; x <= 10; x++ ) { // x declared here so it can be used after the loop Exits for structure when break executed. 16 17 18 19 // if x is 5, terminate loop if ( x == 5 ) break; // break loop only if x is 5 20 21 cout << x << " "; // display value of x 22 23 } // end for 24 25 cout << "n. Broke out of loop when x became " << x << endl;

26 27 28 29 57 return 0; // indicate successful termination } // end

26 27 28 29 57 return 0; // indicate successful termination } // end function main 1 2 3 4 Broke out of loop when x became 5 fig 02_26. cpp (2 of 2) fig 02_26. cpp output (1 of 1)

1 2 3 // Fig. 2. 27: fig 02_27. cpp // Using the continue

1 2 3 // Fig. 2. 27: fig 02_27. cpp // Using the continue statement in a for structure. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 11 12 // function main begins program execution int main() { // loop 10 times for ( int x = 1; x <= 10; x++ ) { 58 fig 02_27. cpp (1 of 2) Skips to next iteration of the loop. next iteration of loop 13 14 15 16 // if x is 5, continue with if ( x == 5 ) continue; // skip remaining code in loop body 17 18 cout << x << " "; // display value of x 19 20 } // end for structure 21 22 23 cout << "n. Used continue to skip printing the value 5" << endl; 24 25 return 0; // indicate successful termination

26 27 59 } // end function main 1 2 3 4 6 7

26 27 59 } // end function main 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5 fig 02_27. cpp (2 of 2) fig 02_27. cpp output (1 of 1)