1 / 51

Chapter 6 - Arrays

Chapter 6 - Arrays. Chapter Objectives Introduce a way to store more than one value in a variable Introduce single dimensional arrays Explain how to declare arrays Explain how to initialize arrays Explain how to access arrays Explain how to pass arrays as parameters to functions

rasia
Télécharger la présentation

Chapter 6 - Arrays

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. Chapter 6 - Arrays • Chapter Objectives • Introduce a way to store more than one value in a variable • Introduce single dimensional arrays • Explain how to declare arrays • Explain how to initialize arrays • Explain how to access arrays • Explain how to pass arrays as parameters to functions • Introduce multidimensional arrays The C++ Coach - Essentials for Introductory Programming - 2000

  2. Chapter 6 - Arrays Have you noticed that so far we have only tracked one of everything in the programs we have written? //Example Grade Calculation without arrays #include <stdlib.h> #include <iostream.h> void main() { int Grade1, Grade2, Grade3, Grade4, Grade5; int Grade6, Grade7, Grade8, Grade9, Grade10; int Sum=0; cin>>Grade1; cin>>Grade2; cin>>Grade3; cin>>Grade4; cin>>Grade5; cin>>Grade6; cin>>Grade7; cin>>Grade8; cin>>Grade9; cin>>Grade10; Sum=Grade1 + Grade2 + Grade3 + Grade4 + Grade5 + Grade6 + Grade7 + Grade8 + Grade9 + Grade10; cout<<"The average of the following Grades = " <<Sum/10<<endl; cout<<Grade1<<endl; cout<<Grade2<<endl; cout<<Grade3<<endl; cout<<Grade4<<endl; cout<<Grade5<<endl; cout<<Grade6<<endl; cout<<Grade7<<endl; cout<<Grade8<<endl; cout<<Grade9<<endl; cout<<Grade10<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  3. Chapter 6 - Arrays 6.1 Declaring an Array What would happen if the previous program were for 100 grades and not 10? A lot of typing! That’s why C++ provides Arrays. An array is declared as follows: VariableType VariableName[Size]; If you want to declare (allocate) an array of 10 integers called Grades, you can do so as follows: int Grades[10]; To access an individual value in an array, you place the subscript of the value you wish to access in between the brackets. Index values are from 0 to the Size-1. This is one of the most confusing aspects of arrays. Observe how the array Grades would appear graphically: Array: Grades Index 0 1 2 3 4 5 6 7 8 9 Values ? ? ? ? ? ? ? ? ? ? The C++ Coach - Essentials for Introductory Programming - 2000

  4. Chapter 6 - Arrays 6.1 Declaring an Array Initially, there are no values in the array Grades. Arrays in C++ are uninitialized unless the user specifically specifies values to initialize it. One way to set individual values in an array is as follows. Observe the following code where each value in the array Grades is set: Grades[0]=100; Grades[1]=99; Grades[2]=97; Grades[3]=99; Grades[4]=100; Grades[5]=98; Grades[6]=97; Grades[7]=95 Grades[8]=97; Grades[9]=99; Individual elements in an array can be set by specifying the index with brackets and then assigning the value you wish to place in the array in the same manner as setting any other variable. Accessing values are equally easy. To display the first value, you would use the following code: cout<<Grades[0]; The C++ Coach - Essentials for Introductory Programming - 2000

  5. Chapter 6 - Arrays 6.1 Declaring an Array - Grade Calculation Example #include <stdlib.h> #include <iostream.h> void main() { int Grades[100]; int Sum=0; int LoopCounter; for(LoopCounter=0;LoopCounter<100;LoopCounter++) { cin>>Grades[LoopCounter]; Sum=Sum+Grades[LoopCounter]; } cout<<"The grades you just entered are:"<<endl; for(LoopCounter=0;LoopCounter<100;LoopCounter++) cout<<Grades[LoopCounter]<<'\t'; cout<<"Average = "<<Sum/100; } The C++ Coach - Essentials for Introductory Programming - 2000

  6. Chapter 6 - Arrays 6.1 Declaring an Array - Grade Calculation Example with Define #include <stdlib.h> #include <iostream.h> #define MaxSize 10 void main() { int Grades[MaxSize]; int Sum=0; int LoopCounter; for(LoopCounter=0;LoopCounter<MaxSize;LoopCounter++) { cin>>Grades[LoopCounter]; Sum=Sum+Grades[LoopCounter]; } cout<<"The Grades you just entered are:"<<endl; for(LoopCounter=0;LoopCounter<MaxSize;LoopCounter++) cout<<Grades[LoopCounter]<<'\t'; cout<<"Average = "<<Sum/MaxSize; } The C++ Coach - Essentials for Introductory Programming - 2000

  7. Chapter 6 - Arrays 6.1 Declaring an Array - Index Location Example #include <stdlib.h> #include <iostream.h> #define MaxSize 5 void main() { int LoopCounter; int Values[MaxSize]; values[0]=1; values[1]=2; values[2]=3; values[3]=4; values[4]=5; for(LoopCounter=0;LoopCounter<MaxSize;LoopCounter++) cout<<"The value at index = "<<LoopCounter<<" is "<< values[LoopCounter]<<endl; } Output: The value at index = 0 is 1 The value at index = 1 is 2 The value at index = 2 is 3 The value at index = 3 is 4 The value at index = 4 is 5 Index 0 1 2 3 4 Values 1 2 3 4 5 The C++ Coach - Essentials for Introductory Programming - 2000

  8. Chapter 6 - Arrays 6.1 Declaring an Array - Survey Example Let’s write a survey program that would count the number of responses. Each response is a number between 1 and 10. #include <stdlib.h> #include <iostream.h> #define NumRatings 10 #define NumResponses 20 void main() { int Rating[NumRatings]={0};//Initialize the entire array to zeros, // a shortcut to be explained later. int LoopCounter; int Response; //Loop thru 20 responses. for (LoopCounter=1; LoopCounter<=20;LoopCounter++) { cout<<"Enter your response"<<endl; cin>>Response; The C++ Coach - Essentials for Introductory Programming - 2000

  9. Chapter 6 - Arrays 6.1 Declaring an Array - Survey Example Continued // Note without check it may work, but you can write over memory if (response < 1 || response > NumRatings) cout<<"Bad response: "<<response<<endl; else ++Rating[Response-1]; } cout<<endl<<endl<<"Rating Number of responses"<<endl; cout<<"-------- -------------------"<<endl; for (LoopCounter = 0; LoopCounter<10;LoopCounter++) cout<<LoopCounter<<'\t'<<rating[LoopCounter-1]<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  10. Chapter 6 - Arrays 6.1 Declaring an Array - More Efficient Survey Example #include <stdlib.h> #include <iostream.h> #define NumRatings 10 #define NumResponses 20 void main() { //Initialize the entire array to zeros, now 11 items int Rating[11]={0}; int LoopCounter; int Response; //Loop thru 20 responses. for (LoopCounter=1; LoopCounter<=NumResponses;LoopCounter++) { cout<<"Enter your response"<<endl; cin>>Response; // Note without check it may work, but you can write over memory if (Response < 1 || Response > 10) cout<<"Bad response: "<<Response<<endl; else ++Rating[Response];//No longer require subtraction! } The C++ Coach - Essentials for Introductory Programming - 2000

  11. Chapter 6 - Arrays 6.1 Declaring an Array - More Efficient Survey Example Cont cout<<endl<<endl<<"Rating Number of responses"<<endl; cout<<"-------- -------------------"<<endl; //No longer require subtraction! for (LoopCounter = 1; LoopCounter<=10;LoopCounter++) cout<<LoopCounter<<'\t'<<Rating[LoopCounter]<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  12. Chapter 6 - Arrays 6.1 Declaring an Array - Incomplete Initialization Example #include <stdlib.h> #include <iostream.h> #define MaxSize 10 void main() { int Value[MaxSize]; int LoopCounter; Value[0] = 197; Value[2] = -100; Value[5] = 350; Value[3] = Value[0]+Value[5]; Value[9] = Value[5]/10; --Value[2]; for(LoopCounter=0;LoopCounter<10;LoopCounter++) cout<<Value[LoopCounter]<<endl; } Output: 197 ? -1 547 ? 350 ? ? ? 35 The C++ Coach - Essentials for Introductory Programming - 2000

  13. Chapter 6 - Arrays 6.2 Array Shortcuts C++ provides methods to improve the performance of initializing arrays. Observe the following inefficient example of using a loop to initialize an array: #define MaxSize 10 int LoopCounter; for(LoopCounter=0;LoopCounter<MaxSize;LoopCounter++) Values[LoopCounter]=0; A better way is to use a shorthand that C++ provides. See the following example as a way to initialize an array to 197, 0, -1, 547, 0, 350, 0, 0, 0, 35. int Values[MaxSize]={ 197, 0, -1, 547, 0, 350, 0, 0, 0, 35}; However, this really doesn't seem to help if you had an array of 1000 items. If you need to specify all 1000 items, then you must list each value. The C++ Coach - Essentials for Introductory Programming - 2000

  14. Chapter 6 - Arrays 6.2 Array Shortcuts Another shortcut that C++ provides allows the allocation of an array without specifying an exact size. This is handy if you are initializing many items and you do not wish to count up the number of items in between the curly braces. See the following example that allocates an array of 7 items from 1 through 7. int Values[] = {1,2,3,4,5,6,7}; //This will allocate the array as if 7 had been placed in the []. The C++ Coach - Essentials for Introductory Programming - 2000

  15. Chapter 6 - Arrays 6.2 Array Shortcuts - Drill 6-1 What is the output of the following code? #include <stdlib.h> #include <iostream.h> #define NumValues 10 void main() { int Values[NumValues] = {5,-2,0,1}; int LoopCounter; for(LoopCounter=0; LoopCounter<NumValues; LoopCounter++) cout<<Values[LoopCounter]<<endl; } Output: 5 -2 0 1 0 0 0 0 0 0 Index 0 1 2 3 4 5 6 7 8 9 Values 5 -2 0 1 0 0 0 0 0 0 The C++ Coach - Essentials for Introductory Programming - 2000

  16. Chapter 6 - Arrays 6.2 Array Shortcuts - Drill 6-2 What is the output of the following code? #include <stdlib.h> #include <iostream.h> #define NumValues 10 void main() { int Values[] = {5,-2,0,1}; int LoopCounter; for(int LoopCounter=0; LoopCounter<NumValues; LoopCounter++) cout<<Values[LoopCounter]<<endl; } Output: 5 -2 0 1 ? ? ? ? ? ? Index 0 1 2 3 4 5 6 7 8 9 Values 5 -2 0 1 ? ? ? ? ? ? The C++ Coach - Essentials for Introductory Programming - 2000

  17. Chapter 6 - Arrays 6.2 Array Shortcuts A programmer must be careful to only access values within the bounds of an array. The lowest index accessible in an array is 0. This is considered the array's lower bound. The highest index accessible in an array is one less than the size of the array. This is considered the array's upper bound. Programmer’s Notebook: It is important to note that you can not copy the contents of one array to the other by using an = operator. If you attempt to do this it will appear to work, however a true copy is not made. Try executing the following code: #include <stdlib.h> #include <iostream.h> #define ArraySize 5 void main() { int Source[ArraySize]={1,2,3,4,5}; int Destination[ArraySize]; int LoopCounter; The C++ Coach - Essentials for Introductory Programming - 2000

  18. Chapter 6 - Arrays 6.2 Array Shortcuts - Duplicate Code Example Continued //This does not copy the array Source to the array Destination. Destination=Source; //output both arrays, both have same values for(LoopCounter=0;LoopCounter<5;LoopCounter++) cout<<"Source["<<LoopCounter<<"]="<<Source[LoopCounter] <<"\t Destination["<<LoopCounter<<"]="<< Destination[LoopCounter]<<endl; //Change the values of the Source array so that the 2 arrays no longer //are the same. Source[0]=10; Source[1]=11; Source[2]=12; Source[3]=13; Source[4]=14; //output the arrays again, both contain the new values. for(LoopCounter=0;LoopCounter<5;LoopCounter++) cout<<"Source["<<LoopCounter<<"]="<<Source[LoopCounter] <<"\t Destination["<<LoopCounter<<"]="<< Destination[LoopCounter]<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  19. Chapter 6 - Arrays 6.2 Array Shortcuts - Duplicate Code Example Continued Modern compilers would not even allow this to occur. In older compilers, the output would be as follows: 1 2 3 4 5 1 2 3 4 5 10 11 12 13 14 10 11 12 13 14 The C++ Coach - Essentials for Introductory Programming - 2000

  20. Chapter 6 - Arrays 6.2 Array Shortcuts - Copy an Array Example Later, we will discuss why arrays function this way, but for now just accept that you can't use an = operator to copy and array. If you wanted to copy one array to another, use the code that follows: #include <stdlib.h> #include <iostream.h> #define ArraySize 5 void main() { int Source[ArraySize]={1,2,3,4,5}; int Destination[ArraySize]; int LoopCounter; for(LoopCounter=0;LoopCounter<5;LoopCounter++) Destination[LoopCounter]=Source[LoopCounter]; } The above code copies each individual element at a time and works properly. The C++ Coach - Essentials for Introductory Programming - 2000

  21. Chapter 6 - Arrays 6.2 Array Shortcuts - Copy Function void Copy(int Destination[], int Source[], int NumElem) { int LoopCounter; for(LoopCounter=0;LoopCounter<NumElem;LoopCounter++) Destination[LoopCounter]=Source[LoopCounter]; } Programmer's Notebook Notice that the Destination array is listed as the first parameter. This is done on purpose, as we will see with all array copying functions. This is to simulate the order we are already familiar with when copying. Normally we use an equals sign as in Destination=Source, so little has changed. The C++ Coach - Essentials for Introductory Programming - 2000

  22. Chapter 6 - Arrays 6.2 Array Shortcuts - Complete Program #include <stdlib.h> #include <iostream.h> #define NumValues1 5 #define NumValues2 10 //Prototypes void Copy(int Destination[], int Source[], int NumValues); void InitializeArray(int Array[], int NumValues); void OutputArray(int Array[], int NumValues); //Main Routine void main() { int Array1[NumValues1]; int Array2[NumValues1]; int Array3[NumValues2]; int Array4[NumValues2]; //Show example with first set of arrays //Get values from users InitializeArray(Array1, NumValues1); The C++ Coach - Essentials for Introductory Programming - 2000

  23. Chapter 6 - Arrays 6.2 Array Shortcuts - Complete Program //Copy the values from Array1 to Array2 Copy(Array2,Array1,NumValues1); //Output the Array OutputArray(Array2, NumValues1); //Get values from users InitializeArray(Array3, NumValues2); //Copy the values from Array3 to Array4 Copy(Array4,Array3,NumValues2); //Output the Array OutputArray(Array4, NumValues2); } //Functions void Copy(int Destination[], int Source[], int NumValues) { int LoopCounter; for(LoopCounter=0;LoopCounter<NumValues;LoopCounter++) Destination[LoopCounter]=Source[LoopCounter]; } The C++ Coach - Essentials for Introductory Programming - 2000

  24. Chapter 6 - Arrays 6.2 Array Shortcuts - Complete Program void InitializeArray(int Array[], int NumValues) { int LoopCounter; //Loop thru the arrays reading values from // the user for(LoopCounter=0; LoopCounter<NumValues;LoopCounter++) { cout<<"Please enter a value:"; cin>>Array[LoopCounter]; } } void OutputArray(int Array[], int NumValues) { int LoopCounter; for(LoopCounter=0; LoopCounter< NumValues; LoopCounter++) { cout<<Array[LoopCounter]<<endl; } } The C++ Coach - Essentials for Introductory Programming - 2000

  25. Chapter 6 - Arrays 6.2 Array Shortcuts Programmer's Notebook When passing arrays as parameters any changes made to the arrays from within the function are remembered outside the function. Drill 6-3 #include <stdlib.h> #include <iostream.h> #define ArraySize 5 //Prototypes void Change(int Values[]); void OutputArray(int Array[], int NumValues); //Functions void Change(int Values[], int NumValues) { Values[2]=10; Values[4]=20; OutputArray(Values, NumValues); } The C++ Coach - Essentials for Introductory Programming - 2000

  26. Chapter 6 - Arrays 6.2 Array Shortcuts void OutputArray(int Array[], int NumValues) { int LoopCounter; for(LoopCounter=0; LoopCounter< NumValues; LoopCounter++) { cout<<Array[LoopCounter]<<endl; } } void main() { int Array1[ArraySize]={1,2,3,4,5}; //Output the Array OutputArray(Array1, ArraySize); //Call Function to Change Values Change(Array1, ArraySize); //Output the Array OutputArray(Array1, ArraySize); } Output: 1 2 3 4 5 1 2 10 4 20 1 2 10 4 20 The C++ Coach - Essentials for Introductory Programming - 2000

  27. Chapter 6 - Arrays 6.3 Character Arrays So far we have just discussed arrays of numbers, but equally important are arrays of characters. Arrays of characters allow you to store names, words, and expressions. //Example of character arrays #include <stdlib.h> #include <iostream.h> void main() { char Word[] = {'H','e','l','l','o','\n'}; int LoopCounter=0; while(Word[LoopCounter]!='\n') cout<<Word[LoopCounter++]; cout<<endl; } The previous program has a '\n' character added to the array. We used this to indicate the end of the array of characters. In reality there is a better way to accomplish this, it called a string. We have already seen strings, but have not really drawn attention to them. Remember the following example? cout<<"We Love the Pittsburgh Steelers"; The C++ Coach - Essentials for Introductory Programming - 2000

  28. Chapter 6 - Arrays 6.3 Character Arrays A string is a series of characters enclosed in " ". See how using string functionality makes allocating a string simple: char Word[]="hello!"; Notice no special characters were needed. We could create the equivalent by allocating an array of characters and making sure that the last character in the array is a '\0'; char Word[7]; Word[0] = 'h'; Word[1] = 'e'; Word[2] = 'l'; Word[3] = 'l'; Word[4] = 'o'; Word[5] = '!'; Word[6] = '\0'; Programmer's Notebook So, to review a ‘A’ and a "A" are NOT the same thing. A ‘A’ is a single character, while a "A" is really two characters an ‘A’ and a ‘\0’. The C++ Coach - Essentials for Introductory Programming - 2000

  29. Chapter 6 - Arrays 6.3 Character Arrays Another advantage of strings is that they can be easily input and output with cout and cin like any other variables. See the simplicity of outputting a string as follows: cout<<Word; No longer must we write code to loop through the array to output the values. Similarly, we can input values into strings with cin. The key is to have enough space in the array to accept all the characters from the user. char Buffer[256]; cout<<"Enter a name"<<endl; cin>>Buffer; The C++ Coach - Essentials for Introductory Programming - 2000

  30. Chapter 6 - Arrays • 6.4 Multidimensional Arrays • Sometimes a problem does not map itself to an array of only one dimension. • Fortunately, C++ provides the ability to create multidimensional arrays, although this is only by appearance. • In reality a multidimensional array is really one continuous block of memory. • To declare an a two dimensional array we use the following template: • VariableType ArrayName[#rows][#columns]; • An example of declaring an array of integers called Values with 4 rows and 5 columns is as follows: • int Values[4][5]; The C++ Coach - Essentials for Introductory Programming - 2000

  31. Chapter 6 - Arrays 6.4 Multidimensional Arrays If we represented the array values graphically with each cell containing its row and column indexes respectively, it would look as follows: Columns 0 1 2 3 4 0 0,0 0,1 0,2 0,3 0,4 Rows 1 1,0 1,1 1,2 1,3 1,4 2 2,0 2,1 2,2 2,3 2,4 3 3,0 3,1 3,2 3,3 3,4 The C++ Coach - Essentials for Introductory Programming - 2000

  32. Chapter 6 - Arrays 6.4 Multidimensional Arrays If we wanted to initialize all the values in the array to 1, we could write a simple nested loop as follows: #include <iostream.h> #include <stdlib.h> #define NumRows 4 #define NumCols 5 void main() { int Values[NumRows][NumCols]; int Rows; int Cols; for (Rows=0;Rows<4;Rows++) for(Cols=0;Cols<5;Cols++) Values[Rows][Cols]=1; } The C++ Coach - Essentials for Introductory Programming - 2000

  33. Chapter 6 - Arrays 6.4 Multidimensional Arrays - Pricing Example New Way #include <stdlib.h> #include <iostream.h> #define RETAIL 0 #define DISCOUNT 1 #define NumPrices 5 #define NumCols 2 void main() { float Prices[NumPrices][NumCols]; int LoopCounter; for(LoopCounter=0;LoopCounter<NumPrices;LoopCounter++) { cout<<"Enter the retail price: "<<endl; cin>>Prices[LoopCounter][RETAIL]; cout<<"Enter the discounted price:"<<endl; cin>>Prices[LoopCounter][DISCOUNT]; } } The C++ Coach - Essentials for Introductory Programming - 2000

  34. Chapter 6 - Arrays 6.4 Multidimensional Arrays - Pricing Example Old Way #include <stdlib.h> #include <iostream.h> #define NumPrices 5 void main() { float Retail[NumPrices]; float Discount[NumPrices]; int LoopCounter; for(int LoopCounter=0;LoopCounter<5;LoopCounter++) { cout<<"Enter the retail price: "<<endl; cin>>Retail[LoopCounter]; cout<<"Enter the discounted price:"<<endl; cin>>Discount[LoopCounter]; } } The C++ Coach - Essentials for Introductory Programming - 2000

  35. Chapter 6 - Arrays 6.4 Multidimensional Arrays - Array Initialization Shortcut Just as we had a shortcut to initializing a single dimensional array, we can also shortcut the initialization of multiple dimensional arrays. See below how we initialize an array of 2 rows and 5 columns of integers. int Values[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}}; Note the commas between the rows. Also note that the extra set of curly braces are optional, but advised. The array can also be initialized as follows, but it is not nearly as readable. int Values[2][5] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; It is also possible to partially initialize a multidimensional array similarly as we did a single dimensional array. See the following example: int Values[2][5] = {{1,2,3,4,5}, {6}}; Columns 0 1 2 3 4 Rows 0 1 2 3 4 5 1 6 0 0 0 0 The C++ Coach - Essentials for Introductory Programming - 2000

  36. Chapter 6 - Arrays 6.4 Multidimensional Arrays - Drill 6-4 #include <stdlib.h> #include <iostream.h> #define NumRows 3 #define NumCols 3 void main() { int SampleArray[NumRows][NumCols] = {{1,2,3}, {4,5,6}, {7,8,9}}; cout<<SampleArray[1][1]<<endl; cout<<SampleArray[2][1]<<endl; cout<<SampleArray[3][3]<<endl; } Output: 5 8 ??? Columns Rows 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 The C++ Coach - Essentials for Introductory Programming - 2000

  37. Chapter 6 - Arrays 6.4 Multidimensional Arrays - Drill 6-5 #include <stdlib.h> #include <iostream.h> #define NumRows 3 #define NumCols 3 void main() { int SampleArray[NumRows][NumCols] = {{1,2,3}, {4,5,6}, {7,8,9}}; int Row; int Col; for (Row=0; Row<NumRows; Row++) for (Col=0; Col<NumCols; Col++) cout<<SampleArray[Col][Row]<<endl; } Output: 1 4 7 2 5 8 3 6 9 Columns Rows 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 The C++ Coach - Essentials for Introductory Programming - 2000

  38. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters Let’s create a program that stores a chessboard configuration. A chessboard consists of 64 squares arranged in eight rows and eight columns. It can contain up to 8 pawns (P), 2 Castles (C), 2 Knights (N), 2 Rooks (R), a Queen (Q), and a King (K) for each player (white versus black). The representation we will store will be the beginning position of the game. See the following pictorial of it. c n r q k r n c p p p p p p p p P P P P P P P P C N R Q K R N C The C++ Coach - Essentials for Introductory Programming - 2000

  39. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters Let’s create a program that stores a chessboard configuration. A chessboard consists of 64 squares arranged in eight rows and eight columns. It can contain up to 8 pawns (P), 2 Castles (C), 2 Knights (N), 2 Rooks (R), a Queen (Q), and a King (K) for each player (white versus black). The representation we will store will be the beginning position of the game. See the following pictorial of it. 0,0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 1,0 1,1 1,2 1,3 1,4 1,5 1,6 1,7 2,0 2,1 2,2 2,3 2,4 2,5 2,6 2,7 3,0 3,1 3,2 3,3 3,4 3,5 3,6 3,7 4,0 4,1 4,2 4,3 4,4 4,5 4,6 4,7 5,0 5,1 5,2 5,3 5,4 5,5 5,6 5,7 6,0 6,1 6,2 6,3 6,4 6,5 6,6 6,7 7,0 7,1 7,2 7,3 7,4 7,5 7,6 7,7 The C++ Coach - Essentials for Introductory Programming - 2000

  40. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Chess Implementation #include <stdlib.h> #include <iostream.h> #define NumRows 8 #define NumCols 8 void main() { char Board[8][8]; int Row; int Col; //Initialize the first row Board[0][0]='c'; Board[0][1]='n'; Board[0][2]='r'; Board[0][3]='q'; Board[0][4]='k'; Board[0][5]='r'; Board[0][6]='n'; Board[0][7]='c'; The C++ Coach - Essentials for Introductory Programming - 2000

  41. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Chess Implementation //Initialize the second row Board[1][0]='p'; Board[1][1]='p'; Board[1][2]='p'; Board[1][3]='p'; Board[1][4]='p'; Board[1][5]='p'; Board[1][6]='p'; Board[1][7]='p'; //Initialize the third thru sixth rows for (Row=3; Row<6; Row++) for (Col=0;Col<8; Col++) Board[Row][Col]=' '; //Initialize the seventh row Board[0][0]='p'; Board[0][1]='p'; Board[0][2]='p'; Board[0][3]='p'; Board[0][4]='p'; Board[0][5]='p'; Board[0][6]='p'; Board[0][7]='p'; The C++ Coach - Essentials for Introductory Programming - 2000

  42. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Chess Implementation //Initialize the eigth row Board[7][0]='c'; Board[7][1]='n'; Board[7][2]='r'; Board[7][3]='k'; Board[7][4]='q'; Board[7][5]='r'; Board[7][6]='n'; Board[7][7]='c'; } The C++ Coach - Essentials for Introductory Programming - 2000

  43. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Chess Implementation //Chessboard implementation with shortcut #include <stdlib.h> #include <iostream.h> #define NumRows 8 #define NumCols 8 void main() { char Board[NumRows][NumCols]={ {'c', 'n', 'r', 'q', 'k', 'r', 'n', 'c'}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {'C', 'N', 'R', 'Q', 'K', 'R', 'N', 'C'}, }; } The C++ Coach - Essentials for Introductory Programming - 2000

  44. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Strings //Program to demonstrate an array of strings #include <stdlib.h> #include <iostream.h> //Defines #define NumNames 10 #define MaxSize 50 //Prototypes void InitializeNames(char Names[NumNames][MaxSize]); void DisplayNames(char Names[NumNames][MaxSize]); //Main Routine void main() { char Names[NumNames][MaxSize]; InitializeNames(Names); DisplayNames(Names); } The C++ Coach - Essentials for Introductory Programming - 2000

  45. Chapter 6 - Arrays 6.5 Multidimensional Arrays of Characters - Strings - Continued //Functions void InitializeNames(char Names[NumNames][MaxSize]) { int LoopCounter; for (LoopCounter=0;LoopCounter<NumNames;LoopCounter++) { cout<<"Enter a Name"<<endl; cin.getline(Names[LoopCounter], MaxSize); } } void DisplayNames(char Names[NumNames][MaxSize]) { int LoopCounter; for (int LoopCounter=0;LoopCounter<NumNames;LoopCounter++) cout<<Names[LoopCounter]<<endl; } The C++ Coach - Essentials for Introductory Programming - 2000

  46. Chapter 6 - Arrays 6.6 Case Study Problem Description Instead of paying in cash, the entrepreneur now pays his employees by check. A check stub should be prepared which shows the employees ID, hours worked, pay rate, gross pay, tax and net pay. Overtime at 1.5 times the hourly wage is paid for any employee working more than 40 hours per week. Write a program that prints a worker's paycheck showing the dollar sign and the amount formatted to two decimal places. Your program input should consist of the employees ID, employees name, the hours worked, the employees tax rate and each employee's hourly pay. The numeric input should be accomplished via a single function called successively for each input. The program should use functions to the maximum extent, store all inputs in arrays, and run continuously until terminated by the operator, at which time the checks for all employees should be displayed. The C++ Coach - Essentials for Introductory Programming - 2000

  47. Chapter 6 - Arrays 6.6 Case Study - Solution #include <stdlib.h> #include <iostream.h> #include <iomanip.h> #define NumRows 100 #define NumColumns 30 float GetValue(int Number); float CalculateGross(float Hours, float Wage); float CalculateTax(float Gross, float TaxRate); void Prompt(int Number); void SetFlags(); void DisplayCheck(int Number, float Hours, char Numbers[],float Wage,float Gross, float Tax, float Pay); void main() { int EmployeeNumber[NumRows]; int Count = 0; int Index; char Name[NumRows][NumColumns]; float Hours[NumRows], Wage[NumRows], TaxRate[NumRows]; float EmployeeTax, EmployeeGross, EmployeeNet; The C++ Coach - Essentials for Introductory Programming - 2000

  48. Chapter 6 - Arrays 6.6 Case Study - Solution Continued do { EmployeeNumber[Count] = int(GetValue(1)); if (EmployeeNumber[Count] <= 0) break; Prompt(2); cin.getline(Name[Count],80); Hours[Count] = GetValue(3); Wage[Count] = GetValue(4); TaxRate[Count] = GetValue(5); Count++; } while(EmployeeNumber[Count-1] > 0); if (Count > 0) SetFlags(); else return; for(Index = 0; Index < Count; Index++) { EmployeeGross = CalculateGross(Hours[Index], Wage[Index]); EmployeeTax = CalculateTax(EmployeeGross, TaxRate[Index]); EmployeeNet = EmployeeGross - EmployeeTax; DisplayCheck(EmployeeNumber[Index], Hours[Index], Name[Index], Wage[Index], EmployeeGross,EmployeeTax,EmployeeNet); } } The C++ Coach - Essentials for Introductory Programming - 2000

  49. Chapter 6 - Arrays 6.6 Case Study - Solution Continued float GetValue(int Number) { float Value; Prompt(Number); cin >> Value; cin.get();//Extracts \n from buffer return Value; } void Prompt(int Number) { switch(Number) { case 1: cout << "\nEnter negative to end or "; cout << "\nEnter employee\'s ID -> "; break; case 2: cout << "Enter employee\'s name -> "; break; case 3: cout << "Enter employee\'s hours -> "; break; case 4: cout << "Enter employee\'s wage rate -> "; break; case 5: cout << "Enter employee\'s tax rate -> "; break; } } The C++ Coach - Essentials for Introductory Programming - 2000

  50. Chapter 6 - Arrays 6.6 Case Study - Solution Continued float CalculateGross(float Hours, float Wage) { const int STDWEEK = 40; float Gross, OverTime; if (Hours > STDWEEK) OverTime = Hours - STDWEEK; else OverTime = 0.0; Gross = (Wage * Hours) + (OverTime * (float).5 * Wage); return Gross; } float CalculateTax(float Gross, float TaxRate) { const float CONVERT = 100.00; float Tax; if (TaxRate > 1) TaxRate = TaxRate/CONVERT; Tax = Gross * TaxRate; return Tax; } The C++ Coach - Essentials for Introductory Programming - 2000

More Related