Chapter Two: Arrays and Structure

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 54

Chapter two

Arrays and Structure


Array and structure
An array is a set of the same type of data, and a structure is a just a set
of data that aren't necessarily the same type. 
Here is an example. 
int SomeArray[5]= {1,2,3,4,5}; 
struct SomeStructure { 
int Number; 
string Sentence; 
} ; 
A structure in C++ is a user-defined type which may contain data
members (subobjects), possibly virtual member functions,
constructors, destructors, operators, etc,. A structure can inherit
from other structures and classes and can be inherited from. A
structure is a basic building block of class hierarchy (in fact, it is the
same thing as a class, except for the default access permission at
the start of its body) 
Difference Between Array and Stucture
structure
A data structure is a group of data elements grouped together under one name. These
data elements, known as members, can have different types and different lengths.
Data structures can be declared in C++ using the following syntax:
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
} object_names;
Where type_name is a name for the structure type, object_name can be a set of valid
identifiers for objects that have the type of this structure. Within braces {}, there is a
list with the data members, each one is specified with a type and a valid identifier as
its name.

For example:
struct product {
int weight;
double price;
} ;product apple; product banana, melon;
Cont…
Once the three objects of a determined structure type are declared
(apple, banana, and melon) its members can be accessed directly.
The syntax for that is simply to insert a dot (.) between the object
name and the member name. For example, we could operate with
any of these elements as if they were standard variables of their
respective types: 
apple.weight
apple.price
banana.weight
banana.price
melon.weight
melon.price
example
// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year; } mine, yours;
void printmovie (movies_t movie);
int main () {
string mystr; mine.title = "2001 A Space Odyssey";
mine.year = 1968;
cout << "Enter title: "; getline (cin,yours.title);
cout << "Enter year: "; getline (cin,mystr);
stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n "; printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours); return 0; }
void printmovie (movies_t movie)
{
cout << movie.title; cout << " (" << movie.year << ")\n"; }
Array
• Given 5 numbers, read them in and
calculate their average
• THEN print out the ones that were above
average
Data Structure Needed
Need some way to hold onto all the individual data items after processing them
making individual identifiers x1, x2, x3,... is not practical or flexible
the answer is to use an ARRAY
a data structure - bigger than an individual variable or constant
• Data structures containing related data items of same type
• Always remain the same size once created
• Array
– Consecutive group of memory locations
• All of which have the same type
– Index
• Position number used to refer to a specific location/element
• Also called subscript
• Place in square brackets
– Must be positive integer or integer expression
• First element has index zero, last element has index n-1
Properties of an array
Homogeneous
Contiguous
Have random access to any element
Ordered (numbered from 0 to n-1)
Number of elements does not change - MUST be a constant when
declared
Declaring Arrays
• Declaring an array
– Arrays occupy space in memory
– Programmer specifies type and number of elements
Syntax
Datatype array_idef[howmany];
• Example
– int c[ 12 ];
» c is an array of 12 ints
– Array’s size must be an integer constant greater than
zero
– Multiple arrays of the same type can be declared in a
single declaration
• Use a comma-separated list of names and sizes
• Example int c[], d[];
Arrays (Cont.)

• To refer to individual elements


– array_idef [ ] with index in the brackets
• Example (assume a = 5 and b = 6)
– c[ a + b ] += 2;
» Adds 2 to array element c[ 11 ]
Fig.7.1 | Array of 12 elements
Arrays (Cont.)
• Examine array c in the figure
– c is the array name
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
• Brackets used to enclose an array
subscript are actually an operator in C++
Declaration of an Array

• The index is also called the subscript


• In C++, the first array element always has
subscript 0, the second array element has
subscript 1, etc.
• The base address of an array is its beginning
address in memory

14
Using a named constant

it is very common to use a named constant


to set the size of an array
E.g.
const int SIZE = 15;
int arr[SIZE];
useful because it can be used to control
loops throughout program
easy to change if size of array needs to be
changed
•It is important to note the difference between the “seventh
element of the array” and “array element 7.” Array subscripts
begin at 0, so the “seventh element of the array” has a
subscript of 6, while “array element 7” has a subscript of 7 and
is actually the eighth element of the array. Unfortunately, this
distinction frequently is a source of off-by-one errors. To avoid
such errors, we refer to specific array elements explicitly by
their array name and subscript number (e.g., c[ 6 ] or
c[ 7 ]).
Solution to problem
int counter = 0, n[5], average = total / 5;
total = 0; counter = 0;
float average; while (ct < 5)
while (counter < 5) {
{ if (n[ct] > average)
cout << "enter a number "; cout << n[ct];
cin >> n[counter]; ct = ct + 1;
total = total + n[counter]; }
counter = counter + 1;
}
Initializing Array
• Initializing an array in a declaration with an
initializer list
– Initializer list
• Items enclosed in braces ({})
• Items in list separated by commas
• Example
– int n[] = { 10, 20, 30, 40, 50 };
» Because array size is omitted in the
declaration, the compiler determines the
size of the array based on the size of the
initializer list
» Creates a five-element array
» Index values are 0, 1, 2, 3, 4
» Initialized to values 10, 20, 30, 40, 50,
respectively
Initializing Array
• Initializing an array in a declaration with
an initializer list (Cont.)
– If fewer initializers than elements in the array
• Remaining elements are initialized to zero
• Example
– int n[ 10 ] = { 0 };
» Explicitly initializes first element to zero
» Implicitly initializes remaining nine elements to
zero
– If more initializers than elements in the array
• Compilation error
Initialization of arrays
• int a[] = {1, 2, 9, 10}; // has 4 elements
• int a[5] = {2, 5, 4, 1, -2, 5}; // error!
• int a[5] = {2, 3}; // rest are zero
• int a[5] = {0}; // all are zero
• can use it with char, float, even bool
Watch out index out of range!
• subscripts range from 0 to n-1
• the compiler will NOT tell you if an index
goes out of that range - it cannot detect
• can make very bad bugs
– from just garbage values in your data to
– crashing your computer to
– damaging your hard drive!
// Initializing an array.
#include <iostream.h>
#include <iomanip.h>
int main()
{
int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ )
n[ i ] = 0; // set element at location i to 0

// output each array element's value


for ( int j = 0; j < 10; j++ )
cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;

return 0; // indicates successful termination


} // end main

Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
Assigning Values to
Individual Array Elements
float temps[5];
int m = 4; // Allocates memory
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
7000 7004 7008 7012 7016

99.4 ? 98.6 101.2 50.6


temps[0] temps[1] temps[2] temps[3] temps[4] 23
What values are assigned?
float temps[5]; // Allocates memory
int m;

for (m = 0; m < 5; m++)


{
temps[m] = 100.0 + m * 0.2 ;
}

7000 7004 7008 7012 7016

? ? ? ? ?
temps[0] temps[1] temps[2] temps[3] temps[4] 24
Now what values are printed?
float temps[5]; // Allocates memory
int m;
.....
for (m = 4; m >= 0; m--)
{
cout << temps[m] << endl;
}

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8


temps[0] temps[1] temps[2] temps[3] temps[4] 25
Indexes
• subscripts can be constants or variables
or expressions
• if i is 5, a[i-1] refers to a[4] and a[i*2] refers
to a[10]
• you can use i as a subscript at one point in
the program and j as a subscript for the
same array later - only the value of the
variable matters
Variable Subscripts
float temps[5]; // Allocates memory
int m = 3;
. . . . . .
What is temps[m + 1] ?

What is temps[m] + 1 ?
7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8


temps[0] temps[1] temps[2] temps[3] temps[4]
27
1 // Fig. 7.5: fig07_05.cpp
2 // Set array s to the even integers from 2 to 20.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <iomanip>
8 using std::setw;
9
10 int main()
11 {
12 // constant variable can be used to specify array size
13 const int arraySize = 10;
14
15 int s[ arraySize ]; // array s has 10 elements
16
17 for ( int i = 0; i < arraySize; i++ ) // set the values
18 s[ i ] = 2 + 2 * i;
Multidimensional Array
• Multidimensional arrays with two dimensions
– Called two dimensional or 2-D arrays
– Represent tables of values with rows and columns
– Elements referenced with two subscripts ([x][y])
– In general, an array with m rows and n columns is
called an m-by-n array
– E.g.
• int a[5][4]; // row then column
• twenty elements, numbered from [0][0] to [4][3]
– Multidimensional arrays can have more than two
dimensions
Two-Dimensional Array
• A two-dimensional array is a collection of
components, all of the same type, structured in two
dimensions, (referred to as rows and columns)
• Individual components are accessed by a pair of
indexes representing the component’s position in
each dimension

DataType ArrayName[ConstIntExpr][ConstIntExpr]...;

30
Processing a 2-d array by rows
finding the total for the first row
for (i = 0; i < 5; i++)
total = total + a[0][i];
finding the total for the second row
for (i = 0; i < 5; i++)
total = total + a[1][i];
Processing a 2-d array by rows
total for ALL elements by adding first row,
then second row, etc.

for (i = 0; i < 5; i++)


for (j = 0; j < 4; j++)
total = total + a[i][j];
Processing a 2-d array by
columns
total for ALL elements by adding first
column, second column, etc.

for (j = 0; j < 4; j++)


for (i = 0; i < 5; i++)
total = total + a[i][j];
Declaring Multidimensional Arrays
Example of three-dimensional array
const NUM_DEPTS = 5;
// mens, womens, childrens, electronics, furniture
const NUM_MONTHS = 12;
const NUM_STORES = 3; // White Marsh, Owings Mills, Towson

int monthlySales[NUM_DEPTS][NUM_MONTHS][NUM_STORES];

rows columns sheets

34
Initializing Multidimensional Arrays
• To initialize a multidimensional arrays , you must assign the list of
values to array elements in order, with last array subscript changing
while the first subscript while the first subscript holds steady.
Therefore, if the program has an array int theArray[5][3], the first
three elements go int theArray[0]; the next three into theArray[1];
and so forth.
• The program initializes this array by writing
• int theArray[5][3] ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; for
the sake of clarity, the program could group the initializations with
braces, as shown below.
• int theArray[5][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13,
14,15} }; The compiler ignores the inner braces, which clarify how
the numbers are distributed.
• Each value should be separated by comma, regardless of whither
inner braces are include. The entire initialization must set must
appear within braces, and it must end with a semicolon.
String manipulation using arrays

• Character in C++
• The C++ library provides several macros
for testing characters.
– Be sure to include ctype.h header file
Character Description
Macro

isalpha Returns true (a nonzero number) if the argument is a letter of the alphabet.
Returns 0 if the argument is not a letter.
isalnum Returns true (a nonzero number) if the argument is a letter of the alphabet or a
digit. Otherwise it returns 0.
isdigit Returns true (a nonzero number) if the argument is a digit 0–9. Otherwise it
returns 0.
islow er Returns true (a nonzero number) if the argument is a lowercase letter.
Otherwise, it returns 0.
isprint Returns true (a nonzero number) if the argument is a printable character
(including a space). Returns 0 otherwise.
ispunct Returns true (a nonzero number) if the argument is a printable character other
than a digit, letter, or space. Returns 0 otherwise.
isupper Returns true (a nonzero number) if the argument is an uppercase letter.
Otherwise, it returns 0.
isspace Returns true (a nonzero number) if the argument is a whitespace character.
#include <iostream.h>
#include <ctype.h>

void main(void)
{
char input;
cout << "Enter any character: ";
cin.get(input);
cout << "The character you entered is: " << input <<
endl;
cout << "Its ASCII code is: " << int(input) << endl;
if (isalpha(input))
cout << "That's an alphabetic character.\n";
if (isdigit(input))
cout << "That's a numeric digit.\n";
if (islower(input))
cout << "The letter you entered is lowercase.\n";
if (isupper(input))
cout << "The letter you entered is uppercase.\n";
if (isspace(input))
cout << "That's a whitespace character.\n";
}
Program Output With Example input
Enter any character: A [Enter]
The character you entered is: A
Its ASCII code is: 65
That's an alphabetic character.
The letter you entered is uppercase.

Program Output With Other Example input


Enter any character: 7 [Enter]
The character you entered is: 7
Its ASCII code is: 55
That's a numeric digit.
Strings 
• C++ has no built-in String type like some
programming languages
• Strings are implemented as null terminated
arrays of characters.
• char [3] abc = “me”
– array abc consists of “m”, “e”, null
• abc = “me” (shortcut for defining and
initializing a string)
Review of the Internal Storage
of C++ strings
• A C++ string is a sequence of characters
stored in consecutive memory locations,
terminated by a null character.
e.g. char string[7] = “Bailey”;
Library Functions for Working
with strings in C++
• The C++ library has numerous functions
for handling C-strings These functions
perform various tests and manipulations.
• string functions are in <string.h>
• So we need to include the string.h header
file to use the Functions
Function Description
strlen Accepts a C-string or a pointer to a string as an argument. Returns the length of the
string (not including the null terminator. Example Usage: len = strlen(name);
strcat Accepts two C-strings or pointers to two strings as arguments. The function appends
the contents of the second string to the first string. (The first string is altered, the
second string is left unchanged.) Example Usage: strcat(string1, string2);
strcpy Accepts two C-strings or pointers to two strings as arguments. The function copies
the second string to the first string. The second string is left unchanged. Example
Usage: strcpy(string1, string2);
strncpy Accepts two C-strings or pointers to two strings and an integer argument. The third
argument, an integer, indicates how many characters to copy from the second string
to the first string. If the string2 has fewer than n characters, string1 is padded with
'\0' characters. Example Usage: strncpy(string1, string2, n);
strcm p Accepts two C-strings or pointers to two string arguments. If string1 and string2are
the same, this function returns 0. If string2 is alphabetically greater than string1, it
returns a negative number. If string2 is alphabetically less than string1, it returns a
positive number. Example Usage: if (strcmp(string1, string2))
strstr Accepts two C-strings or pointers to two C-strings as arguments, searches for the
first occurrence of string2 in string1. If an occurrence of string2 is found, the
function returns a pointer to it. Otherwise, it returns a NULL pointer (address 0).
Example Usage: cout << strstr(string1, string2);
#include <iostream.h>
#include <string.h>
void main() {
char str1[] = "String test";
char str2[] = "Hello";
char one[10];
strncpy(one, str1, 9);
one[9] = '\0';
cout << one << endl;
strncpy(one, str2, 2);
cout << one << endl;
strcpy(one, str2);
cout << one << endl;
}
String compare
#include <iostream.h>
#include <string.h>
void main() {
cout << strcmp("abc", "def") << endl;
cout << strcmp("def", "abc") << endl;
cout << strcmp("abc", "abc") << endl;
cout << strcmp("abc", "abcdef") << endl;
cout << strcmp("abc", "ABC") << endl;
}
String Output
• A string is output by sending it to an output
stream
• E.g
char str[20]=“hello”;
cout<<“ the string str is:”<<str;
String input
• When the input stream cin is used space
characters, newline , tab, etc. are used as
separators and terminators.
– skips over any leading spaces
– terminates reading a value when it finds a white-
space character
– E.g.
Char name[20];
cout<<“enter your name”;
cin>>name
Input: My name is Dawit
Output: My
// This program cycles through a character array,
displaying
// each element until a null terminator is encountered.
#include <iostream.h>

void main(void)
{
char line[80];
int count = 0;

cout << "Enter a sentence of no more than 79


characters:\n";
cin.getline(line, 80);
cout << "The sentence you entered is:\n";
while (line[count] != '\0')
{
cout << line[count];
count++;
}
}
Program Output with Example input
Enter a sentence of no more than 79 characters:
C++ is challenging but fun! [Enter]
The sentence you entered is:
C++ is challenging but fun!
User defined data types (UDT)
• The Type Definition
• In the previous lessons, we used some of C++ keywords
to identify the data types. Examples
were int, short, double, unsigned int, or char. The C+
+ language allows you to create a new name for a data
type without changing the meaning of that data type.
This allows you to name a data type with a name that is
easier for you. This technique doesn't change anything
about the data type, it only gives it a new name you can
use in your program.
Cont…
• To re-define the name of an existing data type, you use
the typedef keyword. The formula to follow is:
• typedefKnownDataTypeNewName;
• The typedef keyword is required to let the compiler
know that you are redefining an existing data type.
The DataType is any of those we have learned so far. It
could be an int, anunsigned int, a char, a double, etc.
While a data type can be made of one word (such
asshort) or more than one word (such as unsigned int),
the new name you are creating for the data type must be
in one word.
Cont…
• An example of renaming a data type is:
• typedef int NumberOfStudents;In this case, NumberOfStudents is just a
new name for an int. It can be used as a new data type exactly as if you
were using an int. Here is an example that redefines an int data type and
uses it in a program:
#include <iostream>
using namespace std;
int main() {
typedef int NumberOfStudents;
NumberOfStudents Grade1, Grade2;
cout << "Enter the number of students.\n";
cout << "Grade 1: ";
cin >> Grade1; cout << "Grade 2: ";
cin >> Grade2;
cout << "\nNumber of students:";
cout << "\n1st Grade: " << Grade1;
cout << "\n2nd Grade: " << Grade2 << "\n\n"; return 0; }
Cont…
Here are examples of creating new names of existing data types
using typedef:
• typedef unsigned int UINT; typedef unsigned char UCHAR; typedef
unsigned long ULONG; typedef long double LONGDOUBLE;

You might also like