0% found this document useful (0 votes)
136 views55 pages

Arrays and Structures in CPP

Arrays allow the processing of a collection of data of the same type. An array is declared with square brackets containing the array size. Each element in the array is accessed via an index number within the brackets. Multi-dimensional arrays can be used to organize data into rows and columns. Arrays must be initialized with values or elements will contain random data. Functions can operate on array elements to calculate values like averages.

Uploaded by

Esubalew Chekol
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
136 views55 pages

Arrays and Structures in CPP

Arrays allow the processing of a collection of data of the same type. An array is declared with square brackets containing the array size. Each element in the array is accessed via an index number within the brackets. Multi-dimensional arrays can be used to organize data into rows and columns. Arrays must be initialized with values or elements will contain random data. Functions can operate on array elements to calculate values like averages.

Uploaded by

Esubalew Chekol
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 55

Arrays and Structures - C++

Collections & user-defined types

Chapter 1- Array and Structures


Introduction to Arrays

 An array is used to process a collection of data


of the same type
 Examples: A list of names
A list of temperatures
 Why do we need arrays?
 Imagine keeping track of 5 test scores, or 100, or
1000 in memory
 How would you name all the variables?
 How would you process each of the variables?

Chapter 1- Array and Structures in C++


Declaring an Array

 An array, named score, containing five variables


of type int can be declared as
int score[ 5 ];
 This is like declaring 5 variables of type int:
score[0], score[1], … , score[4]
 The value in brackets is called
 A subscript
 An index

Chapter 1- Array and Structures in C++


The Array Variables

 The variables making up the array are referred to


as
 Indexed variables
 Subscripted variables
 Elements of the array
 The number of indexed variables in an array is
the declared size, or size, of the array
 The largest index is one less than the size
 The first index value is zero

Chapter 1- Array and Structures in C++


Array Variable Types

 An array can have indexed variables of any type

 All indexed variables in an array are of the


same type
 This is the base type of the array

 An indexed variable can be used anywhere an


ordinary variable of the base type is used

Chapter 1- Array and Structures in C++


Using [ ] With Arrays

 In an array declaration, [ ]'s enclose the size


of the array such as this array of 5 integers:
int score [5];
 When referring to one of the indexed variables,
the [ ]'s enclose a number identifying one of
the indexed variables
 score[3] is one of the indexed variables
 The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)

Chapter 1- Array and Structures in C++


Indexed Variable Assignment

 To assign a value to an indexed variable, use


the assignment operator:

int n = 2;
score[n + 1] = 99;
 In this example, variable score[3] is assigned 99

Chapter 1- Array and Structures in C++


Loops And Arrays

First index is 0 Last index is (size – 1)


 for-loops are commonly used to step through
arrays
 Example: for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score
and the maximum score stored in an array

Chapter 1- Array and Structures in C++


Constants and Arrays

 Use constants to declare the size of an array


 Using a constant allows your code to be easily
altered for use on a smaller or larger set of data
 Example: const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by "
<< (max – score[i]) << endl;
 Only the value of the constant must be changed to make
this code work for any number of students

Chapter 1- Array and Structures in C++


Variables and Declarations

 Most compilers do not allow the use of a variable


to declare the size of an array

Example: cout << "Enter number of students: ";


cin >> number;
int score[number];

 This code is illegal on many compilers

Chapter 1- Array and Structures in C++


Arrays and Memory

 Declaring the array int a[6]


 Reserves memory for six variables of type int
 The variables are stored one after another
 The address of a[0] is remembered
 The addresses of the other indexed variables is not
remembered
 To determine the address of a[3]
 Start at a[0]
 Count past enough memory for three integers to find a[3]

Chapter 1- Array and Structures in C++


Array Index Out of Range

 A common error is using a nonexistent index


 Index values for int a[6] are the values 0 through 5
 An index value not allowed by the array declaration
is out of range
 Using an out of range index value doe not produce
an error message!
 Attempts to read a value out of range returns 0 and attempts to set a value out of range has no effect.

Chapter 1- Array and Structures in C++


Out of Range Problems

 If an array is declared as: int a[6];


and an integer is declared as: int i = 7;
 Executing the statement a[i] = 238; causes…
 The computer to calculate the address of the illegal a[7]

(This address could be where some other variable is stored)

 The value 238 is stored at the address calculated for a[7]

 No warning is given!

Chapter 1- Array and Structures in C++


Initializing Arrays

 To initialize an array when it is declared


 The values for the indexed variables are enclosed
in braces and separated by commas
 Example: int children[3] = { 2, 12, 1 };
Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;

Chapter 1- Array and Structures in C++


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

Chapter 1- Array and Structures in C++


Un-initialized Arrays

 If no values are listed in the array declaration,


some compilers will initialize each variable to a
zero of the base type
 DO NOT DEPEND ON THIS!

Chapter 1- Array and Structures in C++


10.5

Multi-Dimensional Arrays

 C++ allows arrays with multiple index values


 Eg. char page [30] [100];
declares an array of characters named page
 page has two index values:
 The first ranges from 0 to 29

 The second ranges from 0 to 99

 Each index is enclosed in its own brackets


 Page can be visualized as an array of
30 rows and 100 columns
 “page’s” base type is character array of 100

Chapter 1- Array and Structures in C++


Multidimensional array parameter
When a multidimensional array parameter is given in a function
heading or function declaration, the size of the first dimension is
not given,
but the remaining dimension sizes must be given in square
brackets.
Since the first dimension size is not given, you usually need an
additional parameter of type int that gives the size of this first
dimension

Chapter 1- Array and Structures in C++


Multidimensional Array Parameters cont’d…

 The size of an array is not needed


when declaring a formal parameter in a function declaration:
void display_line(const char a[ ], int size);
 The base type of a multi-dimensional array must
be completely specified in the parameter
declaration
 void display_page(const char page[ ] [100],
int size_dimension_1);

Chapter 1- Array and Structures in C++


Program Example: Grading Program

 Grade records for a class can be stored in a


two-dimensional array
 For a class with 4 students and 3 quizzes the array
could be declared as

int grade[4][3];
 The first array index refers to the number of a student
 The second array index refers to a quiz number

 Since student and quiz numbers start with one,


we subtract one to obtain the correct index

Chapter 1- Array and Structures in C++


Grading Program: average scores

 The solution in the next slides is done using functions to compute averages of students and quizzes. Since
we have not covered functions yet , just take the logic in the program to solve the problem stated above.
 The grading program uses one-dimensional
arrays to store…
 Each student's average score
 Each quiz's average score
 The functions that calculate these averages
use global constants for the size of the arrays
 This was done because the
functions seem to be
particular to this program

Chapter 1- Array and Structures in C++


Code to prepare the averages (1/3)

Chapter 1- Array and Structures in C++


Code to prepare the averages (2/3)

Chapter 1- Array and Structures in C++


Code to prepare the averages (3/3)

Chapter 1- Array and Structures in C++


The view of the two-Dimensional Array for the grading problem

Chapter 1- Array and Structures in C++


Another view of two-Dimensional Array of the grading problem

Chapter 1- Array and Structures in C++


Structures

 Recall that elements of arrays


0 1 2 3 4 5 98 99
must all be of the same type
scores : 85 79 92 57 68 80 . . .

 In some situations, we wish to group


elements of different types

employee R. Jones 123 Elm 6/12/55 14.75


Chapter 1- Array and Structures in C++
Structures
Structure: A programmer-defined data type that
allows multiple variables types to be grouped
together
Structure declaration format:
struct structure name
{
type1 field1;
type2 field2;

typen fieldn;
};
Chapter 1- Array and Structures in C++
Example struct Declaration

struct StudentStruct
structure name
{
int studentID;
string name; structure members
short year;
double gpa;
}; Note the
required
Chapter 1- Array and Structures in C++
;
struct Declaration Notes

struct names commonly begin with an


uppercase letter, because they are a type
Multiple fields of same type can be declared
in a comma-separated list
string name,address;
Fields in a structure are all public by default

Chapter 1- Array and Structures in C++


Defining Structure Variables

A struct declaration does not allocate


memory or create variables, because they are a
type
To define variables, use structure tag as the type
name s1
studentID
StudentStruct s1;
name
year

gpa

Chapter 1- Array and Structures in C++


Accessing Structure Members
Use the name of the struct variable
the name of the member
separated by a dot .

getline(cin, s1.name);
cin >> s1.studentID;
s1.gpa = 3.75;

The dot is called the member selector


Chapter 1- Array and Structures in C++
Aggregate Operations with Structures

 Recall that arrays had no whole array operations (except passing reference to parameter)
 Structures DO have aggregate operators
 assignment statement =
 parameter (value or reference)
 return a structure as a function type

Chapter 1- Array and Structures in C++


Aggregate Operations with Structures

 Limitations on aggregate operations


 no I/O cout << old_part;
cin >> new_part;

 no arithmetic operations

old_part = new_part + old_part;

 no comparisons if (old_part < new_part)


cout << ...;
Chapter 1- Array and Structures in C++
Aggregate Operations with Structures


struct variables must be initialized, compared, written one member at a time.

Chapter 1- Array and Structures in C++


Displaying struct Members

To display the contents of a struct variable, you


must display each field or member separately, using
the dot operator
Wrong:
cout << s1; // won’t work!

Correct:
cout << s1.studentID << endl;
cout << s1.name << endl;
cout << s1.year << endl;
cout << s1.gpa;
Chapter 1- Array and Structures in C++
Comparing struct Members

Similar to displaying a struct, you cannot


compare two struct variables directly:

if (s1 >= s2) // won’t work!

Instead, compare member variables:

if (s1.gpa >= s2.gpa) // better

Chapter 1- Array and Structures in C++


Initializing a Structure

Structure members cannot be initialized in the structure


declaration, because no memory has been allocated yet

struct Student // Illegal


{ // initialization
int studentID = 1145;
string name = "Alex";
short year = 1;
float gpa = 2.95;
};

Chapter 1- Array and Structures in C++


Initializing a Structure (continued)

Structure members are initialized at the time a


structure variable is created
You can initialize a structure variable’s members
with either
o an initialization list on structure variable declaration.
o a constructor – not seen here

Chapter 1- Array and Structures in C++


Initialization List Example

Structure Declaration Structure Variable


box
struct Dimensions length 12
{ int length,
width 6
width,
height 3
height;
};
Dimensions box = {12,6,h};
Chapter 1- Array and Structures in C++
Nested Structures
A structure can have another structure as a
member.
struct PersonInfo
{ string name,
address,
city;
};
struct Student
{ int studentID;
PersonInfo pData;
short year;
double gpa;
};
Chapter 1- Array and Structures in C++
Members of Nested Structures
Use the dot operator multiple times to access fields of nested
structures
Student s5;
s5.pData.name = "Joanne";
s5.pData.city = "Tulsa";
Reference the nested structure’s fields by the member variable name,
not by the structure name
s5.PersonInfo.name = "Joanne"; //no!

Chapter 1- Array and Structures in C++


Structures as Function Arguments

You may pass members of struct variables to


functions
computeGPA(s1.gpa);

You may pass entire struct variables to


functions by value or by reference
void CopyPart (PartStruct partOrig, PartStruct &
partNew);

Chapter 1- Array and Structures in C++


Notes on Passing Structures

 Using a value parameter for structure can slow down a


program and waste space
 Using a reference parameter speeds up program
execution, but it allows the function to modify data in
the structure
 To save space and time while protecting structure data
that should not be changed, use a const reference
parameter
void showData(const StudentStruct &s)
// header

Chapter 1- Array and Structures in C++


Returning a Structure from a Function

A function can return a struct


StudentStruct getStuData(); // prototype
s1 = getStuData(); // call

The function must define a local structure variable


o for internal use
o to use with return statement

Chapter 1- Array and Structures in C++


Returning a Structure Example
Student getStuData()
{ Student s; // local variable
cin >> s.studentID;
cin.ignore();
getline(cin, s.pData.name);
getline(cin, s.pData.address);
getline(cin, s.pData.city);
cin >> s.year;
cin >> s.gpa;
return s;
}
Chapter 1- Array and Structures in C++
Contrast - Arrays and structs

Chapter 1- Array and Structures in C++


Arrays of structs

 First declare a struct (such as PartStruct)


 Then specify an array of that type

typedef PartStruct PartsArray [50];


 Access elements of the array, elements of the struct

How do we for (x = 0; x <50; x++)


print all the parts [x].descript;
cout << _______________________;
descrip fields?
Chapter 1- Array and Structures in C++
structs with Arrays

 Example

const ARRAYSIZE = 1000;

struct LISTTYPE
{
int list [ARRAYSIZE]; //array containing the list
int listLength; //length of the list
}

Chapter 1- Array and Structures in C++


Hierarchical structures

struct InventoryStruct {
 Defn => structs where at least one of the PartStruct
components is, itself, apart;
struct
 Example: int qty_sold,
re_order_qty;
VendorStruct
vendor; };

Chapter 1- Array and Structures in C++


Choosing Data Structures

 Strive to group logical elements of a structure together


 calls for hierarchical structures

 Push details of entities down to lower levels of the structure


 Data Abstraction <=> separation of logical peoperties of a data type from its implementation

Chapter 1- Array and Structures in C++


Testing and Debugging Hints

 Declaration of a struct type must end with a semicolon ;


 Be sure to specify the full member selector when referencing a component of a struct variable
 don’t leave out the struct name

Chapter 1- Array and Structures in C++


Testing and Debugging

 When using an array in a struct, the index goes at the end


studentRecord.scores[x]
 When using an array of struct, the index goes after the struct name
parts[x].qty

Chapter 1- Array and Structures in C++


Testing and Debugging

 Process struct members separately … the only aggregate operations will be


 Assignment =
 Parameter passing
void do_it (PartStruct part);
 Function return
PartStruct ProcessThings ( );

Chapter 1- Array and Structures in C++


Testing and Debugging

struct PartStruct struct


{ ScoresStruct {
 Be careful using same member names in different struct types

int qty; int qty;


. . . . . .
 } keeps
Compiler ; them separate OK } ;`
 Human readers can easily confuse them

Chapter 1- Array and Structures in C++

You might also like