1 / 27

Chapter 5

Chapter 5. Arrays: We've got their number. Yahtzee game. You throw 5 dice You want them to be the same If not the same, you are allowed to rethrow some or all the dice up to twice. Game of Yahtzee. You can write: int d1,d2,d3,d4, d5; But can't you declare the dice in a single statement?

dunn
Download Presentation

Chapter 5

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 5 Arrays: We've got their number

  2. Yahtzee game • You throw 5 dice • You want them to be the same • If not the same, you are allowed to rethrow some or all the dice up to twice.

  3. Game of Yahtzee • You can write: • int d1,d2,d3,d4, d5; • But can't you declare the dice in a single statement? • Yes • int d[5] • the dice are d[0],d[1],d[2],d[3], and d[4] • you always start counting at 0 and go up to the array length -1

  4. Initialize the dice • arrays and for-loops go together like bacon and eggs int d[5]; //global array int dice(){ // returns the value of the dice return rand()%6+1; } rollAllDice(){ for(int i=0; i < 5; i++) d[i] = dice(); } rollSomeDice(int a[], int size){ for(int i=0; i < size; i++){ d[a[i]]=dice(); } }

  5. Initializing and Printing an array int main(){ int a[] ={2,234,242,2,3}; for(int i=0; i < 5; i++){ cout << a[i] << " "; } }

  6. Note about arrays • The size of an array needs to be a constant (known at compile time). It cannot be a variable that is not a constant. • Once an array is created, its size cannot be changed. • Make sure that you declare your array to be big enough. • Only access elements 0 up to size-1. Otherwise, the program will behave in unpredictable way. You will be seeing data you are not supposed to see.

  7. Testing the random function • We want to generate 1 million random numbers between 0 and 9 and see if the distribution is even.

  8. #include <math.h> #include <time.h> #include <stdlib.h> #include <iostream> using namespace std; int main(){ int a[]={0,0,0,0,0,0,0,0,0,0}; srand(time(NULL)); rand(); for(int i=0; i < 100000; i++){ int number = rand()%10; a[number]++; } for(int i=0; i < 10; i++){ printf("Number %d appears %d times\n",i, a[i]); } }

  9. Working with strings char* names[] = {"Bob","Mike","Ann","Laura"}; for(int i=0; i < 4; i++){ cout << names[i]; } string functions: strcpy(s1,s2); //copies s2 into s1; char* s3 = strcat(s1,s2); //concatenates s1 and s2 strcmp(s1,s2); //returns 0 is strings are the same // positive integer if s1> s2; // negative integer is s1 < s2; strlen(s); //returns the length of s // strings are null (a.k.a. 0) terminated

  10. Reading Strings char line[50]; int k = 0; while((line[k]=getchar())!= '\n') k++; line[k] = '\0' or alternative: gets(line);

  11. Printing Strings for(int k=0;k<strlen(line)-1;k++) putchar(line[k]) putchar('\n'); alternative: puts(line);

  12. Dealing cards #include <math.h> #include <time.h> #include <stdlib.h> #include <iostream> using namespace std; int main(){ char* suits[4] = {"clubs","diamonds","hearts", "spades"}; char* ranks[13] ={"two","three","four","five","six","seven","eight","nine","ten","jack", "queen", "king", "ace"}; srand(time(NULL));rand(); printf("%s of %s",ranks[rand()%13],suits[rand()%4]); }

  13. Card Dealer #2 • This time, we want to generate a single random number. • We will calculate rank and suit from it. • We will store the calculated numbers in an array. • This will guarantee that every number that is generated is unique.

  14. bool contains(int [], int , int ); int main(){ char* suits[4] = {"clubs","diamonds", "hearts", "spades"}; char* ranks[13] = {"two","three","four","five","six","seven","eight","nine","ten","jack", "queen", "king", "ace"}; srand(time(NULL));rand(); int cards[5]; for(int i=0;i< 5; i++){ int x = rand()%52; while(contains(cards,x,i)){ x = rand()%52; } cards[i]=x; } for(int i=0; i< 5; i++){ printf("%s of%s\n",ranks[cards[i]%13], suits[cards[i]/13]); }}

  15. Method contains bool contains(int a[], int x, int size){ for(int i=0; i < size; i++){ if(a[i] == x) { return true; } } return false; }

  16. Two-dimensional Array Data is commonly in table form Difficult to represent using one-dimensional array A collection of componentsstructured in two dimensions All elements should be the same type

  17. Two-dimensional Array DataType ArrayName[Size1][Size2]; Each size has an integer value and specifies the number of components in that dimension Size1 : the number of rows Size2: the number of columns int data[5][10]; double sales[10][4];

  18. Indexes in 2DArrays Individual array elements are accessed by a pair of indexes The first index represents the element’s row, and the second index represents the element’s column. int data[6][10]; data[2][7] = 4 ; // row 2, column 7

  19. Accessing 2D Array int data[6][12]; data[2][7] = 4 ; // row 2, column 7 [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]data [2] [7] [ 5 ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] row 2, column 7 4 3 2 8 5 9 13 4 8 9 8 0

  20. Two-dimensional Array Initializing the element of a 2D array Elements of each row are enclosed within braces and separated by commas Rows are enclosed within braces int myArray[4][3]={{2,3,-1},{0,-3,5}, {2,6,3},{-2,10,4}};

  21. Two-dimensional Array int scores[2][3] = {3, 6, 4, 7, 3, 9}; Fill elements row-by-row till available If not enough initializer, remaining elements set to 0(same as 1-D array case)

  22. Two-dimensional Array Initializing the element of 2-D Array j int i, j, x[5][4]; … for (i =0; i <=4;i++) { for(j=0;j<=3;j++) { x[i][j]= i *j; } } i

  23. Two-dimensional Array Printout array elements #include <stdio.h> int counter[5][5]; int total=0; void main() { for (int i = 0; i< 5; i++) { for (int j=0;j<5; j++) { counter[i][j] = j + (i *5) ; printf( " %d ", counter[i][j] ); total += counter[i][j]; } printf( " \n "); } printf(" The total is %d ", total); }

  24. Two-dimensional Array Program output 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 The total is 300

  25. Passing an array to a function int counter[5][5]; • In function prototype double maximum (double table[5][5], int x, int y) double max = maximum(counter, 5, 5);

  26. Passing an array to a function void display(const int twoDArray[][50], //[][] int nrows, int ncols) //doesn't compile { for (int i=0; i < nrows; i++) { for (int j=0; j < ncols; j++ ) printf("%4d", twoDArray[i][j]); printf("\n"); } } const int cols = 50; const int rows = 50; int thisArray [rows][cols]; display( thisArray, 10, 30 );

  27. Multidimensional Arrays Can define three-dimensional array or N-dimensional array (N can be any number) Syntax DataType ArrayName[Size1][Size2] … [SizeN]; Each size has a positive integer value and specifies the number of components in that dimension int data[5][10][15];

More Related