1 / 42

Basic Data Structures

Basic Data Structures. Yared Semu Dec 21, 2011 Modified: May 2012. A Question? . Suppose you are asked to write a program to analyze scores given by six judges in a game. How would you tackle the problem? Ok, How you store the scores given by each judge? Well, you have two options:

tanith
Télécharger la présentation

Basic Data Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic Data Structures YaredSemu Dec 21, 2011 Modified: May 2012

  2. A Question? • Suppose you are asked to write a program to analyze scores given by six judges in a game. How would you tackle the problem? • Ok, How you store the scores given by each judge? • Well, you have two options: • Option A : Declare six independent variables for each score • Option B : Declare an Array

  3. What is an Array? It is simply a structure that allow us to group together data items of the same type.

  4. Array: Formal Definition An array allows us to group a number of values of the same type into one large unit.

  5. Consecutive Memory Locations

  6. Defining Arrays: • An array definition specifies a variable type and a name. But it also includes another feature : Size • Note: An array’s size declarator must be a constant integer expression with a value greater than zero. (Literal or Named Constant ) Syntax: type name [size];

  7. Syntax for Array Definition

  8. Examples: Array Declarations: constint POPULATION_SIZE = 210; long population [POPULATION_SIZE]; float salaries [15]; char name [30];

  9. Which of these array declaration are valid? const int SIZE = 110; intnum_people = 100; int size; 1. char letters[26]; 2. double atomic_weights[SIZE]; 3. float heights[num_people]; 4. float areas[34.4]; 5. char name [size];

  10. Accessing array Elements: • The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements. • Example: double scores [6];

  11. Note: No bound checking in C++ • Subscripts numbering always starts at zero. The subscript of the last element is one less than the total number of elements in the array. Example: int scores [6]; 4 3 0 1 5 2 scores

  12. Subscript numbering starts at zero. The subscript of the last element is one less than the total number of elements in the array. Accessing the Elements To access an element of the array, you use array_name[subscript] double scores[4]; //an array to hold 4 scores cout<<”Enter the scores of the four Judges: “; cin>>>>scores[0]>>scores[1]>>scores[2]>>scores[3]; cout<<”Score of Judges:” <<”\n Judge 1 gave “<<scores[0]; <<”\n Judge 2 gave “<<scores[1]; <<”\n Judge 3 gave “<<scores[2]; <<”\n Judge 4 gave “<<scores[3];

  13. Exercise: 1. Write an array declaration statement that stores the score of a student. The student takes 4 courses in the current semester. Ans: double scores [4]; 2. Set the score of the first element of the array you declared above to 90.4 and the last element to 50.6 Ans: scores [0] = 90.4; scores [3] = 50.6;

  14. Note It is not possible to assign one array to another or use an array in an expression hoping to affect all its elements.

  15. Arrays and for loops • Arrays and for loops always go hand in hand.

  16. Using for loops to access array elements constintNUM_JUDGES = 6; double scores[NUM_JUDGES]; double average = 0; double totalScore = 0; cout<<”Enter the “<<NUM_JUDES<<“scores “; for (int i=0; i< NUM_JUDGES; ++i) cin>>scores[i]; cout<<”Average Score”; for (int j=0; j< NUM_JUDGES; ++j) totalScore +=scores[i]; average = totalScore/NUM_JUDGES;

  17. Initializing Arrays • Arrays may be initialized when they are defined. Syntax: type array_name[size] = initializer_list;

  18. Initializing Arrays Example: intage[4] = {25, 12, 15, 27}; /* 25 is stored in age[0], 12 is stored in age[1], 15 is stored in age[2], 27 is stored in age[3] */

  19. Initializing Arrays, contd... • C++ allows us to define an array without specifying its size, as long as we provide an initialization list. • Example double factors[] = {1.0, 1.5, 2.0, 2.5};

  20. More Examples int age[4] = {25, 12}; //age[0] = 25, age[1]=12, age[2]=0, age[3]=0 char name[] = {'B', 'i', 'r', 'u', 'k'}; double factors[4] = {1.0, 1.5, 2.0, 2.5, 3.0}; //Error!

  21. Initializing Arrays • Syntax type array_name[size] = initializer_list; • The initializer list contains a set of comma separated values within a pair of curly braces. • Example int age[4] = {25, 12, 15, 27}; /* 25 is stored in age[0], 12 is stored in age[1], 15 is stored in age[2], 27 is stored in age[3] */

  22. Initializing Arrays, contd... • C++ allows us to define an array without specifying its size, as long as we provide an initialization list. • Example double factors[] = {1.0, 1.5, 2.0, 2.5};

  23. More Examples int age[4] = {25, 12}; //age[0] = 25, age[1]=12, age[2]=0, age[3]=0 char name[] = {'B', 'i', 'r', 'u', 'k'}; double factors[4] = {1.0, 1.5, 2.0, 2.5, 3.0}; //ERROR!

  24. Multidimensional Arrays YaredSemu Dec 23, 2011 Modified : May 2012

  25. Summary: Arrays -101 • An Array is a structure that group a number of items into a larger unit. • Declaration of arrays in C++ have the form: The size must be a constant of one of the integer types. Once defined, the size is fixed. Syntax: type name [size];

  26. Accessing array Elements: • The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements. • Example: int scores [6]; 4 3 0 1 5 2 scores

  27. Initializing Arrays • Arrays may be initialized when they are defined. We can give value to each element when defining the array. Syntax: type array_name[size] = initializer_list;

  28. Arrays as Function Arguments • Functions can be written to process the data in arrays. Usually, such functions accept an array as an argument. • Functions can be written: 1. To put values in an array. 2. Display an array’s contents on the screen 3. Total all of an array’s elements 4. Calculate their average… etc.

  29. Array elements as arguments: • When a single element of an array is passed to a function, it is handled like any other variable. void print(intnum) { //Just display the argument cout<<num<<endl; } int main() { intmyArray[]={1, 2, 3, 4}; print(myArray[3]); return 0; }

  30. Array as an argument • If our printing function were written to accept the entire array as an argument, it would be set up as follows: void print (int []); void print(int num[], int N) { for (int i=0;i<N;++i) cout<<num[i]<<endl; } intmain() { intmyArray[]={1, 2, 3, 4}; print(myArray, 4); return 0; }

  31. Exercise: Array Basics Develop a program that finds the maximum and minimum values of an integer array. The values are to be entered by the user. (Assume five elements are to be stored in the array) Note: • You should use Functions to: • Fill in the array elements from the user • Find the minimum value in the array • Find the maximum value in the array

  32. A Question? • Lets say your are to design a grade-averaging program. The program takes the scores of 10 students and computes the averages of their scores. Students take 4 courses in the current semester. • How you go about solving the problem? Option A : declare about 40 independent Variables (Boooo!) Option B : declare 10 arrays of size 4 for each student (Ok!) Option C: Better Option (Multidimensional Arrays!!)

  33. Multidimensional Arrays • So far, we have seen one dimensional arrays. • We can also have arrays to store N dimensions of information. => Multidimensional arrays • Examples of multidimensional data: • Matrices • Grade reports of students • Yearly weather reports (temperature) summarized by month and day.

  34. Defining Two Dimensional Arrays • Syntax: Example: double scores [3][4]; • It is best to think of a 2D array as a table with rows and columns of elements. • type name [size for dim 1][size for dim 2];

  35. Two Dimensional Arrays • A two dimensional array is like several identical arrays put together..

  36. 2D Arrays • To access an element of the array, we use two subscripts – one for the column and one for the row. • Example: score[1][2] = 12.0; cout<<score[2][3]<<endl; 12.0

  37. Case Study: Grade Averaging Program First Step: Read the scores

  38. Second Step: Calculate the average scores

  39. Finally : Show Time!!

  40. Initializing 2D Arrays • You can consider a 2D array to be an array of arrays. • The initialization statement uses an initializer list where each element is by itself an initializer list for a single row. float scores[2][3] = {{1, 2, 3}, {4, 5, 6}};

  41. Assignment:Due Date : May25, 2012 • Write a program that accepts a 2D integer array from the user and • Sums all the elements • Stores the sum of each row in a 1D integer array • Stores the sum of each column in a 1D integer array

  42. Course Project: Develop a program the performs the following matrix operations. • Addition • Multiplication • Finding the Inverse • Finding the Determinant • You will demonstrate the program 3days after your last final exam.

More Related