include iostream include iomanip include cmath using namespace

  • Slides: 113
Download presentation

#include <iostream> #include <iomanip> #include <cmath> using namespace std; void main() { double number;

#include <iostream> #include <iomanip> #include <cmath> using namespace std; void main() { double number; cout << "SIMPLE ARITHMETIC CALCULATOR" << endl; cout << "Enter the number you're using: "; cin >> number; cout. setf(ios: : fixed); cout. setf(ios: : showpoint); cout. precision(5); cout << endl << "ARITHMETIC RESULTS: " << endl; cout << "NUMBER: " << setw(10) << number << endl; cout << "NUMBER SQUARED: " << setw(10) << pow(number, 2) << endl; cout << "NUMBER CUBED: " << setw(10) << pow(number, 3) << endl; if (number >= 0. 0) cout << "SQUARE ROOT OF NUMBER: " << setw(10) << sqrt(number) << endl; if (number > 0. 0) { cout << "NATURAL LOG OF NUMBER: " << setw(10) << log(number) << endl; cout << "LOG (BASE 2) OF NUMBER: " << setw(10) << log(number) / log(2) << endl; } cout << "SINE OF NUMBER: " << setw(10) << sin(number) << endl; cout << "COSINE OF NUMBER: " << setw(10) << cos(number) << endl; cout << "FLOOR OF NUMBER: " << setw(10) << floor(number) << endl; cout << "CEILING OF NUMBER: " << setw(10) << ceil(number) << endl; cout << "ABSOLUTE VALUE OF NUMBER: " << setw(10) << fabs(number) << endl; cout << endl; return; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 4

Κλήση συναρτήσεων τύπου void main() { int value; int max = -1; int min

Κλήση συναρτήσεων τύπου void main() { int value; int max = -1; int min = INT_MAX; int total = 0; int count = 0; void Function Call print. Header(); cout << “Enter value: ”; cin >> value; while (value >= 0) { max = higher(value, max); min = lower(value, min); total += value; count++; cout << “Enter value: ”; cin >> value; Non-void Function Call } output. Results(max, min, average(total, count)); void Function Call return; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 Non-void Function Call 7

Παράδειγμα int power (int base, unsigned int exponent) { intresult = 1; for (int

Παράδειγμα int power (int base, unsigned int exponent) { intresult = 1; for (int i = 0; i < exponent; i++) result* = base; return result; } Κλήση Συνάρτησης #include <iostream. h> main (void) { cout << "2 ^ 8 = " << power(2, 8) << endl; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 9

#include <iostream. h> int power (int base, unsigned int exponent); // function declaration main

#include <iostream. h> int power (int base, unsigned int exponent); // function declaration main (void) { cout << "2 ^ 8 = " << power(2, 8) << 'n'; } int power (int base, unsigned int exponent) { int result = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 10

Παράδειγμα #include <iostream> using namespace std; inline double Sum(double * Numbers, int Count) {

Παράδειγμα #include <iostream> using namespace std; inline double Sum(double * Numbers, int Count) { double s = 0; for(int i = 0; i < Count; i++) s += Numbers[i]; return s; } int main() { double Nbr[] = { 15. 66, 18, 25, 128. 62, 12. 06, 22. 18 }; double Total = Sum(Nbr, 6); cout << "Sum = " << Total << endl; return 0; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 15

Παράδειγμα -1 //Using default arguments #include <iostream< using namespace std; //Calculate the volume of

Παράδειγμα -1 //Using default arguments #include <iostream< using namespace std; //Calculate the volume of a box int box. Volume(int length = 1, int width = 1 , int height = 1( } return length * width * height{ ; void main() } cout << "The default box volume is: "<< box. Volume() " >> nn. The volume of a box with length 10, n" " >> width 1 and height 1 is: "<< box. Volume(10( " >> nn. The volume of a box with length 10, n" " >> width 5 and height 1 is: "<< box. Volume(10, 5( " >> nn. The volume of a box with length 10, n" " >> width 5 and height 2 is: "< box. Volume(10, 5, 2( ' >> n; ' { ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 17

Παράδειγμα - 2 #include <iostream> using namespace std; void pass. Test (int & i)

Παράδειγμα - 2 #include <iostream> using namespace std; void pass. Test (int & i) { i++; i = 7; } void main ( ) { int j = 5; pass. Test(j); cout << j << endl; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 20

Παράδειγμα - 3 #include <iostream> using namespace std; void swap(int& x, int& y) {

Παράδειγμα - 3 #include <iostream> using namespace std; void swap(int& x, int& y) { int temp = x; x = y; y = temp; } void main() { int i = 1, j = 2; swap(i, j); cout << "i == " << i << ", j == " << j<<endl; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 21

#include <iostream> using namespace std; // Rectangle double Moment. Of. Inertia(double b, double h)

#include <iostream> using namespace std; // Rectangle double Moment. Of. Inertia(double b, double h) { return b * h * h / 3; } int main() { double Base, Height; cout << "Enter the dimensions of the Rectanglen"; cout << "Base: "; cin >> Base; cout << "Height: "; cin >> Height; cout << "n. Moment of inertia with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Base, Height) << "mm" << endl<<endl; return 0; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 26

#include <iostream> using namespace std; // Semi-Circle double Moment. Of. Inertia(double R) { const

#include <iostream> using namespace std; // Semi-Circle double Moment. Of. Inertia(double R) { const double PI = 3. 14159; return R * R * PI/ 8; } int main() { double Radius; cout << "nn. Enter the radius: "; cin >> Radius; cout << "Moment of inertia of a semi-circle with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Radius) << "mmnn"; return 0; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 28

#include <iostream> using namespace std; // Triangle double Moment. Of. Inertia(double b, double h,

#include <iostream> using namespace std; // Triangle double Moment. Of. Inertia(double b, double h, int) { return b * h * h / 12; } int main() { double Base = 7. 74, Height = 14. 38; cout << "Enter the dimensions of the trianglen"; cout << "Base: "; cin >> Base; cout << "Height: "; cin >> Height; cout << "n. Trianglen" << "Moment of inertia with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Base, Height, 1) << "mmnn"; return 0; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 30

int main() { double Length, Height, Radius; Get. Base(); Get. Height(); Get. Radius(); cout

int main() { double Length, Height, Radius; Get. Base(); Get. Height(); Get. Radius(); cout << "Enter the dimensions of the rectanglen"; Length = Get. Base(); Height = Get. Height(); cout << "Rectanglen"<< "Moment of inertia with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Length, Height) << "mmnn"; cout << "Enter the radius of the semi-circlen"; Radius = Get. Radius(); cout << "Semi-Circlen"<< "Moment of inertia with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Radius) << "mmnn"; cout << "Enter the dimensions of the trianglen"; Length = Get. Base(); Height = Get. Height(); cout << "n. Trianglen"<< "Moment of inertia with regard to the X axis: "; cout << "I = " << Moment. Of. Inertia(Length, Height, 1) << "mmn"; return 0; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 31

double Get. Base() { double B; cout << "Enter Base: "; cin >> B;

double Get. Base() { double B; cout << "Enter Base: "; cin >> B; return B; } double Get. Height() { double H; cout << "Enter Height: "; return H; cin >> H; } double Get. Radius() { double R; cout << "Enter Radius: "; return R; cin >> R; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 32

// Rectangle double Moment. Of. Inertia(double b, double h) { return b * h

// Rectangle double Moment. Of. Inertia(double b, double h) { return b * h * h / 3; } // Semi-Circle double Moment. Of. Inertia(double R) { const double PI = 3. 14159; return R * R * PI/ 8; } // Triangle double Moment. Of. Inertia(double b, double h, int) { return b * h * h / 12; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 33

Εκτέλεση του προγράμματος Enter the dimensions of the rectangle Enter Base: 18. 25 Enter

Εκτέλεση του προγράμματος Enter the dimensions of the rectangle Enter Base: 18. 25 Enter Height: 14. 15 Rectangle Moment of inertia with regard to the X axis: I = 17235 mm Enter the radius of the semi-circle Enter Radius: 15. 55 Semi-Circle Moment of inertia with regard to the X axis: I = 22960. 5 mm Enter the dimensions of the triangle Enter Base: 16. 35 Enter Height: 12. 75 Triangle Moment of inertia with regard to the X axis: I = 2824. 02 mm ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 34

Arrays hold multiple values Regular variables hold only one value at a time Regular

Arrays hold multiple values Regular variables hold only one value at a time Regular variable int count; count 5 Variable count stores one value of type int Size, must be literal constant Array variable Number of elements int days[ 3 ]; Allocates memory for 3 ints days 2 1 st element 3 2 nd element 4 3 rd element Array days stores 3 values of type int ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 37

Declaring Arrays To store 5 scores, declare an array consisting of five variables of

Declaring Arrays To store 5 scores, declare an array consisting of five variables of type int Declare array score[ 0 ] 1 st score int score [ 5 ]; score[ 1 ] score[ 2 ] 2 nd score 3 rd score[ 3 ] 4 th score[ 4 ] 5 th score The individual variables that together make up the array are called index variables or subscripted variables The number in square brackets is called an index or subscript Index variable (type int) score[ 2 ] Indexes are numbered starting with 0, not 1 The number of indexed variables in an array is called the declared size of the array Data type of indexed variables int score [ 5 ]; Size of array – 5 indexed variables ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 38

Arrays in Memory An array variable in memory is described by two pieces of

Arrays in Memory An array variable in memory is described by two pieces of information: An address in memory (location of the first byte of array variable) The data type of the array elements (how many bytes of memory are required for one variable of that data type) int arr[ 4 ]; Declare an array Reserves memory for 4 variables of type int memory (in bytes) Address of arr[ 0 ] 1023 1024. 2 bytes X 3 = 6 bytes. after start of arr[ 0 ]. . Address of arr[ 3 ] 1029 1030 Variables placed one after arr[ 0 ] the other in memory Remembers address of arr[ 0 ] arr[ 1 ] Each indexed variable is arr[ 2 ] 2 bytes each arr[ 3 ] Calculates address of others from arr[ 0 ] Size of array = size of element * number of elements 39

Referencing Arrays An index or subscript is used to access individual elements of an

Referencing Arrays An index or subscript is used to access individual elements of an array Index pinpoints a specific element int score[ 5 ]; score Declare array score Contains 5 elements 0 1 2 3 20 ? ? 30 4 Indexes ? Access a specific array element score [ 0 ] = 20; score [ 3 ] = 30; Access element at this index “score sub zero” is assigned 20 “score sub three” is assigned 30 ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 40

Referencing Arrays An indexed variable can be used any place that an ordinary variable

Referencing Arrays An indexed variable can be used any place that an ordinary variable of the same type can be used int score[ 5 ]; Declare array score [ 2 ] Indexed variable of type int “score sub two” cin >> score[ 2 ] >> score[ 4 ]; cout << score[ 2 ] << “ “ << score[ 4 ]; max = score[ 2 ] + score[ 4 ]; score[ 2 ] = 42; The index inside the square brackets can be any expression that evaluates to one of the integers 0 through one less than the size of the array int student = 2; Index is a variable score[ student ] = 99; Set value of score[2] to 99 cout << score[ student ] << “ “ << score[ 2 ]; Accessing the same indexed variable 41

for Loops with Arrays Use the for statement for array manipulations Step through all

for Loops with Arrays Use the for statement for array manipulations Step through all the indexed variables of an array named cur_array Loop control variable for ( int index = 0; index < Size_Of_Array; index++ ) { cur_array[ index ] = 100; cout << cur_array[ index ] << end; } for loop processes indexed variables of array score, score[ 0 ] through score[ 4 ] using loop control variable i Loop control variable int score[ 5 ]; for ( i = 0; i < 5; i++ ) cout << score[ i ] << “ off by “ << ( max - score[ i ] ) << endl; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 42

No Bounds Checking C++ does not perform array bounds checking Attempting to reference a

No Bounds Checking C++ does not perform array bounds checking Attempting to reference a nonexistent array index int arr[ 6 ]; Declare array with 6 elements Index variable, i must evaluate to one of six integers arr[ i ] 0, 1, 2, 3, 4, 5 arr[ i ] = 238; What if i has the value 7: arr[ 7 ] = 238 memory (in bytes) 1023 1024. Computer calculates. address of arr[ 7 ] 1033 1034. . Address of arr[ 7 ]. places 238 here. Address of arr[ 0 ] out of range arr[ 0 ]. . legal arr[ 5 ] arr[ 6 ] illegal access Could belong to some other arr[ 7 ] illegal access variable. 43.

Initializing Arrays Declaring and initializing an array Initialize all three indexed variables of the

Initializing Arrays Declaring and initializing an array Initialize all three indexed variables of the array a int a[ 3 ] = { 2, 1 }; int a[ 3 ]; is equivalent to: a[ 0 ] = 2; Values for indexed a[ 1 ] = 12; variables in order a[ 2 ] = 1; If initializing an array when it is declared, the size can be omitted Automatically sized int b[ ] = { 5, 12, 11 }; is equivalent to: int b[ 3 ] = { 5, 12, 11 }; Partial initialization If fewer values are listed than there are indexed variables, remaining indexed variables are initialized to zero of the array base type int c[ 5 ] = { 2, 4, 8 }; Only initializes first 3 2 4 elements of 5 element array Uninitialized elements 8 0 0 set to zero 44

Initializing Strings Initializing a character array with a string If string constant is used,

Initializing Strings Initializing a character array with a string If string constant is used, null terminator is automatically included Element data type Size can be omitted char short_str [ ] = “abc”; Sized automatically to length of string + 1 for the ‘’ Is equivalent to: char short_str [ 4 ] = “abc”; ‘a’ ‘b’ ‘c’ ‘’ Is not equivalent to: char short_str [ ] = {‘a’, ‘b’, ‘c’}; ‘a’ ‘b’ ‘c’ Character array also has indexed variables short_str[ 0 ] short_str[ 1 ] short_str[ 2 ]. . . int index = 0; Loop ends when element is while ( short_str [ index ] != ‘’ ) { Change value in short_str to short_str [ index ] = ‘X’; contain all ‘X’ characters index++; } ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 ΔΠΘ-ΤΜΗΜΑ 45

More Array Processing array elements is the same as processing other variables int score[

More Array Processing array elements is the same as processing other variables int score[ 5 ] = { 7, 8, 9, 10, 0 }; ++ score [ 2 ]; Increment value in score[ 2 ] int result = score [ 4 ] * 2; Initializes result to value of score[ 4 ] times 2 Array elements in relational expressions if ( score[ 3 ] < score[ 4 ] ) Is the value in score[ 3 ] less than the value in score[ 4 ]? Array elements used to control loops while ( score[ count ] != 0 ) Loop iterates as long as score[ count ] does not equal 0 ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 46

Parallel Arrays Parallel arrays: using two or more arrays to represent relationships involving different

Parallel Arrays Parallel arrays: using two or more arrays to represent relationships involving different data types Payroll program segments: const int NUMEMPS; Number of employees Stores hours worked Elements int hours [NUMEMPS]; by each employee are integers float pay. Rate [NUMEMPS]; Stores pay rate for Elements each employee are floats. . . for ( int index = 0; index < NUMEMPS; index++ ) { cout << “Hours employee #” << ( index + 1 ); cin >> hours[ index ]; cout << “Pay rate employee #” << ( index + 1 ); cin >> pay. Rate[ index ]; } Same index used to access both arrays ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 47

Printing Array Contents Use a loop to display the contents of each array element

Printing Array Contents Use a loop to display the contents of each array element Declare and int test. Arr [ 5 ] = { 10, 20, 30, 40, 50 }; initialize array Doesn’t work! cout << test. Arr << endl; Displays address of the array, not the contents Works! for ( int ct = 0; ct < 5; ct++ ) Loop displays value cout << test. Arr [ ct ] << endl; of each element Exception: Displaying the contents of a char array containing a C-string char name [ ] = “Ned Nerd”; Displays string, not cout << name << endl; array address cout uses when given a char array to determine end of the string ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 48

Array Elements as Function Arguments An array element can be an argument to a

Array Elements as Function Arguments An array element can be an argument to a function With each loop iteration, the value contained in test. Arr [ ct ] is passed to the function show. Val void show. Val ( int num ); Program output: void main ( ) 5 10 15 20 25 { int test. Arr [ 5 ] = { 5, 10, 15, 20, 25 }; for ( int ct = 0; ct < 5; ct++ ) show. Val ( test. Arr [ ct ] ); Array element, type int, as the argument } void show. Val ( int num ) Parameter is also type int { cout << num << “ “; } Array elements can be passed by value or by reference ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 49

Arrays as Function Arguments An entire array can be an argument to a function

Arrays as Function Arguments An entire array can be an argument to a function Any changes to parameter nums, effect argument test. Arr void show. Val ( int nums [ ] ); Accepts address of an array of integers as argument void main ( ) Program output: { 5 10 15 20 25 int test. Arr [ 5 ] = { 5, 10, 15, 20, 25 }; show. Val ( test. Arr ); Starting address of array is } passed to function show. Val void show. Val ( int nums [ ] ) Array passed by reference, { no & needed for ( int ct = 0; ct < 5; ct++ ) cout << nums [ ct ] << “ “; nums references test. Arr } 0 1 2 3 4 test. Arr 5 10 15 20 25 nums[0] nums[1] nums[2] nums[3] nums[4] 50

Arrays as Function Arguments Use two arguments: The address of the array The size

Arrays as Function Arguments Use two arguments: The address of the array The size of the array Modify function show. Val to display the contents of an int array of any size In main: int test. Arr 1 [ 2 ] = { 5, 10 }; int test. Arr 2 [ 5 ] = { 5, 10, 15, 20, 25 }; Declare and initialize arrays int test. Arr 3 [ 7 ] = { 5, 10, 15, 20, 25, 30, 35 }; show. Val ( test. Arr 1, 2 ); Function calls show. Val ( test. Arr 2, 5 ); to show. Val ( test. Arr 3, 7 ); New show. Val: Address of array Size of array void show. Val ( int nums [ ], int size ) { Use parameter to terminate loop for ( int ct = 0; ct < size; ct++ ) cout << nums [ ct ] << “ “; } 51

Arrays as Function Arguments Array parameters give direct access to the array argument void

Arrays as Function Arguments Array parameters give direct access to the array argument void double. Arr ( int nums [ ], int size ); void main ( ) { Program output: int test. Arr [ 5 ] = { 1, 2, 3, 4, 5 }; for ( int ct = 0; ct < 5; ct++ ) 1 2 3 4 5 cout << test. Arr [ ct ] << “ “; 2 4 6 8 10 double. Arr ( test. Arr, 5 ); for ( int ct = 0; ct < 5; ct++ ) cout << test. Arr [ ct ] << “ “; } void double. Arr ( int nums [ ], int size ) { for ( int i = 0; i < size; i++ ) Changes values in parameter nums and nums [ i ] *= 2; argument test. Arr } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 52

Partially Filled Arrays The exact size needed for an array is not always known

Partially Filled Arrays The exact size needed for an array is not always known when the program is written or the size may vary from one run to another Declare array to be the largest size the program could possibly need Use as much of the array as is needed, keep track of part used Function compute_ave returns the average of numbers a[ 0 ] through a[ number_used – 1 ] Partially filled array double compute_ave ( int a[ ], int number_used ) { How much of array is used double total = 0; for ( int index = 0; index < number_used; index++ ) total = total + a[ index ]; if ( number_used > 0 ) return ( total / number_used ); . . A variable similar to number_used must always be an argument to any function that manipulates a partially filled array 53

Two-dimensional Arrays Two-dimensional array is several identical arrays put together in the form of

Two-dimensional Arrays Two-dimensional array is several identical arrays put together in the form of a table Holds multiple sets of values Students row 0 Exam scores column 0 column 1 column 2 score[0][0] score[0][1] score[0][2] row 1 score[1][0] score[1][1] score[1][2] row 2 score[2][0] score[2][1] score[2][2] Number of rows Arrays of exam scores Number of columns float score [ 3 ]; Assign value to score [ 1 ] [ 2 ] = 93. 2; an element Row index cout << score [ 0 ] [ 2 ]; Display value of an element Column index First index represents the row position, second index represents the column position 54

Two-dimensional Arrays Nested loops are used to process each element of a two -dimensional

Two-dimensional Arrays Nested loops are used to process each element of a two -dimensional array float score [ 3 ]; for ( int std = 0; std < 3; std++ ) Outer loop iterates over rows { for ( int exam = 0; exam < 3; exam++ ) Inner loop iterates over columns { cout << “Student “ << std + 1 << “ , exam “ << exam + 1 << “: “; cin >> score [ std ] [ exam ]; Read in an exam score } Row Column Program output: cout << endl; index } Student 1, exam 1: 92. 3 score 0 1 2 Student 1, exam 2: 88. 5 0 92. 3 88. 5 83. 6 Student 1, exam 3: 83. 6 Student 2, exam 1: 79. 2 1 79. 2 72. 8 ? Student 2, exam 2: 72. 8 2 ? ? ? . . . 55

Two-dimensional Arrays as Function Arguments Number of columns is specified in a two-dimensional array

Two-dimensional Arrays as Function Arguments Number of columns is specified in a two-dimensional array parameter Empty Column index Number of rows void show. Arr ( int Arr [ ] [ 2 ], int rows ); void main ( ) Extra braces that enclose each { row’s values are optional int table [ 3 ] [ 2 ] = { { 8, 5 }, { 7, 9 }, { 6, 3 } }; show. Arr ( table, 3 ); Row 1 Row 2 Row 3 } void show. Arr ( int Arr [ ] [ 2 ], int rows ) { Program output: for ( int r = 0; r < rows; r++ ) Iterates rows { for ( int c = 0; c < 2; c++ ) Iterates columns 8 5 cout << Arr [ r ] [ c ] << “ “; 7 9 cout << endl; 6 3 } ΔΠΘ-ΤΜΗΜΑ 56 } ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02

Arrays Strings A two-dimensional array of characters can be used as multiple arrays of

Arrays Strings A two-dimensional array of characters can be used as multiple arrays of strings char team [ 4 ] [ 9 ] = { “Ned”, “Connie”, “Pat”, “Greg” }; 0 N e d 1 C o n n 2 P a t 3 G r e g Four names, 8 characters long i e Maximum length of string is 9 – 1 (for null terminator) Name of array with only a row index is the address of that row Pat cout << team [ 2 ]; Loop displays all names in the array for ( int ct = 0; ct < 4; ct++ ) cout << team [ ct ] << endl; Ned Connie Pat Greg Program output: 57

Strings I/O #include <iostream> using namespace std; char str[80]; void main() { cin >>

Strings I/O #include <iostream> using namespace std; char str[80]; void main() { cin >> str; // get string from user, store in str cout << str<<endl; // display string entered by user } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 63

 • το μέγεθος ενός πίνακα δεν μπορεί να αλλάζει κατά τη διάρκεια του

• το μέγεθος ενός πίνακα δεν μπορεί να αλλάζει κατά τη διάρκεια του προγράμματος int size = 80; char str[size]; cin. get(str, size); cout << str; // // array size define array get string from user display string • Χρήση const variables const int SIZE = 80; // array size: cannot be changed char str[SIZE]; // define array cin. get(str, SIZE); // get string from user cout << str; // display string ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 66

cout << “Enter the student's age: ”; cin >> age; // get a number

cout << “Enter the student's age: ”; cin >> age; // get a number cin. ignore(10, 'n'); // eat the newline cout << “Enter the student's name: ” cin. get(name, SIZE); // get a string ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 68

Συναρτήσεις βιβλιοθήκης για αλφαριθμητικά char s 1[] = “TMHMA”; cout << “Length of s

Συναρτήσεις βιβλιοθήκης για αλφαριθμητικά char s 1[] = “TMHMA”; cout << “Length of s 1 = ” <<strlen(s 1); char src[ ] = “TMHMA”; // string initialized to a value char dest[80]; // empty string variable strcpy(dest, src); // copies the contents of src into dest char s 1[80] = “POLYTEXNIKH”; char s 2[] = “SXOLH”; strcat(s 1, s 2); ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 69

char name[] = “Smith”; n 1 = strcmp(name, “Renaldo”); //returns 1 (first argument follows

char name[] = “Smith”; n 1 = strcmp(name, “Renaldo”); //returns 1 (first argument follows second) n 2 = strcmp(name, “Smith”); //returns 0 (first argument same as second) n 3 = strcmp(name, “Townsend”); //returns -1 (first argument precedes second) Η συνάρτηση stricmp( ) συγκρίνει αλφαριθμητικά αγνοώντας το ταίριασμα πεζών – κεφαλαίων χαρακτήρων ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 70

Πίνακες αλφαριθμητικών (arrays of strings) char names[5][10]; // array of 5 strings for(j=0; j<5;

Πίνακες αλφαριθμητικών (arrays of strings) char names[5][10]; // array of 5 strings for(j=0; j<5; j++) { cout << “Enter name (or press Enter to exit loop): ”; cin. get(names[j], 10); if( strlen(names[j])==0 ) // if user presses [Enter], break; // exit from loop } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 72

Αρχικοποίηση πίνακα (Initialize array of strings) const int MAX = 10; //maximum length of

Αρχικοποίηση πίνακα (Initialize array of strings) const int MAX = 10; //maximum length of day name +1 const int DPW = 7; // days per week const char day_name[DPW][MAX] = // array of day names { “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 73

Pointers, Arrays & Pointers, Dynamic Memory Allocation ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 74

Pointers, Arrays & Pointers, Dynamic Memory Allocation ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 74

Address Operator The address operator & returns the memory address of a variable A

Address Operator The address operator & returns the memory address of a variable A variable is allocated a section of memory large enough to hold a value of the variable’s data type int num; Memory Integer data type allocated 4 bytes num 1 byte Address 1201 The first byte allocated to variable num Get the address of variable num Address operator &num 1 byte Each byte of memory has a unique address Returns the address of num Display the address of variable num cout << &num; 75

Pointer Variables Pointer variables or pointers store memory addresses Using pointer variables to indirectly

Pointer Variables Pointer variables or pointers store memory addresses Using pointer variables to indirectly manipulate data stored in other variables Declare a pointer variable that stores the address of an integer variable int *ptr; “ptr is a pointer to an int” Store address of Identifier ( name) of an int data type Means it is a pointer variable int x = 25; int * ptr; ptr = &x; Pointer variable Assign address of x to pointer variable ptr cout << “Value in x “ << x << endl; cout << “Address of x “ << ptr << endl; Value in x 25 Address in x 0 x 07 e 00 Program output x Value of x 25 ptr Address of x 0 x 07 e 00 76

Indirection Operator The indirection operator dereferences the pointer A dereferenced pointer can change the

Indirection Operator The indirection operator dereferences the pointer A dereferenced pointer can change the value of the variable it is pointing to Program output: void main( ) Value in x twice 25 25 Value in x twice 100 { int x = 25; int * ptr; Declare pointer variable ptr = &x; Assign address of x Indirectly accesses value in variable x cout << “Value in x twice “ << x << ‘ ‘ << *ptr << endl; *ptr = 100; Stores 100 in x cout << “Value in x twice “ << x << ‘ ‘ << *ptr << endl; } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 77

Pointer Variables The value of one pointer variable can be assigned to another pointer

Pointer Variables The value of one pointer variable can be assigned to another pointer variable int *p 1, *p 2, v 1; Declare 2 pointer variables p 1 = &v 1; p 1 points to variable v 1 p 2 = p 1; Now p 2 also points to v 1 cout << *p 2; Outputs the value of v 1 Do not confuse p 1 = p 2 and *p 1 = *p 2 p 1 = p 2; p 1 The value of one pointer is assigned to another p 2 pointer p 1 84 p 2 99 Now p 1 points to the same thing as p 2 84 99 *p 1 = *p 2; The value of one variable is assigned the value of another variable Access the p 1 variables the pointers are p 2 pointing to 99 99

Arrays and Pointers An array name, without brackets and an index, is the starting

Arrays and Pointers An array name, without brackets and an index, is the starting address of the array – a pointer constant Dereference array name short nums[ ] = { 10, 20, 30, 40, 50 }; cout << “Value of first element is “ << *nums << endl; Program output: nums[0] nums[1] 10 20 Value of first element is 10 nums[2] 30 nums[3] nums[4] 40 nums (nums+1) (nums+2) (nums+3) Starting address of array and first element Equivalent expressions 50 (nums+4) nums[0] * nums Is actually: nums[1] * ( nums+1 ) * ( nums+1 * sizeof (short)) nums[2] * ( nums+2 ) * ( nums+2 * sizeof (short)) 79

Arrays and Pointers array [ index ] is equivalent to * ( array +

Arrays and Pointers array [ index ] is equivalent to * ( array + index ) Program output: 1 5 10 20 50 void main ( ) 1 5 10 20 50 { 1 5 10 20 50 int bills[ 5 ] = { 1, 5, 10, 20, 50 }, count; 1 5 10 20 50 int * ptr; Pointer variable to an int Assign address of bills array to pointer variable ptr = bills; for ( count = 0; count < 5; count++ ) Subscript notation cout << bills [ count ] << “ “; Using array name cout << endl; for ( count = 0; count < 5; count++ ) Subscript notation Using pointer variable cout << ptr [ count ] << “ “; cout << endl; for ( count = 0; count < 5; count++ ) Pointer notation cout << * ( bills + count ) << “ “; Using array name cout << endl; for ( count = 0; count < 5; count++ ) Pointer notation cout << * ( ptr + count ) << “ “; Using pointer variable } 80

Pointer Arithmetic Another method of moving through an array Pointer arithmetic offers a restricted

Pointer Arithmetic Another method of moving through an array Pointer arithmetic offers a restricted set of operations for manipulating the addresses in pointers Given a pointer a, a + n or a – n is a pointer to the value n elements away ( n is the offset from the original pointer ) If a is an array a[ 5 ] = { 2, 4, 6, 8, 22 }; a is a constant pointing to the first element a + 1 is a constant pointing to the second element (offset is 1) Add one element size from the current pointer value a Address = pointer a + (4 * size of element) a memory address 100 array a 2 a[ 0 ] or *(a + 0 ) a+1 104 4 a[ 1 ] or *( a + 1 ) a+2 108 6 a[ 2 ] or *( a + 2 ) a+3 112 8 a[ 3 ] or *( a + 3 ) a+4 116 22 a[ 4 ] or *( a + 4 ) ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 81

Pointer Arithmetic Addition and subtraction can be performed on pointer variables nums++ Add one

Pointer Arithmetic Addition and subtraction can be performed on pointer variables nums++ Add one element size to pointer nums- - Subtract one element size void main ( ) { from pointer cout << *nums; int set [ 5 ] = { 5, 10, 15, 20, 25 }; nums++; int * nums, index; Dereference pointer nums = set; for ( index = 0; index < 5; index++ ) display element value Pointer incremented to cout << *nums++ << “ “; point to next element cout << endl; for ( index = 0; index < 5; index++ ) cout << * - -nums << “ “; Pointer decremented to } Program output: 5 10 15 20 25 25 20 15 10 5 point to previous element Dereference pointer display element value nums - -; cout << *nums; 82

Initializing Pointers can be initialized at declaration time to the address of an existing

Initializing Pointers can be initialized at declaration time to the address of an existing object or variable Same type Not the same type int my. Value; Address of variable my. Value int * pint = &my. Value; Declaration and initialization int ages [ 20 ]; No & needed int * pint = ages; Array name is a pointer Already contains an address float my. Float; Error – incompatible types int * pint = &my. Float; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 83

Comparing Pointers can be compared using relational operators < > == != >= <=

Comparing Pointers can be compared using relational operators < > == != >= <= Array elements are stored in consecutive memory locations nums Addresses nums[0] nums[1] nums[2] nums[3] nums[4] 0 x 5 A 00 0 x 5 A 04 0 x 5 A 08 0 x 5 A 0 C 0 x 5 A 10 Compares addresses of array elements if ( &nums[1] > &nums[0] ) if ( nums == &nums[0] ) 0 x 5 A 04 > 0 x 5 A 00 ? 0 x 5 A 00 == 0 x 5 A 00 ? Compares the addresses stored in the pointer variables if ( ptr 1 < ptr 2 ) Compares the values that ptr 1 and ptr 2 point to if ( *ptr 1 < *ptr 2 ) Dereferencing operators 84

Pointers as Function Parameters Pointer parameters give functions access to the original variables used

Pointers as Function Parameters Pointer parameters give functions access to the original variables used as arguments Program output: void double. Value ( int * val ); Double num is 20 void main ( ) { Use address of operator int num = 10; Pass address of num to function double. Value ( &num ); cout << “Double num is “ << num << endl; } Pointer variable to an integer void double. Value ( int * val ) initialized to address of num { Multiplies the value of the variable * val *= 2; pointed to by val by 2, which is num } num val 10 20 85

Pointers as Function Parameters Pointers used as parameters can accept array addresses as arguments

Pointers as Function Parameters Pointers used as parameters can accept array addresses as arguments sales void get. Sales ( float * fptr ); fptr void main ( ) { float sales [4]; get. Sales ( sales ); Array name stores address. . . of beginning of array } void get. Sales ( float * fptr ) Pointer variable to a float initialized to beginning address of sales { for ( int ct = 0; ct < 4; ct++ ) Read values into array { elements using pointer fptr cout << “Enter sales amount: “; cin >> fptr [ ct ]; First * dereference fptr, read in value } Subscript Then ++ increment address in fptr } notation cin >> *fptr++; Pointer notation 86

Dynamic Memory Allocation Through the use of pointers, variables can be created and destroyed

Dynamic Memory Allocation Through the use of pointers, variables can be created and destroyed while the program is running Dynamically allocate memory for an int * iptr; Declare a pointer variable iptr = new int; Points to allocated Operator block of memory Pool of unused memory Request enough memory for an int Operand is a data type Store a value in the memory pointed to by iptr *iptr = 25; 0 x. A 652 25 Releasing a dynamically allocated variable iptr 0 x. A 652 delete iptr; Operator Frees the memory pointed to by iptr 87

Dynamic Memory Allocation Use the new operator to dynamically allocate an array Dynamically allocate

Dynamic Memory Allocation Use the new operator to dynamically allocate an array Dynamically allocate memory for a 100 element array int * iptr; Declare a pointer variable iptr = new int [100]; Request enough memory Element type for 100 ints Pool of unused memory Check if allocation was successful if ( iptr == NULL ) iptr will have a value of address 0 or NULL if not enough memory { cout << “Allocation error”; 0 x. A 652 return; Predefined constant } Store the value 1 in every array element iptr for ( int ct = 0; ct < 100; ct++ ) iptr [ ct ] = 1; Releasing a dynamically allocated array delete [ ] iptr; Frees the memory pointed to by iptr 0 x. A 652 1 1 1. . . 88

Dynamic Memory Allocation void main ( ) { float * sales; Pointer variable to

Dynamic Memory Allocation void main ( ) { float * sales; Pointer variable to a float int num. Days; cout << “Enter number of days: “; Ask user for size of array cin >> num. Days; sales points to starting address sales = new float [ num. Days ]; of allocated memory if ( sales == NULL ) Number of elements { Check if allocation was successful cout << “Error allocating memory”; return; } cout << “Enter sales for each dayn”; for ( int ct = 0; ct < num. Days; ct++ ) { Read values into array elements using cin >> sales [ ct ]; pointer sales in subscript notation. . delete [ ] sales; Free dynamically allocated memory 89 }

Abstract Data Types An abstraction is a model of something that includes only the

Abstract Data Types An abstraction is a model of something that includes only the general characteristics of an object Example: The term ‘dog’ is an abstraction It defines a general type of animal without specifying the detailed characteristics of any particular type of dog Abstract data types (ADTs) are data types created by the programmer ADTs have their own range (domain) of data and their own set of operations A structure is one way to create an abstract data type ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 91

Abstract Data Types (ADTs) Primitive data types are part of the C++ language bool

Abstract Data Types (ADTs) Primitive data types are part of the C++ language bool int char float double These data types define what values a variable may hold, and what operations may be performed on the values Example: Integer data types are not used to store fractional numbers Only the integer data types allow the modulus operator (% ) ADTs are composed of one or more primitive types Programmer decides what values are acceptable Programmer designs the set of operations to work on those values ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 92

Combining Data Use a structure when a relationship exists between items of different data

Combining Data Use a structure when a relationship exists between items of different data types Information between items of different data types Employee number Employee name Hours worked Hourly pay rate Gross pay int emp. Num; char name[ 25 ]; float hours; float pay. Rate; float gross. Pay Package employee information together in a structure C++ Keyword struct Pay. Roll Creates a data type called Pay. Roll { Tag int emp. Num; Opening brace char name[ 25 ]; Five members float hours; float pay. Rate; Closing brace float gross. Pay; with semicolon }; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 93

Declaring Structure Variables Each instance of the Pay. Roll structure contains its own set

Declaring Structure Variables Each instance of the Pay. Roll structure contains its own set of members New data type Name of data type struct Pay. Roll { int emp. Num; char name[ 25 ]; float hours; float pay. Rate; float gross. Pay; }; dept. Head emp. Num name hours pay. Rate gross. Pay Members Declare variables of type Pay. Roll dept. Head, shop. Emp; Structure variables are instances of Pay. Roll shop. Emp emp. Num name hours pay. Rate gross. Pay ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 94

Accessing Structure Members Use the dot operator (. ) to access individual members struct

Accessing Structure Members Use the dot operator (. ) to access individual members struct Pay. Roll { int emp. Num; char name[ 25 ]; Program output float hours, pay. Rate, gross. Pay; }; Enter employee number: 122 Enter employee name: Jane Java Enter number of hours and pay rate: void main( ) Instance of 40 25. 50 Pay. Roll { Gross Pay: $1020. 00 Pay. Roll emp 1; cout << “Enter employee number: “; cin >> emp 1. emp. Num; Read value into 25 cout << “Enter employee name: “; element character array cin. getline ( emp 1. name, 25 ); cout << “Enter number of hours and pay rate: n”; cin >> emp 1. hours >> emp 1. pay. Rate; emp 1. gross. Pay = emp 1. hours * emp 1. pay. Rate; 95. .

Initializing a Structure A structure variable can be initialized at declaration struct Geo. Info

Initializing a Structure A structure variable can be initialized at declaration struct Geo. Info Define data type Geo. Info { char city [ 30 ]; char state [ 3 ]; int distance; }; Instance of type Geo. Info Initial values Geo. Info location 1 = { “State College”, “PA”, 250 }; city member state member distance member Geo. Info location 2 = { “Harrisburg” }; Only initializes city member Location 2. state = “PA”; Location 2. distance = 310; Using assignment operator to initialize state and distance members ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 96

Arrays of Structures Declare a 100 element array of type Book. Info struct Book.

Arrays of Structures Declare a 100 element array of type Book. Info struct Book. Info Define data type Book. Info { char title [ 50 ]; int number; Number of elements float price; Array name }; Each element is a Book. Info book. List [ 100 ]; Book. Info structure Access each element of the array with a subscript book. List [ 5 ]. title Accesses the title member of element [ 5 ] Display the information of each array element for ( int index = 0; index < 100; index++ ) { cout << book. List [ index ]. title << endl; cout << book. List [ index ]. number << endl; cout << book. List [ index ]. price << end; ΔΠΘ-ΤΜΗΜΑ}ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 97

Nested Structures A structure variable can have another structure variable as a member struct

Nested Structures A structure variable can have another structure variable as a member struct Costs Declare nested structure first { float wholesale; Member of Item float retail; structure }; struct Item widget. pricing. retail { Dot Member of Costs char part. Num [ 10 ]; operators structure char description [ 25 ]; Costs pricing; Member is a }; Costs structure Item widget; widget. pricing. wholesale = 100. 0; widget. pricing. retail = 150. 0; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 98

Structures as Function Arguments Individual members as function arguments struct Rectangle { Function definition:

Structures as Function Arguments Individual members as function arguments struct Rectangle { Function definition: float mult ( float x, float y ) float length; float width; { float area; return x * y; Members as }; } arguments Rectangle box; box. area = mult ( box. length, box. width ); Entire structure variables as function arguments show. Rect ( box ); Structure variable as argument Parameter r is initialized to box’s member values Function definition: void show. Rect ( Rectangle r ) { cout << r. length << endl; cout << r. width << endl; cout << r. area << endl; } Display r’s members

Structures as Function Arguments Pass large structures by reference for better performance struct Rectangle

Structures as Function Arguments Pass large structures by reference for better performance struct Rectangle { float length; float width; float area; }; Argument is Rectangle box; init. Rect ( box ); modified by function Function definition: void init. Rect ( Rectangle &r ) { r. length = 10; Reference to box r. width = 5; r. area = r. length * r. width; } Initializes box’s members If passing data structures by reference only for efficiency, use the const modifier Function definition: show. Rect ( box ); With the const modifer, values of members cannot accidentally be modified void show. Rect ( const Rectangle &r ) Reference to box { cout << r. length << endl; cout << r. width << endl; cout << r. area << endl; }

Functions Returning Structures Functions can return a structure struct Circle { Returns an entire

Functions Returning Structures Functions can return a structure struct Circle { Returns an entire Function definition: float radius; Circle structure Circle init. Circle ( ) float diameter; { float area; Circle temp; Create a local }; temp. radius = 10. 0; Circle structure temp. diameter = 20. 0; Circle round; temp. area = 314. 159; round = init. Circle( ); return temp; Return value assigned to } a Circle structure Return local structure Limitation of value-returning function: returns only a single value By returning a structure, a value-returning function can return multiple values ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 101

Pointers to Structures struct Circle { float radius; float diameter; float area; }; Circle

Pointers to Structures struct Circle { float radius; float diameter; float area; }; Circle round; round cir. Ptr 0 x. A 604 radius diameter area Declare a pointer variable to a Circle structure Pointer Structure Circle *cir. Ptr; Pointer to a Circle structure Store address of a Circle structure in a pointer variable cir. Ptr = &round; Address of structure Pointer Accessing members of a structure through a pointer ( *cir. Ptr ). radius = 10; cir. Ptr->radius = 10; Dereferences only cir. Ptr Has higher precedence Structure pointer operator: special operator for dereferencing structure pointers 102

Pointers to Structures A pointer to a structure may be used as a function

Pointers to Structures A pointer to a structure may be used as a function Parameter is a pointer parameter to a Circle structure struct Circle { float radius; float diameter; float area; }; Circle round; init. Circle ( &round ); Argument is address of round c Function definition: void init. Circle ( Circle *c ) References round { c->radius = 10. 0; c->diameter = 20. 0; c->area = 314. 159; } round radius 0 x. A 604 10 diameter 20 area 314. 159 Accessing members of argument round 103

Pointers as Structure Members Structures can contain pointers as members struct Grade. Info {

Pointers as Structure Members Structures can contain pointers as members struct Grade. Info { char name [ 25 ]; int *test. Scores; Pointer to int array float average; }; student 1 name test. Scores 0 x. FB 304 average Grade. Info student 1; Dynamically allocate array. . student 1. test. Scores = new int [ num. Scores ]; 0 x. FB 304 for (int ct = 0; ct < num. Scores; ct++ ) { cout << “Enter test score: “; cin >> student 1. test. Scores [ ct ]; Read an integer into member test. Score total += student 1. test. Scores [ ct ]; indexed by ct } student 1. average = total / num. Scores; 104

Παράδειγμα #include <iostream> using namespace std; struct Grade. Info { char *name; // Student

Παράδειγμα #include <iostream> using namespace std; struct Grade. Info { char *name; // Student name int // Dynamically allocated array *test. Scores; float average; // Test average }; Grade. Info student, *st. Ptr; int num. Scores=5; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 110

void main() { st. Ptr=&student; student. name=“PRODUCTION_ENGINEERING”; float total=0. 0; student. test. Scores =

void main() { st. Ptr=&student; student. name=“PRODUCTION_ENGINEERING”; float total=0. 0; student. test. Scores = new int [num. Scores]; for (int ct = 0; ct < num. Scores; ct++ ) { cout << "Enter test score: "; cin >> student. test. Scores[ct]; total += student. test. Scores[ct]; } student. average = total / num. Scores; cout << "average ="<<student. average<<endl; for ( ct = 0; ct < num. Scores; ct++ ) { cout<<"ct="<<ct<<" -----"<<*st. Ptr->test. Scores<<endl; *st. Ptr->test. Scores++; } } ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 111

Παράδειγμα // specify a type enum days_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat

Παράδειγμα // specify a type enum days_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat }; days_of_week day 1, day 2; // create variables of that type day 1 = Mon; // give them values day 2 = Wed; ΔΠΘ-ΤΜΗΜΑ ΜΠΔ: ΑΝΤΙΚΕΙΜΕΝΟΣΤΡΑΦΗΣ ΠΡΟΓΡΑΜΜΑΤΙΣΜΟΣ /02 113