• No results found

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

N/A
N/A
Protected

Academic year: 2021

Share "Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c"

Copied!
15
0
0

Loading.... (view fulltext now)

Full text

(1)

TNCG18 (C++): Lec 3 1

Lecture 3

• Data structures

– arrays

– structs

• C strings: array of chars

• Arrays as parameters to functions

• Multiple subscripted arrays

• Struct s as parameters to functions

• Default arguments

• Inline functions

• Redirection of stdin and stdout

TNCG18 (C++): Lec 3 2

Arrays

• Consecutive group of memory locations of the same type.

• To refer to an element (e.g. 3rd)

c[2]

• First element at position 0

• ith element at position i-1

c[6]

-45 6 0 72 1543 -89

0 62 -3

1 6453 78 Name of array

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

Position number of the element within array c

int c[12];

(2)

TNCG18 (C++): Lec 3 3

Arrays

• Array elements like other variables

– Assignment and printing for an integer array c

c[ 0 ] = 3;

cout << c[ 0 ] << endl;

• Can perform operations inside subscript

c[ 5 – 2 ] same as c[3]

Declaring Arrays

• When declaring arrays, specify

– type arrayName[ arraySize ];

int c[10]; // array of 10 integers float d[3284]; // array of 3284 floats

– The array size can be defined as a constant

const int arraySize = 10; See Fig04_06.cpp int c[ arraySize ];

• Declaring multiple arrays of same type

– Use comma separated list, like regular

variables

int b[ 100 ], x[ 27 ];

(3)

TNCG18 (C++): Lec 3 5

Initializing Arrays

• With a loop

See Fig04_03.cpp, Fig04_05.cpp

• Initializer list

See Fig04_04.cpp

– Specify each element when array declared

int n[ 5 ] = { 1, 2, 3, 4, 5 };

int v[ 100 ] = {0};

– If too many initializers then syntax error – If array size omitted, initializers determine

size

int n[] = { 1, 2, 3, 4, 5 };

• 5 initializers, therefore 5 element array

TNCG18 (C++): Lec 3 6

Defining Array Size

• Can be specified with constant variable

const

int size = 20;

char v[size];

• Constants cannot be changed

• Constants must be initialized when declared

• Also called read-only variables

See Fig04_08.cpp Fig04_07.cpp

(4)

TNCG18 (C++): Lec 3 7

Examples

• Histogram

– SeeFig04_10.cpp

• Throwing a dice and counting frequencies – See Fig04_11.cpp

• Listing student grades frequencies – See Fig04_09.cpp

• Compute mean, median, and mode – See Fig04_17.cpp

Arrays in C++

• No range checking

• The array does not ”know” its size

• Cannot input or output an array directly , except strings

• Comparison and assignment not

implemented

(5)

TNCG18 (C++): Lec 3 9

Character Arrays

• C strings

– Arrays of characters

– All C strings end with null ('\0')

• char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0’ };

• char string1[] = "hello";

– Nullcharacter implicitly added – string1has 6 elements

– Subscripting

• string1[0]is 'h‘

• string1[2]is 'l'

TNCG18 (C++): Lec 3 10

Character Arrays

• Input from keyboard

char string2[ 10 ];

cin >> string2;

– Reads user input in string2

• Stops at first white space character

• Adds null character

– If too much text entered, data written beyond array

#include <iomanip>

char string3[ 5 ];

cin >> setw(5) >> string3;

See Fig04_12.cpp

Reads at most 4 chars and last array position is for the null

(6)

TNCG18 (C++): Lec 3 11

Character Arrays

• Printing strings

cout << string2 << endl;

• Does not work for other array types

– Characters printed until null character found

Passing Arrays to Functions

• Function prototype

void modifyArray( int b[], int arraySize );

void modifyArray( int [], int);

• No need for array size between brackets

• Ignored by compiler

• Array parameter as const

• Array values cannot be modified (compiler error)

void doNotModify( const int [] );

• See Fig04_15.cpp

(7)

TNCG18 (C++): Lec 3 13

Calling Functions with Array Arguments

• Call function modifyArray

– To pass array myArray to modifyArray

int myArray[24];

modifyArray(myArray, 24);

• Array size is usually an argument

– Not required

– Useful to iterate over all elements

TNCG18 (C++): Lec 3 14

Passing Arrays to Functions

• Arrays passed-by-reference

– Functions can modify original array data – The array’s name is address of first element

• Function knows where the array is stored

• Can change original memory locations

• Individual array elements passed-by-value

– Like regular variables

square(myArray[3]);

– See Fig04_14.cpp

(8)

TNCG18 (C++): Lec 3 15

Default Arguments

• Function prototype

void modifyArray( int b[], int arraySize = 100);

• Function call

int v[100];

modifyArray(v);

//modifyArray(v, 100);

modifyArray(myArray, 24);

Default value

Static Local Arrays

• If

static

, local variables are saved between function calls

– Visible only in function body – Used for performance reasons – Can declare local arrays to be static

• Initialized to zero by default

static int array[3];

• If not static

– Created (and destroyed) in every function call

See Fig04_13.cpp

(9)

TNCG18 (C++): Lec 3 17

Multiple-Subscripted Arrays

• Multiple subscripts

– a[ i ][ j ] int a[ 3 ][ 4 ];

– Tables with rows and columns – Specify row, then column – “Array of arrays”

• a[0]is an array of 4 elements

• a[0][0] is the first element of that array

Row 0 Row 1 Row 2

Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ]

a[ 1 ][ 0 ] a[ 2 ][ 0 ]

a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ]

a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ]

a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ]

Row subscript Array name

Column subscript

TNCG18 (C++): Lec 3 18

Multiple-Subscripted Arrays

• To initialize

– Initializers grouped by row in braces

int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

1 2 3 4

1 0 3 4 Row 0 Row 1

(10)

TNCG18 (C++): Lec 3 19

Multiple-Subscripted Arrays

• Access to an element cout << b[0][1];

– Outputs 0

– Cannot access an element using commas cout << b[0, 1];

• Syntax error!!!

• Function prototypes

– Must specify sizes of subscripts

• First subscript not necessary, as with single- scripted arrays

void printArray( int [][2], int size );

1 0 3 4

See Fig04_22.cpp See Fig04_23.cpp

StructureType in C++

struct

is used to contain data of different types

struct Card { int value;

char suit [10]; //field, member };

Card ace = {13, ”Hearts”}; // initialization

• Size (i.e. number of bytes)?

• sizeof(ace).

(11)

TNCG18 (C++): Lec 3 21

Structure Type

• How do you write in C?

typedef struct { int value; //

char suit [10];

} Card;

Card ace = {13, ”Hearts”};

TNCG18 (C++): Lec 3 22

Operations on structs

• Memberwise assignment ace.value = 1;

• Assignment is allowed Card ace2 = ace;

– Yes, array fields get copied without need to copy each field at a time !!!

– But surprise !!!,

//doesn’t compile ace2.suit = ace.suit;

//instead use a string copy function strcpy(ace2.suit, ace2.suit);

#include<cstring>

(12)

TNCG18 (C++): Lec 3 23

Operations on structs

• Comparison, input, and output are not available

if (ace2 == ace)... //does not work cin >> ace2; //does not work

• Implement your own functions

– Overload operators ==, >> and <<

See Fig06_01.cpp

Using Structures as Function Arguments

• Pass the structure argument by value

void printCard(Card c){

cout << “Value: “ << c.value

<< “Suit: “ << c.suit << endl;

}

• Pass an array by value to a function

– Create a structure with the array as a member

• See struct1.cpp

(13)

TNCG18 (C++): Lec 3 25

Using Structures as Function Arguments

• Pass the structure argument by reference

void printCard(const Card &c){

cout << “Value: “ << c.value

<< “Suit: “ << c.suit

<< endl;

}

– Pass-by-reference more efficient

TNCG18 (C++): Lec 3 26

Inline Functions

inline double cube(const double side) { return side * side * side;

}

int main() { double val;

cin >> val;

cout << “Cube volume: ”

<< cube(val) << endl;

return 0;

}

(14)

TNCG18 (C++): Lec 3 27

• Function call replaced by functions code

– Only used for small functions

– Compiler is free to ignore the inline qualifier

– Advantage

• Efficiency: avoid function call overhead

– Disadvantages

• Changes in a inline function require that whole project to be recompiled

• Program size increases

Inline Functions

Reading a Sequence of Values

• cin >> k returns

0

when

– EOF is found or

– a value of the wrong type is given

int main(){

int k, sum = 0;

while (cin >> k) sum += k;

cout << sum << endl;

return 0;

} See sum.cpp

(15)

TNCG18 (C++): Lec 3 29

Reading Variables

int k;

cin >> k;

cout << k;

int k;

if (cin >> k) cout << k;

Prints any trash in k, if user gives a non-integer value.

No problem!!!

TNCG18 (C++): Lec 3 30

Redirection of input and output

• Redirection of input (DOS and Unix)

sum < input.txt

reads sequence of ints from file input.txt

• Redirection of output

sum > output.txt

writes the result to file output.txt

• Piping (DOS and Unix)

dice | sum

output of dice.exe is

redirected as input to sum.exe

References

Related documents

The one that impressed me was the way the business leaders have picked up all three and have really put the focus on getting the basics right, getting the stability right,

However, task relevant colour did affect response inhibition as participants were 25ms faster to countermand their response when the stop signal was red versus green (Exp 3)..

Data collected as part of this IRWMP can be used to support existing state programs such as the Surface Water Ambient Monitoring Program, the Groundwater Ambient Monitoring and

We find positive wage spillovers for medium-skilled workers with wages just above the minimum wage, but negative effects for high-skilled top earners in East Germany, where the bite

(Bottom panels) Global stress (left panel) and Net reduction (total number of ICU beds or ventilators efficiently transferred, right panel) offered by the sequential,

Preliminary work for the Minnesota DOT and Local Roads Research Board (MnDOT/LRRB), titled Field Usage of Alternative Deicers for Snow and Ice Control, recommended laboratory

The mechanical properties of concrete specimens containing different percentages of shell husk aggregates namely 0, 10%, 20%, 30%, and 40% in the ratio of mass are

This research paper highlights the integration efforts estimation using a work flow model, to accurately estimate the efforts and cost needed for SOA application.. Keywords: