1 / 66

Review (Week2) - Control Structures

C++ has only seven control structures: Sequence structure Programs executed sequentially by default Selection structures if , if/else , switch Repetition structures while , do/while , for. Review (Week2) - Control Structures.

judith-lynn
Download Presentation

Review (Week2) - Control Structures

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. C++ has only seven control structures: Sequence structure Programs executed sequentially by default Selection structures if, if/else, switch Repetition structures while, do/while, for Review (Week2)- Control Structures

  2. What is the value of sum after completion of this loop?sum = 0;for(i= -5; i <=1; i++) { sum = sum -i; }(a) 1(b) 14(c) -14(d) –15b

  3. If c is equal to 6, which of the following will be printed after execution of the following code?cout << ( x == 7 ? “correct” : “incorrect” );(a) 6(b) 7(c) correct(d) incorrect

  4. Functions Prepackaged functions: from the standard library programmer-defined functions Function Definitions Function Prototypes Header Files Recursion References and Reference Parameters Review (Week3)- Function

  5. 1 // Fig. 3.4: fig03_04.cpp 2 // Finding the maximum of three integers 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int maximum( int, int, int ); // function prototype 10 11 int main() 12 { 13 int a, b, c; 15 cout << "Enter three integers: "; 16 cin >> a >> b >> c; 18 // a, b and c below are arguments to 19 // the maximum function call 20 cout << "Maximum is: " << maximum( a, b, c ) << endl;

  6. Function definition Comma separate list of arguments; Data type needed for each argument; Data type of result returned. Program Output 21 22 return 0; 23 } 24 25 // Function maximum definition 26 // x, y and z below are parameters to 27 // the maximum function definition 28 int maximum( int x, int y, int z ) 29 { 30 int max = x; 31 32 if ( y > max ) 33 max = y; 34 35 if ( z > max ) 36 max = z; 37 38 return max; 39 } Enter three integers: 22 85 17 Maximum is: 85 Enter three integers: 92 35 14 Maximum is: 92 Enter three integers: 45 19 98 Maximum is: 98

  7. Header Files //file MyFunctions.h Double CalCost(int Quantity, double Price); //file MyMain.cpp #include <iostream> #include “MyFunctions.h” Int main () { int ItemQuantity; double ItemPrice, Cost; ItemQuantity = 20; ItemPrice = 2.5 Cost = CalCost(ItemQuantity, ItemPrice); cout << “Total Cost is”<< Cost<<endl; Return(); } //end main() function //file MyFunction.cpp #include “MyFunctions.h” Double CalCost(int Quantity, double Price) { double Cost; Cost = Quantity * Price; reture Cost; }

  8. Example: Random Number Generation • Scaling • Reduces random number to a certain range • Modulus ( % ) operator • Reduces number between 0 and RAND_MAX to a number between 0 and the scaling factor • Example i = rand() % 6 + 1; • Generates a number between 1 and 6

  9. 1. Define loop Output random number Program Output 1 // Fig. 3.7: fig03_07.cpp 2 // Shifted, scaled integers produced by 1 + rand() % 6 Notice rand() % 6 . This returns a number between 0and 5 (scaling). Add 1 to get a number between 1and6. 3 #include <iostream> Executing the program again gives the same "random" dice rolls. 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 #include <cstdlib> 13 14 int main() 15 { 16 for ( int i = 1; i <= 20; i++ ) { 17 cout << setw( 10 ) << ( 1 + rand() % 6 ); 18 19 if ( i % 5 == 0 ) 20 cout << endl; 21 } 22 23 return 0; 24 } Program to roll dice 5 5 3 5 5 2 4 2 5 5 5 3 2 2 1 5 1 4 6 4

  10. Recursion • Example: factorial (Mathematical formulas are often expressed recursively) • Definition: 3! = 3*2*1 = 6 • Recursion expression: 3! = 3*2! 2! = 2*1! 1! = 1 • N! can be expressed recursively as: N! = N * (N-1)! recursive case 1! = 1 base case • The factorial is defined in terms of another factorial until the base case of 1! is reached

  11. Recursion A recursive solution to the factorial problem is defined by the following function called factorial: int factorial (int number) { //base case if (number == 1) return 1; //Recursive step else return number * factorial (number - 1); }

  12. 1.4 If r = 5, what is value returned by fibo function?int fibo(int r){if(r == 0 || r== 1) return r;elsereturn fibo(r-1) + fibo( r - 2);}(a) 0(b) 2(c) 3(d) 5d

  13. References and Reference Parameters 3 ways to pass arguments to functions - 2 considered here and a third later Pass by value: Input values from calling function are not changed on return from called function Copy of data passed to function Changes to copy do not change original Used to prevent unwanted side effects Pass by reference: Arguments are referenced by their address and changes to contents of these addresses means the values in calling function are changed Function can directly access data Changes affect original

  14. Function arguments #include <vcl\condefs.h> #include <iostream.h> //Args2.cpp void SwapbyValue( float x, float y); void SwapbyReference( float &x, float &y); int main(void) { char screenoff; float a=1.0, b=2.0; cout << "a = " << a << " b = " << b << endl; SwapbyValue (a, b); cout <<" Swap by Value\n"; cout << "a = " << a << " b = " << b << endl; SwapbyReference (a, b); cout <<" Swap by Reference\n"; cout << "a = " << a << " b = " << b << endl; cin >> screenoff; return 0; } void SwapbyValue( float x, float y) { float tmp; tmp = x; x = y; y = tmp; } void SwapbyReference( float &x, float &y) { float tmp; tmp = x; x = y; y = tmp; }

  15. Review (Week4)- Arrays Arrays Passing Arrays to Functions Sorting Arrays Searching Arrays: Linear Search and Binary Search

  16. Passing Arrays to Functions If array HourlyTemp has been declared as: Int HourlyTemp[24] the function call modifyArray (HourlyTemp, 24 ); passes array HourlyTemp and its size to function modifyArray C++ pass arrays to functions using simulated pass-by-reference --- the called function can modify the element values in the callers’ original arrays. The value of the name of the array is the address in the computer’s memory of the first element of the array.

  17. Passing Arrays to FunctionsFunction prototype • The function header for function modefyArray might be written as: void modifyArray (int b[], int arraySize ); • take an integer array and a single integer; • indicating that modifyArray expects to receive the address of an array of integers in parameter b and the number of array elements in parameter arraySize. • Note the strange appearance if the function prototype for modifyArray Void modifyArray (int [], int); Names optional in prototype

  18. Passing Arrays to Functions • Arrays passed-by-reference • Functions can modify original array data • Value of name of array is address of first element • Function knows where the array is stored • Can change original memory locations • Individual array elements passed-by-value • Like regular variables • square( myArray[3] );

  19. Sorting Arrays • Sorting data • is an Important computing application • Virtually every organization must sort some data • Massive amounts must be sorted • Bubble sort (sinking sort) • Several passes through the array • Successive pairs of elements are compared • If increasing order (or identical), no change • If decreasing order, elements exchanged • Repeat these steps for every element • If there are n elements, only n-1 passes are needed to sort the n element and only n-1 comparisons are needed for each pass.

  20. Sorting Arrays • Example: • Go left to right, and exchange elements as necessary • On the first pass, the largest value sink to the bottom element; • …… • Original: 3 4 2 7 6 • Pass 1: 3 2 46 7(elements exchanged) • Pass 2: 2 3 4 6 7 • Pass 3: 2 3 4 6 7 (no changes needed) • Pass 4: 2 3 4 6 7 • Small elements "bubble" to the top (like 2 in this example)

  21. Searching Arrays: Linear Search • Search array for a key value • Linear search • Compare each element of array with key value • Useful for small and unsorted arrays • Inefficient Key (8) compare with ... a[1], a[2], a[3], a[4], … , a[n-1], a[n] 2 6 4 8 89 37

  22. Searching Arrays: Binary Search • Binary search • Only used with sorted arrays • Compare middle element with key • If equal, match found • If key < middle • Repeat search on first half of array • If key > middle • Repeat search on last half • Very fast • At most N steps, where 2 > # of elements • 30 element array takes at most 5 steps 2 > 30 N 5

  23. Review (Week5)- Pointers and Strings Pointer Variable Calling Functions by Reference Relationship Between Pointers and Arrays

  24. count 7 7 Pointer • Pointer variables • Contain memory addresses as values • Normally, variable contains specific value (direct reference) • Pointers contain address of variable that has specific value (indirect reference) countPtr count 600000 500000

  25. Pointer Declarations • * indicates variable is pointer int *myPtr; declares pointer to int, pointer of type int * • Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; • Can declare pointers to any data type float *floatPtr;

  26. Calling Functions by Reference • 3 ways to pass arguments to function • Pass-by-value • Pass-by-reference with reference arguments • Pass-by-reference with pointer arguments • Arguments passed to function using reference arguments • Modify original values of arguments

  27. Function arguments #include <vcl\condefs.h> #include <iostream.h> //Args2.cpp void SwapbyValue( float x, float y); void SwapbyReference( float *x, float *y); int main(void) { char screenoff; float a=1.0, b=2.0; cout << "a = " << a << " b = " << b << endl; SwapbyValue (a, b); cout <<" Swap by Value\n"; cout << "a = " << a << " b = " << b << endl; SwapbyReference (&a, &b); cout <<" Swap by Reference\n"; cout << "a = " << a << " b = " << b << endl; cin >> screenoff; return 0; } void SwapbyValue( float x, float y) { float tmp; tmp = x; x = y; y = tmp; } void SwapbyReference( float *x, float *y) { float tmp; tmp = *x; *x = *y; *y = tmp; }

  28. location 3000 3004 3008 3012 3016 pointer variable vPtr v[0] v[1] v[2] v[4] v[3] Pointer Expressions and Pointer Arithmetic • Pointer arithmetic • Increment/decrement pointer (++ or --) • Add/subtract an integer to/from a pointer( + or += , - or -=) • Pointers may be subtracted from each other • Pointer arithmetic meaningless unless performed on pointer to array • 5 element int array on a machine using 4 byte ints • vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000 • vPtr += 2; sets vPtr to 3008 vPtr points to v[ 2 ] V[5]

  29. Relationship Between Pointers and Arrays • Array and Point may be used almost interchangeable • Arrays and pointers closely related • Array name like constant pointer • Pointers can do array subscripting operations • Assume • int b[5]; • int *bPtr; bPtr = b; bPtr = &b[0]; &b[3] bPtr+3 Array name (without a subscript)is a pointer to the first element of the array.

  30. Relationship Between Pointers and Arrays int b[]= {10,20,30,40}; • Four notation for referring to array elements • Array subscript notation b[n] e.g. b [0] = 10 b [1] = 20 b [2] = 30 b [3] = 40 • Point/offset notation where the pointer is array name *(b + n ) e.g. *(b + 0 ) = 10 *(b + 1 ) = 20 *(b + 2 ) = 30 *(b + 3 ) = 40 • Pointer subscript notation bPtr[n] e.g. bPtr[0] = 10 bPtr[1] = 20 bPtr[2] = 30 bPtr[3] = 40 • Point/offset notation *( bPtr + n ) e.g. *( bPtr + 0 ) = 10 *( bPtr + 1 ) = 20 *( bPtr + 2 ) = 30 *( bPtr + 3 ) = 40

  31. Assuming a is an integer array of 7 items and aptr is a pointer to the array. Which of the following addresses the 4th item of the array? (a) a[4](b) *aptr(c) &a[3](d) *(aptr+4)c

  32. Review (Week6)- Classes andData Abstraction Structure Class Initializing Class Objects: Constructors

  33. Structure tag Structure members Structure Definitions • Structures • Aggregate data types built using elements of other types struct Time { int hour; int minute; int second; }; • Structure member naming • In same struct: must have unique names • In different structs: can share name • struct definition must end with semicolon

  34. Structure Definitions • struct definition • Creates new data type used to declare variables • Structure variables declared like variables of other types • Examples: • Time timeObject; • Time timeArray[ 10 ]; • Time *timePtr; • Time &timeRef = timeObject;

  35. Accessing Structure Members • Member access operators • Dot operator (.) accesses a structure or a class members via the variable name for the object or via a reference to the object. cout << timeObject.hour; cout << timeRef.hour; • Arrow operator (->) accesses a structure or a class members via pointer to object cout << timePtr->hour; • timePtr->hour same as ( *timePtr ).hour • Parentheses required • * lower precedence than .

  36. // example about structures#include <iostream>using namespace std;struct movies { string title; int year;} ;int main (){ movies mine; mine.title = "2001 A Space Odyssey"; mine.year = 1968; cout << "My favorite movie is:\n ";cout << mine.title; cout << " (" << mine.year << ")\n"; return 0;} My favorite movie is: 2001 A Space Odyssey (1968)

  37. // example: class constructor#include <iostream>using namespace std;class CRectangle { int width, height; public: CRectangle (int=5,int=5); int area (void) {return (width*height);}};CRectangle::CRectangle (int a, int b) { width = a; height = b;}int main () { CRectangle recta (3,4); CRectangle rectb; CRectangle rectc(3); cout << "recta area: " << recta.area() << endl; cout << "rectb area: " << rectb.area() << endl; cout << "rectc area: " << rectc.area() << endl; return 0;} recta area: 12 rectb area: 25 rectc area: 15

  38. Review (Week7)- Classes Part II Composition: Objects as Members of Classes Dynamic Memory static Class Members Operator Overloading

  39. Dynamic Memory Management with Operators new and delete ??? To use pointers you much follow four steps: • Declare the pointer variable Int *FredsPtr; • Reserve a space in memory for the value FredsPtr = new int; • Assign a value for the pointer *FredsPtr = 30; • Use delete to free the memory Delete FredsPtr; FredsPtr FredsPtr *FredsPtr FredsPtr ??? FredsPtr

  40. Dynamic Memory Management with Operators new and delete • new 1. Can declare and reserve a space in one line: Int *FredsPtr = new int; Int *FredsPtr; FredsPtr = new int; 2. Providing initializers double *ptr = new double( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 ); 3. Allocating arrays int *gradesArray = new int[ 10 ];

  41. Dynamic Memory Management with Operators new and delete The NULL pointer Int main() { Int *FredsPtr = NULL; if (FredsPtr = = NULL){ // if the pointer is NULL FredsPtr = new int; //then create a new pointer *FredsPtr = 30; //and give it a value } } FredsPtr *FredsPtr FredsPtr

  42. #include <iostream> • using namespace std; • int main () • { • int i,n; • int * p; • cout << "How many numbers would you like to type? "; • cin >> i; • p= new int[i]; • if (p == 0) • cout << "Error: memory could not be allocated"; • else • { • for (n=0; n<i; n++) • { • cout << "Enter number: "; • cin >> p[n]; • } • cout << "You have entered: "; • for (n=0; n<i; n++) • cout << p[n] << ", "; • delete[] p; • } • return 0; • } • Declare the pointer variable • Reserve a space in memory for the value • Assign a value for the pointer • Use delete to free the memory How many numbers would you like to type? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32,

  43. Operator Overloading • Types • Built in (int, char) or user-defined • Can use existing operators with user-defined types • Cannot create new operators • Overloading operators • Create a function for the class • Name function operator followed by symbol • Operator+ for the addition operator +

  44. Operator Overloading • C++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example: int a, b, c; a = b + c; This is obviously valid code in C++, since the different variables of the addition are all fundamental types. • Nevertheless, it is not so obvious that we could perform an operation similar to the following one: struct { string product; float price; } a, b, c; a = b + c; In fact, this will cause a compilation error. However, we can design classes able to perform operations using standard operators.

  45. // vectors: overloading operators example #include <iostream> using namespace std;  class CVector { public: int x,y; CVector (int=0, int=0); CVector operator + (CVector); };  CVector::CVector (int a, int b) { x = a; y = b; }  CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); }  int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } CVector (int, int); // function name CVector (constructor) CVector operator+ (CVector); // function returns a CVector type operator sign (parameters) { /*...*/ } c = a + b; c = a.operator+ (b); 4,3

  46. // operator_overloading.cpp #include <iostream> using namespace std; class Complex { public: Complex( double r, double i ) : re(r), im(i) { } Complex operator-( Complex &other ); void Display( ) { cout << re << ", " << im << endl; } private: double re, im; }; // Operator overloaded using a member function Complex Complex::operator-( Complex &other ) { return Complex( re - other.re, im - other.im ); } int main() { Complex a = Complex( 1.2, 3.4 ); Complex b = Complex( 5.6, 7.8 ); Complex c = Complex( 0.0, 0.0 ); c = a - b; c.Display(); } c = a - b; c = a.operator- (b); -4.4, -4.4

  47. Review (Week8)_Inheritance Base Classes and Derived Classes

  48. 1 // Fig. 9.17: point3.h 2 // Point3 class definition represents an x-y coordinate pair. 3 #ifndefPOINT3_H 4 #definePOINT3_H 5 6 class Point3 { 7 8 public: 9 Point3( int = 0, int = 0 ); // default constructor 10 11 void setX( int ); // set x in coordinate pair 12 int getX() const; // return x from coordinate pair 13 14 void setY( int ); // set y in coordinate pair 15 int getY() const; // return y from coordinate pair 16 17 void print() const; // output Point3 object 18 19 private: 20 int x; // x part of coordinate pair 21 int y; // y part of coordinate pair 22 23 }; // end class Point3 24 25 #endif // default constructor Point3::Point3( int xValue, int yValue ) : x( xValue ), y( yValue ) { // empty body } // end Point3 constructor point3.h (1 of 1) Better software-engineering practice: private over protected when possible.

  49. 1 // Fig. 9.18: point3.cpp 2 // Point3 class member-function definitions. 3 #include <iostream> 4 5 using std::cout; 6 7 #include"point3.h" // Point3 class definition 8 9 // default constructor 10 Point3::Point3( int xValue, int yValue ) 11 : x( xValue ), y( yValue ) 12 { 13 // empty body 14 15 } // end Point3 constructor 16 17 // set x in coordinate pair 18 void Point3::setX( int xValue ) 19 { 20 x = xValue; // no need for validation 21 22 } // end function setX 23 Member initializers specify values of x and y. point3.cpp (1 of 2)

  50. 24 // return x from coordinate pair 25 int Point3::getX() const 26 { 27 return x; 28 29 } // end function getX 30 31 // set y in coordinate pair 32 void Point3::setY( int yValue ) 33 { 34 y = yValue; // no need for validation 35 36 } // end function setY 37 38 // return y from coordinate pair 39 int Point3::getY() const 40 { 41 return y; 42 43 } // end function getY 44 45 // output Point3 object 46 void Point3::print() const 47 { 48 cout << '[' << getX() << ", " << getY() << ']'; 49 50 } // end function print Invoke non-private member functions to access private data. point3.cpp (2 of 2)

More Related