Chapter Two: Arrays and Structure
Chapter Two: Arrays and Structure
Chapter Two: Arrays and Structure
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.)
14
Using a named constant
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
? ? ? ? ?
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;
}
What is temps[m] + 1 ?
7000 7004 7008 7012 7016
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.
int monthlySales[NUM_DEPTS][NUM_MONTHS][NUM_STORES];
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.
void main(void)
{
char line[80];
int count = 0;