basic data structures

42
BASIC DATA STRUCTURES Yared Semu Dec 21, 2011 Modified: May 2012

Upload: tanith

Post on 24-Feb-2016

34 views

Category:

Documents


0 download

DESCRIPTION

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: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Basic Data Structures

BASIC DATA STRUCTURESYared SemuDec 21, 2011

Modified: May 2012

Page 2: Basic Data Structures

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

Page 3: Basic Data Structures

What is an Array?

It is simply a structure that allow us to group together data items of the same type.

Page 4: Basic Data Structures

Array: Formal Definition

An array allows us to group a number of values of the same type into one large unit.

Page 5: Basic Data Structures

Consecutive Memory Locations

Page 6: Basic Data Structures

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];

Page 7: Basic Data Structures

Syntax for Array Definition

Page 8: Basic Data Structures

Examples: Array Declarations:

const int POPULATION_SIZE = 210;

long population [POPULATION_SIZE];float salaries [15];char name [30];

Page 9: Basic Data Structures

Which of these array declaration are valid?

const int SIZE = 110;int num_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];

Page 10: Basic Data Structures

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];

Page 11: Basic Data Structures

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];

0 1 2 3 4 5

scores

Page 12: Basic Data Structures

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];

Subscript numbering starts at zero. The subscript of the last element is one less than the total number of elements in the array.

Page 13: Basic Data Structures

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;

Page 14: Basic Data Structures

Note

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

Page 15: Basic Data Structures

Arrays and for loops

• Arrays and for loops always go hand in hand.

Page 16: Basic Data Structures

Using for loops to access array elements

const int NUM_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;

Page 17: Basic Data Structures

Initializing Arrays• Arrays may be initialized when they are defined.

Syntax:type array_name[size] = initializer_list;

Page 18: Basic Data Structures

Initializing Arrays

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] */

Page 19: Basic Data Structures

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};

Page 20: Basic Data Structures

More Examplesint 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!

Page 21: Basic Data Structures

Initializing Arrays

• Syntaxtype array_name[size] = initializer_list;• The initializer list contains a set of comma

separated values within a pair of curly braces.• Exampleint 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] */

Page 22: Basic Data Structures

Initializing Arrays, contd...

• C++ allows us to define an array without specifying its size, as long as we provide an initialization list.

• Exampledouble factors[] = {1.0, 1.5, 2.0, 2.5};

Page 23: Basic Data Structures

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!

Page 24: Basic Data Structures

MULTIDIMENSIONAL ARRAYSYared SemuDec 23, 2011

Modified : May 2012

Page 25: Basic Data Structures

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:

Syntax:

type name [size];

The size must be a constant of one of the integer types.Once defined, the size is fixed.

Page 26: Basic Data Structures

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];

0 1 2 3 4 5

scores

Page 27: Basic Data Structures

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;

Page 28: Basic Data Structures

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 screen3. Total all of an array’s elements4. Calculate their average… etc.

Page 29: Basic Data Structures

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(int num) {

//Just display the argument cout<<num<<endl; } int main() {

int myArray[]={1, 2, 3, 4}; print(myArray[3]); return 0;

}

Page 30: Basic Data Structures

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; } int main() {

int myArray[]={1, 2, 3, 4}; print(myArray, 4); return 0;

}

Page 31: Basic Data Structures

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:

1. Fill in the array elements from the user2. Find the minimum value in the array3. Find the maximum value in the array

Page 32: Basic Data Structures

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!!)

Page 33: Basic Data Structures

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.

Page 34: Basic Data Structures

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];

Page 35: Basic Data Structures

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

together..

Page 36: Basic Data Structures

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

Page 37: Basic Data Structures

Case Study: Grade Averaging Program

First Step: Read the scores

Page 38: Basic Data Structures

Second Step: Calculate the average scores

Page 39: Basic Data Structures

Finally : Show Time!!

Page 40: Basic Data Structures

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}};

Page 41: Basic Data Structures

Assignment: Due Date : May25, 2012

1. Write a program that accepts a 2D integer array from the user and

a) Sums all the elementsb) Stores the sum of each row in a 1D integer arrayc) Stores the sum of each column in a 1D integer

array

Page 42: Basic Data Structures

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.