Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.

Similar presentations


Presentation on theme: "Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays."— Presentation transcript:

1 Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

2 Starting Out with C++, 3 rd Edition 2 7.1 Arrays Hold Multiple values Unlike regular variables, arrays can hold multiple values.

3 Starting Out with C++, 3 rd Edition 3 Figure 7-1 int count Enough memory for 1 int 12345 float price Enough memory for 1 float 56.981 char letter Enough memory for 1 char A

4 Starting Out with C++, 3 rd Edition 4 Figure 7-2

5 Starting Out with C++, 3 rd Edition 5 Partial Array Initialization When an array is being initialized, C++ does not require a value for every element. int numbers[7] = {1, 2, 4, 8};

6 Starting Out with C++, 3 rd Edition 6 Table 7-1

7 Starting Out with C++, 3 rd Edition 7 Program 7-1 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element int array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees: "; cin >> hours[0]; cin >> hours[1]; cin >> hours[2]; cin >> hours[3];

8 Starting Out with C++, 3 rd Edition 8 Program continues cin >> hours[4]; cin >> hours[5]; cout << "The hours you entered are:"; cout << " " << hours[0]; cout << " " << hours[1]; cout << " " << hours[2]; cout << " " << hours[3]; cout << " " << hours[4]; cout << " " << hours[5] << endl; }

9 Starting Out with C++, 3 rd Edition 9 Figure 7-7

10 Starting Out with C++, 3 rd Edition 10 Program 7-2 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element short array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees: "; for (int count = 0; count < 6; count++) cin >> hours[count]; cout << "The hours you entered are:"; for (count = 0; count < 6; count++) cout << " " << hours[count]; cout << endl; }

11 Starting Out with C++, 3 rd Edition 11 Program 7-3 // This program asks the user for the number of hours worked // by 6 employees. It uses a 6-element short array to store the // values. #include void main(void) { short hours[6]; cout << "Enter the hours worked by six employees.\n"; for (int count = 1; count <= 6; count++) { cout << "Employee " << count << ": "; cin >> hours[count - 1]; } cout << "The hours you entered are\n";

12 Starting Out with C++, 3 rd Edition 12 Program continues for (count = 1; count <= 6; count++) { cout << "Employee " << count << ": "; cout << hours[count - 1] << endl; }

13 Starting Out with C++, 3 rd Edition 13 Figure 7-8

14 Starting Out with C++, 3 rd Edition 14 7.4 Array Initialization Arrays may be initialized when they are declared.

15 Starting Out with C++, 3 rd Edition 15 Program 7-5 // This program displays the number of days in each month. // It uses a 12-element int array. #include void main(void) { int days[12]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July

16 Starting Out with C++, 3 rd Edition 16 / This program displays the number of days in each month. // It uses a 12-element int array. #include main() {int days[12]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July days[7] = 31; // August days[8] = 30; // September days[9] = 31; // October days[10] = 30; // November days[11] = 31; // December for (int count = 0; count < 12; count++) { cout << "Month " << (count + 1) << " has "; cout << days[count] << " days.\n"; } system("pause"); }

17 Starting Out with C++, 3 rd Edition 17 Program 7-6 // This program displays the number of days in each month. // It uses a 12-element int array. #include main() { int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int count = 0; count < 12; count++) { cout << "MMonth " << (count + 1) << " has "; cout << days[count] << " days.\n"; } system("pause"); }

18 Starting Out with C++, 3 rd Edition 18 Program 7-7 // This program uses an array of ten characters to store the // first ten letters of the alphabet. The ASCII codes of the // characters are displayed. #include main() { char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; cout << "Character" << "\t" << "ASCII Code\n"; cout << "--------" << "\t" << "----------\n"; for (int count = 0; count < 10; count++) { cout << letters[count] << "\t\t"; cout << int(letters[count]) << endl; } system("pause"); }

19 Starting Out with C++, 3 rd Edition 19 Program 7-8 // This program has a partially initialized array. #include void main(void) { int numbers[7] = {1, 2, 4, 8}; // Initialize the // first 4 elements. cout << "Here are the contents of the array:\n"; for (int index = 0; index < 7; index++) cout << numbers[index] << endl; }

20 Starting Out with C++, 3 rd Edition Slide 7- 20 Default Values If too few values are listed in an initialization statement –The listed values are used to initialize the first of the indexed variables –The remaining indexed variables are initialized to a zero of the base type –Example: int a[10] = {5, 5}; initializes a[0] and a[1] to 5 and a[2] through a[9] to 0

21 Starting Out with C++, 3 rd Edition #include using namespace std; int main () { int a[20]; int i; for (i=0;i<20;++i) { a[i]=i+1; cout<<"a[i]="<<a[i]<<endl;} system("pause"); return 0; }

22 Starting Out with C++, 3 rd Edition #include using namespace std; int main (){ int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl<<x[I]<<"\t"<<y[I]; } system("pause"); return 0; }

23 Starting Out with C++, 3 rd Edition #include main () { int a[6]={40,60,50,70,80,90}; int I; for(I=0;I<6;I++) cout<<a[I]<<endl; //cout<<a[I]<<"\t"; system("pause"); return 0; }

24 Starting Out with C++, 3 rd Edition //initializing an array #include main() { int n[10]; int i; for(int i=0;i<10;i++) // initialize array n[i] = 0; cout << "Element”" << setw(13) << " value" << endl; // setw(13) 13 space for (i=0; i<10;i++) // print array // needs iomanip.h cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

25 Starting Out with C++, 3 rd Edition initialize elements of array n to 0 #include using namespace std; #include using std::setw; int main () { int n[ 10 ]; // n is an array of 10 integers // initialize elements of array n to 0 for ( int i = 0; i < 10; i++ ) { n[ i ] = i + 100; // set element at location i to i + 100 } cout << "Element" << setw( 13 ) << "Value" << endl; // output each array element's value for ( int j = 0; j < 10; j++ ) { cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl; } system("pause"); return 0; }

26 Starting Out with C++, 3 rd Edition initializing an array with a declaration #include main() { int Element,value,i; int n[10]={32,27,64,18,95,14,90,70,60,37}; cout << "Element”" << setw(13) << "“ value" << endl; for(i=0;i<10;i++) // print array cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

27 Starting Out with C++, 3 rd Edition compute the sum of the elements of the array // compute the sum of the elements of the array #include main() { const int arraysize =12; int a[arraysize] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int total=0; for(int i=0;i<arraysize ;i++) total+= a[i]; cout <<" total of array element valuesis " << total << endl; system("pause"); return 0; }

28 Starting Out with C++, 3 rd Edition // 2 array x,y=x*x #include main() { int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl <<x[I]<< " "<<y[I]; } system("pause"); return 0; }

29 Starting Out with C++, 3 rd Edition //multiply by *2 #include main() { //rscr(); int i; int a[5]={5,8,1,9,2}; for(i=0;i<=4;i++) {cout<<a[i]*2<<endl;} system("pause"); }

30 Starting Out with C++, 3 rd Edition #include main() { int i,n; int a[5]; cout<<"pls ent size arr: "<<setw(4); cin>>n; cout<<endl; for(i=1;i<=n;i++) {cout<<"enter number : "<<i<<" "<<setw(4); cin>>a[i]; cout<<i<<"*2="<<setw(4)<<a[i]*2<<endl;} system("pause"); }

31 Starting Out with C++, 3 rd Edition Pointer #include main() { int arr[3]; arr[0]=4; arr[1]=5; arr[2]=6; int *p; p=&arr[0]; cout<<"p= "<<*(p+1)<<endl; system("pause"); }

32 Starting Out with C++, 3 rd Edition 32 Implicit Array Sizing It is possible to declare an array without specifying its size, as long as you provide an initialization list. float ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

33 Starting Out with C++, 3 rd Edition Strings char string1[ ]="first"; Equal == char string1[ ]={'f','i','r','s','t','\o'}

34 Starting Out with C++, 3 rd Edition 34 Initializing With Strings When initializing a character array with a string, simply enclose the string in quotation marks: char name[] = “Warren”;

35 Starting Out with C++, 3 rd Edition 35 Figure 7-11

36 Starting Out with C++, 3 rd Edition Strcpy(string copy) #include main () { char x[]="Happy Hegrey year for All Muslem"; char y[25]; cout<<" The stringin array x is : "<< x << endl; cout<<" The stringin array y is: "<< strcpy(y,x) << endl; system("pause"); return 0; }

37 Starting Out with C++, 3 rd Edition #include main () { char s1[20]="computer"; char s2[ ]="science" ; cout<<"s1= " <<s1 << endl << "s2= " << s2 <<endl; cout<< "strcat(s1,s2) = " << strcat (s1, s2) << endl; system("pause"); return 0; }

38 Starting Out with C++, 3 rd Edition using strcmp( string copy ) // using strcmp #include int main () { char *s1 = "Saudia"; char *s2 = "Riyadh"; char *s3 = "Dirayah"; cout << "s1= " << s1<< endl<< "s2= " <<s2<<endl << "s3= " << s3<< endl<< endl<< "strcmp(s1, s2)= " << strcmp(s1, s2) <<endl<< "strcmp(s1, s3)= " << strcmp(s1, s3) <<endl<< "strcmp(s3, s1)= " << strcmp(s3, s1) <<endl<< endl; system("pause"); return 0; }

39 Starting Out with C++, 3 rd Edition 39 Program 7-9 // This program displays the contents of two char arrays. #include main() { char name1[] = "Holly"; char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'}; cout << name1 << endl; cout << name2 << endl; system("pause"); }

40 Starting Out with C++, 3 rd Edition 40 Program Output Holly Warren

41 Starting Out with C++, 3 rd Edition 41 7.5 Processing Array Contents Individual array elements are processed like any other type of variable.

42 Starting Out with C++, 3 rd Edition 42 Program 7-10 // This program stores, in an array, the hours worked by 5 // employees who all make the same hourly wage. #include main() { int hours[5]; float payRate; cout << "Enter the hours worked by 5 employees who all\n"; cout << "earn the same hourly rate.\n"; for (int index = 0; index < 5; index++) { cout << "Employee #" << (index + 1) << ": "; cin >> hours[index]; //system("pause"); } system("pause"); }

43 Starting Out with C++, 3 rd Edition 43 Program continues cout << "Enter the hourly pay rate for all the employees: "; cin >> payRate; cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < 5; index++) { float grossPay = hours[index] * payRate; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; }

44 Starting Out with C++, 3 rd Edition 44 Program 7-11 // This program stores, in an array, the hours worked by 5 // employees who all make the same hourly wage. It then // displays the gross pay, including any overtime. #include // Constant for defining the array size void main(void) { int hours[5]; float payRate; cout << "Enter the hours worked by 5 employees who all\n"; cout << "earn the same hourly rate.\n"; for (int index = 0; index < 5; index++) { cout << "Employee #" << (index + 1) << ": "; cin >> hours[index]; }

45 Starting Out with C++, 3 rd Edition 45 7.6 Focus on Software Engineering: Parallel Arrays By using he same subscript, you can build relationships between data stored in two or more arrays.

46 Starting Out with C++, 3 rd Edition 46 Program 7-12 // This program stores, in two arrays, the hours worked by 5 // employees, and their hourly pay rates. #include // Constant for defining the array size const int numEmps = 5; void main(void) { int hours[numEmps]; float payRate[numEmps]; cout << "Enter the hours worked by “ << numEmps << “ employees and their\n"; cout << "hourly rates.\n"; for (int index = 0; index < numEmps; index++) { cout << "hours worked by employee #" << (index + 1); cout << ": ";

47 Starting Out with C++, 3 rd Edition 47 Program continues cin >> hours[index]; cout << "Hourly pay rate for employee #"; cout << (index + 1) << ": "; cin >> payRate[index]; } cout << "Here is the gross pay for each employee:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); for (index = 0; index < numEmps; index++) { float grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; }

48 Starting Out with C++, 3 rd Edition 48 Program Output with Example Input Enter the hours worked by 5 employees and their hourly rates. hours worked by employee #1: 10 [Enter] Hourly pay rate for employee #1: 9.75 [Enter] hours worked by employee #2: 15 [Enter] Hourly pay rate for employee #2: 8.62 [Enter] hours worked by employee #3: 20 [Enter] Hourly pay rate for employee #3: 10.50 [Enter] hours worked by employee #4: 40 [Enter] Hourly pay rate for employee #4: 18.75 [Enter] hours worked by employee #5: 40 [Enter] Hourly pay rate for employee #5: 15.65 [Enter] Here is the gross pay for each employee: Employee #1: $97.50 Employee #2: $129.30 Employee #3: $210.00

49 Starting Out with C++, 3 rd Edition 49 7.7 Thou Shalt Not Assign You cannot use the assignment operator to copy one array’s contents to another. for (int count=0; count < 4; count++) newVal[count] = oldVal[count];

50 Starting Out with C++, 3 rd Edition 50 Table 7-2

51 Starting Out with C++, 3 rd Edition

52

53

54 Multi dimensional array int b[2][2]={{1,2},{3,4}}; b[1][1]=4, b[1][0]=3, b[0][1]=2, b[0][0]=1 54

55 Starting Out with C++, 3 rd Edition // using function in array #include int printArray(int [ ] [3]); int main( ) { int array1[2] [3] = { {1, 2, 3}, {4, 5, 6}}; int array2[2] [3] = {1, 2, 3, 4, 5}; int array3[2] [3] = { {1, 2}, {4} }; cout << "values in array1 by row are : " << endl; printArray(array1); cout << "values in array2 by row are : " << endl; printArray(array2); cout << "values in array3 by row are : " << endl; printArray(array3); system("pause"); return 0; } int printArray(int a[ ][3]){ //int i,j; for(int i=0;i<2;i++) { for(int j=0;j<3;j++) cout << a[i][j] <<" "; cout <<endl; }} 55

56 Starting Out with C++, 3 rd Edition Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of rows and columns: const int NUMROWS = 3; const int NUMCOLS = 7; int Array[NUMROWS][NUMCOLS]; Array[2][5] 3 rd value in 6 th column Array[0][4] 1 st value in 5 th column The declaration must specify the number of rows and the number of columns, and both must be constants. 0123456 041893-460 1124574150980 284877567818579

57 Starting Out with C++, 3 rd Edition Processing a 2-D Array A one-dimensional array is usually processed via a for loop. Similarly, a two- dimensional array may be processed with a nested for loop: for (int Row = 0; Row < NUMROWS; Row++) { for (int Col = 0; Col < NUMCOLS; Col++) { Array[Row][Col] = 0; } Each pass through the inner for loop will initialize all the elements of the current row to 0. The outer for loop drives the inner loop to process each of the array's rows.

58 Starting Out with C++, 3 rd Edition Initializing in Declarations int Array1[2][3] = { {1, 2, 3}, {4, 5, 6} }; int Array2[2][3] = { 1, 2, 3, 4, 5 }; int Array3[2][3] = { {1, 2}, {4 } }; If we printed these arrays by rows, we would find the following initializations had taken place: Rows of Array1: 1 2 3 4 5 6 Rows of Array2: 1 2 3 4 5 0 Rows of Array3: 1 2 0 4 0 0 for (int row = 0; row < 2; row++) { for (int col = 0; col < 3; col++) { cout << setw(3) << Array1[row][col]; } cout << endl; }

59 Starting Out with C++, 3 rd Edition Higher-Dimensional Arrays An array can be declared with multiple dimensions. 2 Dimensional3 Dimensional Multiple dimensions get difficult to visualize graphically. double Coord[100][100][100];

60 Starting Out with C++, 3 rd Edition 2-D Arrays as Parameters When passing a two-dimensional array as a parameter, the base address is passed, as is the case with one-dimensional arrays. But now the number of columns in the array parameter must be specified. This is because arrays are stored in row-major order, and the number of columns must be known in order to calculate the location at which each row begins in memory: address of element (r, c) = base address of array + r*(number of elements in a row)*(size of an element) + c*(size of an element) void Initialize(int TwoD[][NUMCOLS], const int NUMROWS) { for (int i = 0; i < NUMROWS; i++) { for (int j = 0; j < NUMCOLS; j++) TwoD[i][j] = -1; }

61 Starting Out with C++, 3 rd Edition Data Types data type:a collection of values and the definition of one or more operations that can be performed on those values C++ includes a variety of built-in or base data types: short, int, long, float, double, char, etc. The values are ordered and atomic. C++ supports several mechanisms for aggregate data types: arrays, structures, classes. These allow complex combinations of other types as single entities. C++ also supports other mechanisms that allow programmers to define their own custom data types: enum types and typedef s.

62 Starting Out with C++, 3 rd Edition Array & Matrix in C ++ Dr. Ahmed Telba

63 Starting Out with C++, 3 rd Edition Slide 7- 63 Default Values If too few values are listed in an initialization statement –The listed values are used to initialize the first of the indexed variables –The remaining indexed variables are initialized to a zero of the base type –Example: int a[10] = {5, 5}; initializes a[0] and a[1] to 5 and a[2] through a[9] to 0

64 Starting Out with C++, 3 rd Edition Print array content #include using namespace std; int main () { int a[20]; int i; for (i=0;i<20;++i) { a[i]=i+1; cout<<"a[i]="<<a[i]<<endl;} system("pause"); return 0; }

65 Starting Out with C++, 3 rd Edition Math for array #include using namespace std; int main (){ int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl<<x[I]<<"\t"<<y[I]; } system("pause"); return 0; }

66 Starting Out with C++, 3 rd Edition Print in both vertical and horizontal #include main () { int a[6]={40,60,50,70,80,90}; int I; for(I=0;I<6;I++) cout<<a[I]<<endl; //cout<<a[I]<<"\t"; system("pause"); return 0; }

67 Starting Out with C++, 3 rd Edition Using iominip. Lib for set width(setw) an array #include main() { int n[10]; int i; for(int i=0;i<10;i++) // initialize array n[i] = 0; cout << "Element”" << setw(13) << " value" << endl; // setw(13) 13 space for (i=0; i<10;i++) // print array // needs iomanip.h cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

68 Starting Out with C++, 3 rd Edition initializing an array with a declaration #include main() { int Element,value,i; int n[10]={32,27,64,18,95,14,90,70,60,37}; cout << "Element”" << setw(13) << "“ value" << endl; for(i=0;i<10;i++) // print array cout << setw(7) <<i<<setw(13) <<n[i]<<endl; system("pause"); return 0; }

69 Starting Out with C++, 3 rd Edition compute the sum of the elements of the array // compute the sum of the elements of the array #include main() { const int arraysize =12; int a[arraysize] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int total=0; for(int i=0;i<arraysize ;i++) total+= a[i]; cout <<" total of array element valuesis " << total << endl; system("pause"); return 0; }

70 Starting Out with C++, 3 rd Edition Strings char string1[ ]="first"; Equal == char string1[ ]={'f','i','r','s','t','\o'}

71 Starting Out with C++, 3 rd Edition Strcpy(string copy) #include main () { char x[]="Happy Hegrey year for All Muslem"; char y[25]; cout<<" The stringin array x is : "<< x << endl; cout<<" The stringin array y is: "<< strcpy(y,x) << endl; system("pause"); return 0; }

72 Starting Out with C++, 3 rd Edition #include main () { char s1[20]="computer"; char s2[ ]="science" ; cout<<"s1= " <<s1 << endl << "s2= " << s2 <<endl; cout<< "strcat(s1,s2) = " << strcat (s1, s2) << endl; system("pause"); return 0; }

73 Starting Out with C++, 3 rd Edition using strcmp( string copy ) // using strcmp #include int main () { char *s1 = "Saudia"; char *s2 = "Riyadh"; char *s3 = "Dirayah"; cout << "s1= " << s1<< endl<< "s2= " <<s2<<endl << "s3= " << s3<< endl<< endl<< "strcmp(s1, s2)= " << strcmp(s1, s2) <<endl<< "strcmp(s1, s3)= " << strcmp(s1, s3) <<endl<< "strcmp(s3, s1)= " << strcmp(s3, s1) <<endl<< endl; system("pause"); return 0; }

74 Starting Out with C++, 3 rd Edition // copy content of Array #include main() { int x[5], y[5]; int I; for (I=0;I<5;++I) { x[I]=I; y[I]=I*I; cout<<endl <<x[I]<< " "<<y[I]; } system("pause"); return 0; }

75 Starting Out with C++, 3 rd Edition Pointer #include main() { int arr[3]; arr[0]=4; arr[1]=5; arr[2]=6; int *p; p=&arr[0]; cout<<"p= "<<*(p+1)<<endl; system("pause"); }

76 Starting Out with C++, 3 rd Edition //multiply by *2 #include main() { //rscr(); int i; int a[5]={5,8,1,9,2}; for(i=0;i<=4;i++) {cout<<a[i]*2<<endl;} system("pause"); }

77 Starting Out with C++, 3 rd Edition #include main() { int i,n; int a[5]; cout<<"pls ent size arr: "<<setw(4); cin>>n; cout<<endl; for(i=1;i<=n;i++) {cout<<"enter number : "<<i<<" "<<setw(4); cin>>a[i]; cout<<i<<"*2="<<setw(4)<<a[i]*2<<endl;} system("pause"); }

78 Starting Out with C++, 3 rd Edition // program to add matrix to another one #include using namespace std; int main() { int a[10][10],b[10][10],c[10][10]; int i,j,m,n; cout >m; cout >n; for(i=0;i<m;i++) for(j=0;j<n;j++) { cout >a[i][j]; cout >b[i][j]; c[i][j]=a[i][j]+b[i][j]; } for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<a[i][j]<<" "; cout<<"\n"; } cout<<"\n +\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<b[i][j]<<" "; cout<<"\n"; } cout<<"\n =\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<c[i][j]<<" "; cout<<"\n"; } system("pause"); return 0; }

79 Starting Out with C++, 3 rd Edition // program to add matrix to another one #include using namespace std; int main() { int a[10][10],b[10][10],c[10][10]; int i,j,m,n; cout >m; cout >n; for(i=0;i<m;i++) for(j=0;j<n;j++) { cout >a[i][j]; cout >b[i][j]; c[i][j]=a[i][j]-b[i][j]; } for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<a[i][j]<<" "; cout<<"\n"; } cout<<"\n +\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<b[i][j]<<" "; cout<<"\n"; } cout<<"\n =\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<c[i][j]<<" "; cout<<"\n"; } system("pause"); return 0;}

80 Starting Out with C++, 3 rd Edition //matrix multiplication #include using namespace std; #define M 20 int a[M][M],b[M][M],c[M][M];//all arrays' elements equal zero main() { int ma,na,mb,nb,i,j,k; /*ma=number of A rows,na=number of A columns, mb=number of B rows,nb=number of B columns, i,j,k:counters */ cout >ma>>na; cout >mb>>nb; if(na!=mb) cout<<"verify multiplication condition na=mb\n"; else { cout<<"enter A elements\n";//reading A elements for(i=0;i<ma;i++) for(j=0;j<na;j++) { cout >a[i][j];} cout<<"enter B elements\n";//reading B elements for(i=0;i<mb;i++) for(j=0;j<nb;j++) { cout >b[i][j];} for(i=0;i<ma;i++)//multiplication for(j=0;j<nb;j++) for(k=0;k<na;k++) c[i][j]+=(a[i][k]*b[k][j]); cout<<"the result C=\n\n"; for(i=0;i<ma;i++) {for(j=0;j<nb;j++) cout<<c[i][j]<<"\t"; cout<<"\n\n";} } system("pause"); }

81 Starting Out with C++, 3 rd Edition // string in Array #include using namespace std; void print(string m[],int n) { for(int i=0;i<n;i++) cout<<m[i]<<"\n"; } int main() { string months[12]={"January","February","March","April","May", "June","July","August","September","October","November","December"}; print(months,12); system("pause"); return 0; }

82 Starting Out with C++, 3 rd Edition String copy char mystring[6] = { 'H', 'e', 'l', 'l', 'o', '\0' }; char mystring[ ] = { 'H', 'e', 'l', 'l', 'o', '\0' }; // setting value to string #include using namespace std; int main () // null\0 end of char { char MyName[20]; strcpy (MyName,"Basil"); cout << MyName<<endl; system("pause"); return 0; }

83 Starting Out with C++, 3 rd Edition cin with strings // cin with strings #include using namespace std; int main () { char mybuffer [100]; cout << "What's your name?\n"; cin.getline (mybuffer,100); cout << "Hello " << mybuffer << ".\n"; cout << "Which is your favourite book?\n"; cin.getline (mybuffer,100); cout << "I like " << mybuffer << " too.\n"; system("pause"); return 0; }

84 Starting Out with C++, 3 rd Edition #include using namespace std; //Using function in Matrix void print(int a[][3]) { int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) cout<<a[i][j]<<"\t"; cout<<"\n\n"; } int main() { int X[3][3],i,j; int positives=0,negatives=0,zeros=0; int even=0,odd=0; for(i=0;i<3;i++) for(j=0;j<3;j++) { cout<<"X["<<i+1<<"]["<<j+1<<"]= "; cin>>X[i][j]; if(X[i][j]>0) positives++; if(X[i][j]<0) negatives++; if(X[i][j]==0) zeros++; if(X[i][j]%2==0) even++; if(X[i][j]%2!=0) odd++; } cout<<"\n"; print(X);//printing X cout<<"\nnumber of positive elements="<<positives; cout<<"\nnumber of negative elements="<<negatives; cout<<"\nnumber of zeroth elements="<<zeros; cout<<"\nnumber of even elements="<<even; cout<<"\nnumber of odd elements="<<odd; cout<<"\nleading diagonal: "; for(i=0;i<4;i++) cout<<X[i][i]<<"\t"; cout<<"\ncross diagonal: "; for(i=0;i<3;i++) { for(j=0;j<3;j++) if(i+j==3-1) cout<<X[i][j]<<"\t"; } cout<<endl; system("pause"); return 0; }

85 Starting Out with C++, 3 rd Edition Enumerated Types enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; enum Season {WINTER, SPRING, SUMMER, FALL}; enum Hemisphere {NORTH, SOUTH, EAST, WEST}; Month Mon; Season Period; Hemisphere Region;... if (Mon == JAN && Hemisphere == NORTH) Period = WINTER; An enumerated type is defined by giving a name for the type and then giving a list of labels, which are the only values that a variable of that type is allowed to have. Enumerated types allow the creation of specialized types that support the use of meaningful labels within a program. They promote code readability with very little overhead in memory or runtime cost. An enumerated type is allowed to have up to 256 values and a variable of an enumerated type will occupy one byte of memory. It is an error for the same label to be listed as a value for two different enumerated types.

86 Starting Out with C++, 3 rd Edition Designing with Enumerated Types Enumerated types provide a mechanism for the abstraction of real world entities. Enumerated type variables do not contain the character string of the value. The internal representation uses integer values; it is bad practice to rely on those values. Since the labels are logically constant values it is common to express them using all capital letters, just as for named constants. Enumerated type values cannot be read or (usefully) written directly. Enumerated type variables and values can be used in relational comparisons, in assignments and in switch statements as selectors and case labels. Enumerated type variables can be passed as parameters and used as the return value of a function. Good use of enumerated data types make the program more readable by providing a way to incorporate meaningful labels (thus easier to debug) and they help in self- documenting the program.

87 Starting Out with C++, 3 rd Edition C++ Simple Data Types enum –a user-defined data type –formed by listing identifiers

88 Starting Out with C++, 3 rd Edition Enumerated Types examples enum Birds {BLUEJAY, CARDINAL, ROBIN, SEAGULL}; enum LetterGrade {A, B, C, D, F}; Birds aBird; LetterGrade grade; Valid Statements aBird = ROBIN; grade = A; // does not contain the character ‘A’ if (grade = = B) ….;

89 Starting Out with C++, 3 rd Edition Enumerated Types in Arrays const int Numcities = 10; enum Climate {SUN, RAIN, FROST, SNOW}; Climate Weather[NumCities]; Valid assignments: Weather[0]=RAIN;. Weather[9]=SNOW; To set all cities to SUN: int wIndex; for (wIndex = 0; wIndex < Numcities; wIndex++) Weather[wIndex]=SUN;

90 Starting Out with C++, 3 rd Edition 90 7.8 Printing the Contents of an Array To display the contents of an array, you must use a loop to display the contents of each element. int array[5] = { 10, 20, 30, 40, 50 }; for (int count = 0; count < 5; count++) cout << array[count] << endl;

91 Starting Out with C++, 3 rd Edition 91 7.9 Arrays As Function Arguments To pass an array as an argument to a function, pass the name of the array.

92 Starting Out with C++, 3 rd Edition 92 Program 7-13 // This program demonstrates that an array element is passed // to a function like any other variable. #include void ShowValue(int);// Function prototype void main(void) { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; for (int Cycle = 0; Cycle < 8; Cycle++) ShowValue(collection[Cycle]); }

93 Starting Out with C++, 3 rd Edition 93 Program continues //************************************ // Definition of function showValue. * // This function accepts an integer argument. * // The value of the argument is displayed. * //************************************ void ShowValue(int Num) { cout << Num << " "; }

94 Starting Out with C++, 3 rd Edition 94 Program Output 5 10 15 20 25 30 35 40

95 Starting Out with C++, 3 rd Edition 95 Program 7-14 // This program demonstrates an array being passed to a function. #include void showValues(int []);// Function prototype void main(void) { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; showValues(collection); // Passing address of array collection } //*********************************************** // Definition of function showValues. * // This function accepts an array of 8 integers * // as its argument. The contents of the array * // is displayed. * //*********************************************** void showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; }

96 Starting Out with C++, 3 rd Edition 96 Program Output 5 10 15 20 25 30 35 40

97 Starting Out with C++, 3 rd Edition 97 Program 7-15 // This program demonstrates an array being passed to a function. #include void showValues(int []);// Function prototype void main(void) { int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16}; showValues(set1); cout << endl; showValues(set2); } //*********************************************** // Definition of function showValues. * // This function accepts an array of 8 integers * // as its argument. The contents of the array * // is displayed. * //*********************************************** void showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; }

98 Starting Out with C++, 3 rd Edition 98 Program Output 5 10 15 20 25 30 35 40 2 4 6 8 10 12 14 16

99 Starting Out with C++, 3 rd Edition Pointer #include main() { int arr[3]; arr[0]=4; arr[1]=5; arr[2]=6; int *p; p=&arr[0]; cout<<"p= "<<*(p+1)<<endl; system("pause"); }

100 Starting Out with C++, 3 rd Edition 100 Program 7-16 // This program uses a function that can display the contents // of an integer array of any size. #include void showValues(int [], int);// Function prototype void main(void) { int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int set2[4] = {2, 4, 6, 8}; int set3[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; showValues(set1, 8); cout << endl; showValues(set2, 4); cout << endl; showValues(set3, 12); }

101 Starting Out with C++, 3 rd Edition 101 Program continues //*********************************************** // Definition of function showValues. * // This function displays the contents of the * // array passed into nums. The value passed * // into elements is the number of elements in * // the nums array. * //*********************************************** void showValues(int nums[], int elements) { for (int index = 0; index < elements; index++) cout << nums[index] << " "; }

102 Starting Out with C++, 3 rd Edition 102 Program Output 5 10 15 20 25 30 35 40 2 4 6 8 1 2 3 4 5 6 7 8 9 10 11 12

103 Starting Out with C++, 3 rd Edition 103 Program 7-17 // This program uses a function that doubles the contents of // the elements within an array. #include void doubleArray(int [], int);// Function prototype const int arraySize = 12; void main(void) { int set[arraySize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; cout << "The arrays values are:\n"; for (int index = 0; index < arraySize; index++) cout << set[index] << " "; cout << endl; doubleArray(set, arraySize); cout << "After calling doubleArray, the values are:\n";

104 Starting Out with C++, 3 rd Edition 104 Program continues for (int index = 0; index < arraySize; index++) cout << set[index] << " "; cout << endl; } //************************************************** // Definition of function doubleArray. * // This function doubles the value of each element * // in the array passed into nums. * // The value passed into size is the number of * // elements in the nums array. * //************************************************** void doubleArray(int nums[], int size) { for (int index = 0; index < size; index++) nums[index] *= 2; }

105 Starting Out with C++, 3 rd Edition 105 Program Output The array values are: 1 2 3 4 5 6 7 8 9 10 11 12 After calling doubleArray, the values are: 2 4 6 8 10 12 14 16 18 20 22 24

106 Starting Out with C++, 3 rd Edition 106 7.10 Two-dimensional Arrays A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.

107 Starting Out with C++, 3 rd Edition 107 Program 7-18 // This program demonstrates a two-dimensional array. #include void main(void) { float sales[3][4]; // 2D array, 3 rows and 4 columns. float totalSales = 0;// To hold the total sales. int dir, qtr;// Loop counters.

108 Starting Out with C++, 3 rd Edition 108 Program continues cout << "This program will calculate the total sales of\n"; cout << "all the company's divisions.\n"; cout << "Enter the following sales information:\n\n"; // Nested loops to fill the array with quarterly // sales figures for each division. for (div = 0; div < 3; div++) { for (qtr = 0; qtr < 4; qtr++) { cout << "Division " << (div + 1); cout << ", Quarter " << (qtr + 1) << ": $"; cin >> sales[div][qtr]; } cout << endl; // Print blank line. }

109 Starting Out with C++, 3 rd Edition 109 Program continues // Nested loops to add all the elements. for (div = 0; div < 3; div++) for (qtr = 0; qtr < 4; qtr++) totalSales += sales[div][qtr]; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "The total sales for the company are: $"; cout << totalSales << endl; }

110 Starting Out with C++, 3 rd Edition 110 Program Output with Example Input This program will calculate the total sales of all the company's divisions. Enter the following sales information: Division 1, Quarter 1: $31569.45 [Enter] Division 1, Quarter 2: $29654.23 [Enter] Division 1, Quarter 3: $32982.54 [Enter] Division 1, Quarter 4: $39651.21 [Enter] Division 2, Quarter 1: $56321.02 [Enter] Division 2, Quarter 2: $54128.63 [Enter] Division 2, Quarter 3: $41235.85 [Enter] Division 2, Quarter 4: $54652.33 [Enter]

111 Starting Out with C++, 3 rd Edition 111 Output continues Division 3, Quarter 1: $29654.35 [Enter] Division 3, Quarter 2: $28963.32 [Enter] Division 3, Quarter 3: $25353.55 [Enter] Division 3, Quarter 4: $32615.88 [Enter] The total sales for the company are: $456782.34

112 Starting Out with C++, 3 rd Edition 112 Passing Two-dimensional Arrays to Functions When a two-dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns.

113 Starting Out with C++, 3 rd Edition 113 7.11 Arrays of Strings A two-dimensional array of characters can be used as an array of C-strings.

114 Starting Out with C++, 3 rd Edition 114 Program 7-20 // This program displays the number of days in each month. // It uses a two-dimensional character array to hold the // names of the months and an int array to hold the number // of days. #include void main(void) { char months[12][10] = {"January", "February", "March", "April", "May", "June", "July", "August", "September”, "October", "November","December"}; int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int count = 0; count < 12; count++) { cout << months[count] << " has "; cout << days[count] << " days.\n"; } }

115 Starting Out with C++, 3 rd Edition 115 Program 7-20 (continued) Program Output January has 31 days. February has 28 days. March has 31 days. April has 30 days. May has 31 days. June has 30 days. July has 31 days. August has 31 days. September has 30 days. October has 31 days. November has 30 days. December has 31 days.

116 Starting Out with C++, 3 rd Edition 116 Three Dimensional Arrays and Beyond C++ allows you to create arrays with virtually any number of dimensions. Here is an example of a three-dimensional array declaration: float seat[3][5][8];

117 Starting Out with C++, 3 rd Edition 117 7.14 Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms that you may use in your programs. These data types and algorithms are programmer- defined. They are not part of the C++ language, but were created in addition to the built-in data types.


Download ppt "Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays."

Similar presentations


Ads by Google