1 of 103

C++ Primer (continued)

C. Papachristos

Robotic Workers Lab

University of Nevada, Reno

CS-202

2 of 103

Course Week

CS-202 C. Papachristos

Course , Projects , Labs:

Your 1st Lab was/is today Thursday 1/23.

Your 1st Project will be announced today Thursday 1/23.

  • Project is graded.
  • Project Deadline is next Wednesday night 1/29 @ 11:59 pm (firm).

Monday

Tuesday

Wednesday

Thursday

Friday

 

 

 

Lab (8 Sections)

 

 

CLASS

 

CLASS

 

PASS Session�(Tentative)

PASS Session�(Tentative)

Project DEADLINE

NEW Project

 

3 of 103

Today’s Topics

CS-202 C. Papachristos

Operators & Expressions

Scope & Resolution

Statements & Flow Control

Namespaces & Resolution

C++ Input / Output

Arrays

4 of 103

Operators & Expressions

CS-202 C. Papachristos

Operators (General)

A variety of operators in programming languages:

  • Unary (1), Binary (2), Ternary (3)

(depends on number of operands, i.e. things they operate on)

Represented by special symbolic characters

  • ( + ) means add( , ) , hence it is a Binary operator.

5 of 103

Operators & Expressions

CS-202 C. Papachristos

Operator Precedence Order

Precedence

Operator

Description

Associativity

1

::

Left-to-right

2

a++   a--

Suffix/postfix increment and decrement

type()   type{}

a()

a[]

.   ->

3

++a   --a

Right-to-left

+a   -a

!   ~

(type)

*a

Indirection (dereference)

&a

sizeof

new   new[]

delete   delete[]

4

.*   ->*

Left-to-right

5

a*b   a/b   a%b

6

a+b   a-b

7

<<   >>

8

<=>

9

<   <=

For relational operators < and ≤ respectively

>   >=

For relational operators > and ≥ respectively

Precedence

Operator

Description

Associativity

10

==   !=

For relational operators = and ≠ respectively

Left-to-right

11

&

12

^

Bitwise XOR (exclusive or)

13

|

Bitwise OR (inclusive or)

14

&&

15

||

16

a?b:c

Right-to-left

throw

=

Direct assignment (provided by default for C++ classes)

+=   -=

Compound assignment by sum and difference

*=   /=   %=

Compound assignment by product, quotient, and remainder

<<=   >>=

Compound assignment by bitwise left shift and right shift

&=   ^=   |=

Compound assignment by bitwise AND, XOR, and OR

17

,

Left-to-right

6 of 103

Operators & Expressions

CS-202 C. Papachristos

Standard Arithmetic Operators

Left-to-Right Associativity, Standard rules of arithmetic Precedence

  • Parentheses
  • Multiplication ( * ), Division ( / ), Modulo ( % ) - Precedence Group 5
  • Addition ( + ), Subtraction ( - ) - Precedence Group 6
  • Exponents … (Note: Do not use ( ^ ) for exponents.)

7 of 103

Operators & Expressions

CS-202 C. Papachristos

Standard Relational Operators

Testing for:

  • Equality ( == ) , Inequality ( != )
  • Less-Than ( < ) , Higher-Than ( > )
  • Less/Equal-To ( <= ) , Higher/Equal-To ( >= )
  • Evaluate to ( true ) or ( false )

8 of 103

Operators & Expressions

CS-202 C. Papachristos

Standard Logical Operators

Evaluating:

  • Logical AND ( && ) , OR ( || ) , NOT( ! )
  • Evaluate to ( true ) or ( false )

AND�&&

a

true

false

b

true

true

false

false

false

false

OR�||

a

true

false

b

true

true

true

false

true

false

NOT�!

!a

a

true

false

false

true

9 of 103

Operators & Expressions

CS-202 C. Papachristos

Standard Bitwise Operators

Useful to conduct Bitwise operations:

(Boolean , bit-by-bit operations on Registers)

  • AND ( & ) , OR ( | ) , XOR ( ^ ) , NOT( ~ )
  • Bitwise Shifting Left ( << ) , Right ( >> )

AND &

a

b

a & b

0

0

0

0

1

0

1

0

0

1

1

1

OR |

a

b

a | b

0

0

0

0

1

1

1

0

1

1

1

1

XOR ^

a

b

a ^ b

0

0

0

0

1

1

1

0

1

1

1

0

NOT ~

a

~ a

0

1

1

0

Examples with 8-bit variables:

a

10011001

153

b

01010101

85

Bitwise AND

a & b

00010001

17

Bitwise OR

a | b

11011101

221

Bitwise XOR

a ^ b

11001100

204

Bitwise NOT

~ a

01100110

102

~ b

10101010

170

10 of 103

Operators & Expressions

CS-202 C. Papachristos

Unary Operators

  • Logical Negation ( ! )

( ! true ) is false

( ! false ) is true

  • Post-Increment ( ++ ) and Post-Decrement ( -- )

( x ++ ) evaluates to ( x ) , and x shall be increased by 1

( x -- ) evaluates to ( x ) , and x shall be decreased by 1

  • Pre-Increment ( ++ ) and Pre-Decrement ( -- • )

( ++ x ) evaluates to ( x + 1 ) , and x shall be increased by 1

( -- x ) evaluates to ( x – 1 ) , and x shall be decreased by 1

11 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

const double kmph_to_mph = 0.621371192; // km/h –to- mph

float distance_km = 100.0F; // kilometers

float time_h = 0.5F; // hours

double velocity_mph; // miles/hour

velocity_mph = kmph_to_mph * (distance_km / time_h);

An expression

Another expression

12 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

13 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

14 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

15 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

16 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

A Complex Statement (Assignment followed by Ternary Expression)

17 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

Right-to-Left Associativity of Assignment operator

18 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

Ternary Expression: Evaluation of Test Expression

19 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = (5==7) ? 1*a : -1*a ;

Result: false → Evaluates to 2nd Expression

20 of 103

Operators & Expressions

CS-202 C. Papachristos

Expressions

When simple units of operands and operators are combined into larger units, (always following the strict rules of precedence and associativity).

  • Expression is each aggregate computable unit (simpler or larger).

Conditional Ternary Operator ( ? )

Composed of Expressions:

(Test_Expression) ? (Evaluated_Expression_If_TRUE) : (Evaluated_Expression_If_FALSE)

5==7 ? printf("5 equals 7") : printf("5 does not equal 7");

int a = 10;

int b = -10;

Evaluation of Ternary Expression is a double literal

21 of 103

Operators & Expressions

CS-202 C. Papachristos

Operator Associativity

Kicks in when operators of the same

precedence appear in an Expression.

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

22 of 103

Operator Associativity

Kicks in when operators of the same

precedence appear in an Expression.

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Operators & Expressions

CS-202 C. Papachristos

Examples with Expressions:

A) 3 * 6 / 9

( 3 * 6 ) / 9

18 / 9

2

B) int x, y, z;

x = y = z = 0;

23 of 103

Operator Associativity

Kicks in when operators of the same

precedence appear in an Expression.

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Examples with Expressions:

A) 3 * 6 / 9

( 3 * 6 ) / 9

18 / 9

2

B) int x, y, z;

x = y = z = 0;

Operators & Expressions

CS-202 C. Papachristos

24 of 103

Operator Associativity

Kicks in when operators of the same

precedence appear in an Expression.

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Examples with Expressions:

A) 3 * 6 / 9

( 3 * 6 ) / 9

18 / 9

2

B) int x, y, z;

x = y = z = 0;

x = y = z = 0;

x = y = z = 0;

Operators & Expressions

CS-202 C. Papachristos

25 of 103

Operators

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Operators & Expressions

CS-202 C. Papachristos

Arithmetic precision of calculations

  • C++ Rules are a VERY important consideration here !
  • Expressions in C++ might not evaluate as you’d “expect”!

“Highest-order operand” determines type�of arithmetic “precision”.

26 of 103

Operators

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Operators & Expressions

CS-202 C. Papachristos

Arithmetic precision of calculations

“Highest-order operand” determines type�of arithmetic “precision”.

  • 17 / 5 evaluates to 3 in C++!

Both operands are ints, hence integer division is performed.

  • 17.0 / 5 evaluates to 3.4 in C++!

Highest-order operand is double (17.0), hence double precision division is performed.

27 of 103

Operators

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Operators & Expressions

CS-202 C. Papachristos

Arithmetic precision of calculations

“Highest-order operand” determines type�of arithmetic “precision”.

  • 17 / 5 evaluates to 3 in C++!

Both operands are ints : Integer division.

  • 17.0 / 5 evaluates to 3.4 in C++!

Highest-order operand is double : Double division.

  • int intVar1 = 1, intVar2 = 2;

double doubleVar = intVar1 / intVar2;

doubleVar is 0.0 !

28 of 103

Operators

Postfix operators: ++ -- (left to right)

Prefix operators: ++ -- (right to left)

Unary operators: + - ! (right to left)

* / % (left to right)

+ - (left to right)

< > <= >=

== !=

&&

||

? :

Assignment operator: = (right to left)

Operators & Expressions

CS-202 C. Papachristos

Arithmetic precision of calculations

“Calculations executed sequentially”

  • 1 / 2 / 3.0 / 4 performs 3 separate divisions.

(1 / 2) equals 0

(0 / 3.0) equals 0.0

(0.0 / 4) equals 0.0 !

  • “Just one operand” can change the result of a large expression.
  • Have to bear in mind all operands & operators rules!

29 of 103

Operators & Expressions

CS-202 C. Papachristos

Type Casting with ( )• or ()

Perform explicit type-casting conversion

Can add “.0” to literals to force precision: 15; 15.0; 15.0F;

convertedVar = (new_type)originalVar;

convertedVar = new_type(originalVar);

double x = (double) intVar1 / intVar2;

double x = double( intVar1 / intVar2 );

Casting to force double-precision division among two integer variables! DOES IT?

Alternative C++ expression:� double x = static_cast<double>( X );

int

double

float

30 of 103

Operators & Expressions

CS-202 C. Papachristos

Type Casting with ( )• or ()

Perform explicit type-casting conversion

Can add “.0” to literals to force precision: 15; 15.0; 15.0F;

convertedVar = (new_type)originalVar;

convertedVar = new_type(originalVar); valid C++ expression

double x = (double) intVar1 / intVar2;

double x = double( intVar1 / intVar2 );

Casting to force double-precision division among two integer variables! DOES IT?

Alternative C++ expression:� double x = static_cast<double>( X );

31 of 103

Operators & Expressions

CS-202 C. Papachristos

Type Casting Operator ( )• or ()

Perform explicit type-casting conversion

Can add “.0” to literals to force precision: 15; 15.0; 15.0F;

convertedVar = (new_type)originalVar;

convertedVar = new_type(originalVar);

double x = (double) intVar1 / intVar2;

double x = double( intVar1 / intVar2 );

Casting to force double-precision division among two integer variables! DOES IT?

Alternative C++ expression:� double x = static_cast<double>( X );

0.5

0.0

(For intVar1=1, intVar2=2)

32 of 103

Operators & Expressions

CS-202 C. Papachristos

Type Conversion

  • Implicit type conversion

Done by the compiler:

17 / 5.5;� “Implicit type cast” 1717.0

  • Explicit type conversion

Programmer-enforced:

(double)17 / 5.5;

double(17) / 5.5;� static_cast<double>( 17 ) / 5.5;

33 of 103

Operators & Expressions

CS-202 C. Papachristos

Shorthand Operators

  • Arithmetic operation & Assignment

Also shorthands:

  • Post-increment/decrement: i++ (evaluate expression then increment/decrement)
  • Pre-increment/decrement: ++i (increment/decrement then evaluate expression)

Shorthand Expression

count += 2;

total -= discount;

bonus *= 2;

time /= rushFactor;

change %= 100;

amount *= cnt1 + cnt2;

Equivalent Expression

count = count + 2;

total = total - discount;

bonus = bonus * 2;

time = time / rushFactor;

change = change % 100;

amount = amount * (cnt1 + cnt2);

34 of 103

Scope

CS-202 C. Papachristos

You can define new variables in many places in your code.

So where is it in effect / What is its Variable Scope?

  • The set of statements in which the variable is known to the compiler.

Where a variable can be referenced from in your program

  • Limited by the code Block in which the variable is defined

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

bool adult = false;

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

35 of 103

Scope

CS-202 C. Papachristos

You can define new variables in many places in your code.

So where is it in effect / What is its Variable Scope?

  • The set of statements in which the variable is known to the compiler.

Where a variable can be referenced from in your program

  • Limited by the code Block in which the variable is defined

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

bool adult = false;

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

36 of 103

Scope

CS-202 C. Papachristos

You can define new variables in many places in your code.

So where is it in effect / What is its Variable Scope?

  • The set of statements in which the variable is known to the compiler.

Where a variable can be referenced from in your program

  • Limited by the code Block in which the variable is defined

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

bool adult = false;

if(age >= 18) {

bool adult = true;

cout << adult;

}

cout << adult;

bool adult = false;

{

bool adult = true;

cout << adult;

}

cout << adult;

The Block Scope {}

(it’s more generic)

37 of 103

Statements

CS-202 C. Papachristos

A complete unit of execution (equivalent to a sentence in a language).

  • Expression statements

Assignment expressions

Use of ( ++ ) or ( -- )

Method invocations

Object creation

  • Flow Control statements

Selection structures

Repetition/Iteration structures

End with semicolon ( ; )

Follow Scope rules

38 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • If / then / else

Block: a group of zero or more statements that are grouped together by delimiters

( in C++ braces “{” and “}” )

  • Good practice is to include the curly braces even for single-liners.

if (x == 0)

cout << "0";

else

cout << "not 0";

cout << "Done";

if (x == 0)

cout << "0";

cout << "Done";

if (x == 0){

cout << "x is ";

cout << "0";

}

else{

cout << "x is ";

cout << "not 0";

}

cout << "Done";

Brace-enclosed Block

39 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • If / then / else

Block: a group of zero or more statements that are grouped together by delimiters�( in C++ braces “{” and “}” )

  • Good practice is to include the curly braces even for single-liners.

Brace-enclosed Block

if (x = 0)

cout << "1";

cout << "Done";

Note (common error!) :

if (x == 0)

cout << "0";

cout << "Done";

if (x == 0)

cout << "0";

else

cout << "not 0";

cout << "Done";

if (x == 0){

cout << "x is ";

cout << "0";

}

else{

cout << "x is ";

cout << "not 0";

}

cout << "Done";

40 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • Switch

  • The switching value must evaluate to

an integer or enumerated type

  • The case values must be either:

a) a constant or literal, or

b) an enum value

  • The case values must be of the same type

as the switch expression

Notes:

break statements are typically used to terminate each case.

• It is usually a good practice to include a default case.

switch(cardValue) {

case 11:

cout << "Jack";

break;

case 12:

cout << "Queen";

break;

case 13:

cout << "King";

break;

default:

cout << cardValue;

break;

}

41 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • Switch

  • The switching value must evaluate to

an integer or enumerated type

  • The case values must be either:

a) a constant or literal, or

b) an enum value

  • The case values must be of the same type

as the switch expression

switch(cardValue) {

case 11:

cout << "Jack";

case 12:

cout << "Queen";

case 13:

cout << "King";

default:

cout << cardValue;

}

Notes:

break statements are typically used to terminate each case.

• Without a break statement, cases “fall through” to the next statement.

Why?:

In reality switch is like a special kind of goto

42 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • Switch

  • The switching value must evaluate to

an integer or enumerated type

  • The case values must be either:

a) a constant or literal, or

b) an enum value

  • The case values must be of the same type

as the switch expression

switch(cardValue) {

case 11:

{ cout << "Jack";

int some_var = 1;

} break;

case 12:

{ cout << "Queen";

int some_var = 2;

} break;

case 13:

{ cout << "King";

int some_var = 3;

} break;

default:

{ cout << cardValue;

int some_var = 0;

} break;

}

Notes:

In reality switch is like a special kind of goto

Means you should also brace-enclose each case Scope !

Note:

Separate scopes under every case !

Otherwise, it looks like some_var is getting re-defined under the same scope 4 times…

43 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • While

Executes a block of statements while a particular condition/expression is true

  • Do While

Performs at least one block execution

int count = 0;

while(count < 10) {

cout << count;

count++;

}

int count = 0;

do {

cout << count;

count++;

} while(count < 10)

44 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • For

Iterate over a range of values.

  • The initialization expression initializes the loop it is executed once, as the loop begins.
  • Loop ends when the termination expression evaluates to false.
  • The increment expression is invoked after each iteration.

for ( init; term; incr ) {

}

for (int count = 0; count < 10; count++) {

cout << count;

}

for (int count = 25; count < 50; count += 5){ //increment by 5

cout << count;

}

45 of 103

Statements

CS-202 C. Papachristos

Flow Control Statements

  • For

Iterate over a range of values.

  • The initialization expression initializes the loop it is executed once, as the loop begins.
  • Loop ends when the termination expression evaluates to false.
  • The increment expression is invoked after each iteration.

for ( init; term; incr ) {

}

for ( ; ; ) {

cout << "Running" << endl;

}

for (int count = 0 ; ; ++count){

cout << count << endl;

}

//continuously running, no increment

//continuously running, increment by 1

46 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Namespaces

A collection of name definitions under a top-level identifier.

Most common is namespace std

  • Contains all standard library definitions !

The using keyword: Instruct the compiler to attempt to resolve names therein

Examples:� #include <iostream>� using namespace std;

#include <iostream>

using std::cin; � using std::cout;

or

What is the difference ?

47 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Namespaces

A collection of name definitions under a top-level identifier.

Most common is namespace std

  • Contains all standard library definitions !

The using keyword: Instruct the compiler to attempt to resolve names therein

Examples:� #include <iostream>� using namespace std;

#include <iostream>

using std::cin; � using std::cout;

Includes entire standard library of name definitions:

cout , cin , cerr , endl

or

48 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Namespaces

A collection of name definitions under a top-level identifier.

Most common is namespace std

  • Contains all standard library definitions !

The using keyword: Instruct the compiler to attempt to resolve names therein

Examples:� #include <iostream>� using namespace std;

#include <iostream>

using std::cin; � using std::cout;

Includes entire standard library of name definitions:

cout , cin , cerr , endl

Specify just the (object) names we want to import for scope resolution …

or

49 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Resolution Operator ( :: )

Explicit resolution under a namespace

Objects: std::cout

Functions: std::count( its, itl, val )

In case of name conflicts, it might supersede any using keyword usage:

#include <iostream>� using namespace std;

namespace ns{

int cout = 1;

}

cout << ns::cout;

Namespace declaration

50 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Resolution Operator ( :: )

Explicit resolution under a namespace

Objects: std::cout

Functions: std::count( its, itl, val )

In case of name conflicts, it might supersede any using keyword usage:

#include <iostream>� using namespace std;

namespace ns{

int cout = 1;

}

cout << ns::cout;

  • cout evaluates to std::cout
  • ns::cout evaluates to the variable in ns

Namespace declaration

51 of 103

#include <algorithm>

using namespace std;

int count = 0;

int increment() {

return ++count;

}

Namespaces - Resolution

CS-202 C. Papachristos

Scope Resolution (Ambiguities)

Revisiting the (BAD!) practice of using namespace std;

Functions: std::count( its, itl, val)

Long error code…

error: reference to 'count' is ambiguous: note: candidates are: int count In file included from /usr/include/c++/4.9/algorithm:62:0, from 2: /usr/include/c++/4.9/bits/stl_algo.h:3947:5: note: template<class _IIter, class _Tp> typename std::iterator_traits<_Iterator>::difference_type std::count(_IIter, _IIter, const _Tp&) count(_InputIterator __first, _InputIterator __last, const _Tp& __value)

#include <algorithm>

using namespace std;

int increment() {

int count = 0;

return ++count;

}

52 of 103

Namespaces - Resolution

CS-202 C. Papachristos

Scope Resolution (Ambiguities)

Revisiting the (BAD!) practice of using namespace std;

Functions: std::count( its, itl, val)

#include <algorithm>

int increment() {

using namespace std;

int count = 0;

return ++count;

}

#include <algorithm>

int count = 0;

int increment(){

using namespace std;

return ++count;

}

Ambiguous

Why?

53 of 103

#include <algorithm>

int increment() {

using namespace std;

int count = 0;

return ++count;

}

#include <algorithm>

int count = 0;

int increment(){

using namespace std;

return ++count;

}

Namespaces - Resolution

CS-202 C. Papachristos

Scope Resolution (Ambiguities)

The (BAD!) practice of using namespace std;

Functions: std::count( its, itl, val)

Ambiguous

Rule looks at Global Scope

  • Behaves “as-if” it’s placed together with #include statements, even though it’s trying to import names into the Local Scope only.

54 of 103

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

Input / Output

CS-202 C. Papachristos

Console

Input / Output

55 of 103

Input / Output

CS-202 C. Papachristos

Console Input / Output

  • Console Input, Output, and Error stream objects in C++ are called:

cin, cout, cerr

  • They are Global Objects of the classes�ostream (outputstream) and istream (inputstream)
  • Defined in the C++ library header called <iostream>(we’ll leave it at that for now)

Useful for:

  • User input
  • User output
  • Error messages (exclusive stream, redirection if required)

56 of 103

#include <iostream>

using namespace std;

int main()

{

int numberOfCodeLines;

cout << "Hello new programming enthusiast! "

<< "Welcome to C++.\n";

cout << "How many lines of C code have you written in your life?" << endl;

cin >> numberOfCodeLines;

if (numberOfCodeLines < 10000) {

cout << "You might find C++ to have a very steep learning curve." << endl;

}

else {

cout << "Your background might very well save the day!" << endl;

}

return 0;

}

Input / Output

CS-202 C. Papachristos

Preprocessor directives

Note:

using namespace std;

Without it:

std::cout

std::cin

std::cerr

57 of 103

Input / Output

CS-202 C. Papachristos

Console Input / Output

  • Console Input, Output, and Error stream objects in C++ are called:

cin, cout, cerr

  • They are Global Objects of the classes�ostream (outputstream) and istream (inputstream)
  • Defined in the C++ library called <iostream>

Note:

std::cout and std::cin are Global Objects of the classes std::ostream and std::istream

  • #include <iostream> is responsible for including their corresponding declarations in your programs.

Side-Note:

Guaranteed at least past C++11

58 of 103

Input / Output

CS-202 C. Papachristos

Console Output ( std::cout )

Any primitive C++ data type can be output:

  • Variables
  • Constants
  • Literals
  • Expressions (which can include all of above)

cout << numberOfGames << " games played.";�2 values are output:� Value of variable numberOfGames� Literal string " games played."

  • Cascading: multiple values with one cout-initiated expression.

Note:

Insertion Operators

59 of 103

Input / Output

CS-202 C. Papachristos

Output

New lines in output

  • Escape sequences are valid: "\n" is “newline”

A second method:

  • Object std::endl
  • Flushes output buffer ( std::flush )

Examples:

cout << "Hello World\n";

cout << "Hello World" << endl;

  • Makes sense to force output of heavy, crash-prone processes.
  • Creates overhead.
  • Same in line-buffered context.

Table from:

Absolute C++

Copyright © 2016

Pearson, Inc.

All rights reserved.

60 of 103

Input / Output

CS-202 C. Papachristos

Output Format

Numeric values may not display as you’d expect:cout << "The price is $" << price << endl;

If double price = 78.5; then will we get ?

The price is $78.500000

The price is $78.5

OR

61 of 103

Input / Output

CS-202 C. Papachristos

Output Format

Numeric values may not display as you’d expect:cout << "The price is $" << price << endl;

If double price = 78.5; then will we get ?

  • Force Decimals-related formatting before calling cout << … :

cout.setf(ios::fixed);� cout.setf(ios::showpoint);� cout.precision(3);

Fixed Precision

Show Decimal Point

Set Precision Decimals

Note:

std::cout and std::cin are Global Objects of the classes std::ostream and std::istream

With their corresponding class methods setf() and precision()

e.g. cout.setf(…); and / or cin.setf(…); you can change their “attributes”.

cout.precision(…); cin.precision(…);

The price is $78.500

62 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Prompt user for input� cout << "Enter number of objects: ";� cin >> numOfObjects;

User-friendly input/output design:

  • Every cin should have a corresponding prior cout prompt.

Note:

no "\n" or std::endl in cout here. Prompt will “wait” for user input on the same line !

63 of 103

Input / Output

CS-202 C. Papachristos

Console Input ( std::cin )

No literals allowed for cin

  • Must input to a variable

Waits on-screen for keyboard entry

  • cin >> num;

Value entered at keyboard is ‘assigned’ to num.

cin >> firstName >> lastName >> age;

  • Consumes any leading whitespaces, and stops reading at next whitespace.

  • Can also be cascaded, >> operators separate each “type” of thing we read in.

Note:

Extraction Operators

64 of 103

Input / Output

CS-202 C. Papachristos

Console Input ( std::cin )

No literals allowed for cin

  • Must input to a variable

Waits on-screen for keyboard entry

  • cin >> num;

Value entered at keyboard is ‘assigned’ to num.

cin >> firstName >> lastName >> age;

  • Consumes any leading whitespaces, and stops reading at next whitespace.

Example type-in: [ws][ws] 420 [ws] 911 [↵] num : 420

  • Can also be cascaded, >> operators separate each “type” of thing we read in.

65 of 103

Input / Output

CS-202 C. Papachristos

Console Input ( std::cin )

No literals allowed for cin

  • Must input to a variable

Waits on-screen for keyboard entry

  • cin >> num;

Value entered at keyboard is ‘assigned’ to num.

cin >> firstName >> lastName >> age;

  • Consumes any leading whitespaces, and stops reading at next whitespace.

Example type-in: [ws][ws] 420 [ws] 911 [↵] num : 420

  • Can also be cascaded, >> operators separate each “type” of thing we read in.

Example type-in: christos [ws] papachristos [ws] 34 [↵]

66 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Whitespace Skipping,�an Example:

Note:

std::noskipws

std::skipws

cin << noskipws << … ;

cin.setf( noskipws );

cin << … ;

or

#include <iostream>

int main () {

char a, b, c;

// set whitespace skip flag, read in " 0 1 2"

std::cin >> std::skipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

// flushes cin

std::cin.ignore(INT_MAX);

// unset whitespace skip flag, read in " 0 1 2"

std::cin >> std::noskipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

return 0;

}

cin << skipws << … ;

cin.setf( skipws );

cin << … ;

or

Note: Default is to skipws.

67 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Whitespace Skipping,�an Example:

Note:

std::noskipws

std::skipws

cin << noskipws << … ;

cin.setf( noskipws );

cin << … ;

or

#include <iostream>

int main () {

char a, b, c;

// set whitespace skip flag, read in " 0 1 2"

std::cin >> std::skipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

// flushes cin

std::cin.ignore(INT_MAX);

// unset whitespace skip flag, read in " 0 1 2"

std::cin >> std::noskipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

return 0;

}

Input: [ws][ws] 0 [ws][ws][ws] 1 [ws] 2

Output: 0,1,2

cin << skipws << … ;

cin.setf( skipws );

cin << … ;

or

Note: Default is to skipws.

68 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Whitespace Skipping,�another Example:

Note:

std::noskipws

std::skipws

cin << noskipws << … ;

cin.setf( noskipws );

cin << … ;

or

#include <iostream>

int main () {

char a, b, c;

// set whitespace skip flag, read in " 0 1 2"

std::cin >> std::skipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

// flushes cin

std::cin.ignore(INT_MAX);

// unset whitespace skip flag, read in " 0 1 2"

std::cin >> std::noskipws >> a >> b >> c;

std::cout << a << "," << b << "," << c << std::endl;

return 0;

}

Input: [ws][ws] 0 [ws][ws][ws] 1 [ws] 2

Output: [ws],[ws],0

cin << skipws << … ;

cin.setf( skipws );

cin << … ;

or

Note: Default is to skipws.

69 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Prompt user for input�

#include <iostream>

using namespace std;

int main()

{

char name[256];

int age;

cout << "What is your age?\n";

cin >> age;

cout << "What is your name?\n";

cin >> name;

cout << "Hello " << name << ", at " << age

<< " your age is perfect to learn C++! << endl;

return 0;

}

70 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

Whitespace Behavior:

Note:

Will stop at whitespace.

cin >> name;

cout << name;

John

We could have done instead:

cin >> firstName

>> lastName;

or

Sample Dialog 1:

What is your age?

34

What is your name?

Christos

Hello Christos, at 34 your age is perfect to learn C++!

Sample Dialog 2:

What is your age?

16

What is your name?

John Doe

Hello John, at 16 your age is perfect to learn C++!

Reading in to Cstring variable name

stops at whitespace character!

71 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

What if we want something�more generic?

Read-in the entire line !

Note:

getline ( char* s,

streamsize n,

char delim );

#include <iostream>

const int STR_SIZE = 256;

int main () {

char in_str[STR_SIZE];

// without whitespace skip flag read in " 10 1 23"

// by getting the entire line

std::cin.getline(in_str, STR_SIZE);

std::cout << in_str << std::endl;

std::cout << atoi(in_str) << std::endl;

std::cout << atoi(&in_str[2]) << ","

<< atoi(&in_str[7]) << ","

<< atoi(&in_str[9]) << std::endl;

return 0;

}

Input: [ws][ws] 10 [ws][ws][ws] 1 [ws] 23

Output: [ws][ws] 10 [ws][ws][ws] 1 [ws] 23

Takes a C-string (char array)�to store result,�the size of the C-string array,�and a delimiting char

(default is '\n')

72 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

What if we want something�more generic?

Read-in the entire line !

#include <iostream>

const int STR_SIZE = 256;

int main () {

char in_str[STR_SIZE];

// without whitespace skip flag read in " 10 1 23"

// by getting the entire line

std::cin.getline(in_str, STR_SIZE);

std::cout << in_str << std::endl;

std::cout << atoi(in_str) << std::endl;

std::cout << atoi(&in_str[2]) << ","

<< atoi(&in_str[7]) << ","

<< atoi(&in_str[9]) << std::endl;

return 0;

}

Input: [ws][ws] 10 [ws][ws][ws] 1 [ws] 23

Output: 10

Needs�Parsing

Note:

getline ( char* s,

streamsize n,

char delim );

Takes a C-string (char array)�to store result,�the size of the C-string array,�and a delimiting char

(default is '\n')

73 of 103

Input / Output

CS-202 C. Papachristos

User Input /Output

What if we want something�more generic?

Read-in the entire line !

#include <iostream>

const int STR_SIZE = 256;

int main () {

char in_str[STR_SIZE];

// without whitespace skip flag read in " 10 1 23"

// by getting the entire line

std::cin.getline(in_str, STR_SIZE);

std::cout << in_str << std::endl;

std::cout << atoi(in_str) << std::endl;

std::cout << atoi(&in_str[2]) << ","

<< atoi(&in_str[7]) << ","

<< atoi(&in_str[9]) << std::endl;

return 0;

}

Input: [ws][ws] 10 [ws][ws][ws] 1 [ws] 23

Output: 10,1,23

But HOW ?

Note:

getline ( char* s,

streamsize n,

char delim );

Takes a C-string (char array)�to store result,�the size of the C-string array,�and a delimiting char

(default is '\n')

74 of 103

Input / Output

CS-202 C. Papachristos

Error Output ( std::cerr )

cerr works same as cout

  • Mechanism for distinguishing between regular output and error output
  • Most systems allow cout and cerr to be “redirected” to other devices

e.g., line printer, output file, error console, etc.

75 of 103

Input / Output

CS-202 C. Papachristos

File Input / Output

Similarly to cin, a combination of:

  • cin >> var;

At the top:

#include <fstream>� using namespace std;

An input stream object (creation just as with any other variable):

ifstream inputStream;

“Connect” the inputStream variable to a text file (via pathname):

inputStream.open("filename.txt");

Input Object (C++)

Extraction Operator

Variables

76 of 103

Input / Output

CS-202 C. Papachristos

File Input / Output

Read-in by using the Extraction Operator ( >> ):

inputStream >> var;

The result is the same as using cin >> var except the input is coming from the text file and not the keyboard.

Check that EOF hasn’t been reached:

if ( !inputStream.eof() )

Close with :

inputStream.close();

77 of 103

Input / Output

CS-202 C. Papachristos

File Input / Output

Output (similarly):

An output stream object (creation just as with any other variable):

ofstream outputStream;

Open file to write:

outputStream.open("filename.txt", ofstream::out);

outputStream.open("filename.txt");

Write-out by using the Insertion Operator ( << ):

outputStream << var;

Close with :

outputStream.close();

or

78 of 103

Input / Output

CS-202 C. Papachristos

File Input / Output

database.txt

#include <iostream>

#include <fstream>

using namespace std;

int main() {

char name[256];

int age;

char inputFilename[] = "database.txt";

ifstream inputStream;

inputStream.open(inputFilename);

inputStream >> name >> age;

inputStream.close(inputFilename);

char outputFilename[] = "new_database.txt";

ofstream outputStream;

outputStream.open(outputFilename);

outputStream << "Name: " << name << ", Age: " << ++age;

outputStream.close(outputFilename);

return 0;

}

Christos 34

new_database.txt

Name: Christos, Age: 35

Sample Input File:

Sample Output File:

79 of 103

Arrays

CS-202 C. Papachristos

A collection of related data items.

  • Can be of any data type.
  • They are static

Their size does not change.

They are declared contiguously in memory.

In other words, an array’s data is stored in �one big block, together.

int arr[5];

arr as a name�is equivalent to the�starting address of

its first element�arr[0]

arr[1]

arr[2]

arr[3]

arr[4]

arr[0]

Address 0x1024

Address 0x1025

Address 0x1026

Address 0x1027

Address 0x1028

Address 0x1029

Address 0x1030

Address 0x1031

Address 0x1032

Address 0x1033

Address 0x1034

Address 0x1035

Address 0x1036

Address 0x1037

Address 0x1038

Address 0x1039

Address 0x1040

Address 0x1041

Address 0x1042

Address 0x1043

Address 0x…

Address 0x1022

Address 0x1023

Address 0x1044

Address 0x1045

Address 0x…

80 of 103

Arrays

CS-202 C. Papachristos

Recall simple variables:

  • Allocated memory in an "address"

Array declarations allocate memory

for entire array

  • Sequential allocation

Addresses allocated "back-to-back“.

Allows indexing calculations.

Simple "addition" from array beginning (index 0).

arr as a name�is equivalent to the�starting address of

its first element�arr[0]

arr[1]

arr[2]

arr[3]

arr[4]

arr[0]

Address 0x1024

Address 0x1025

Address 0x1026

Address 0x1027

Address 0x1028

Address 0x1029

Address 0x1030

Address 0x1031

Address 0x1032

Address 0x1033

Address 0x1034

Address 0x1035

Address 0x1036

Address 0x1037

Address 0x1038

Address 0x1039

Address 0x1040

Address 0x1041

Address 0x1042

Address 0x1043

Address 0x…

Address 0x1022

Address 0x1023

Address 0x1044

Address 0x1045

Address 0x…

81 of 103

Arrays

CS-202 C. Papachristos

Array Declaration

<type> <name> [size];

float xArray [10];

This array now has memory to hold size=10 floats.

0-based indexing (0 is our natural “first” number):

xArray[9]; At size-1 lies the final element of the array.

C++ pitfall:

The compiler will “let you go” beyond size-1.

Compiler will not detect this as an error.

xArray[10] = 1.0F;

Unpredictable results! Up to programmer to “stay in range”.

82 of 103

Arrays

CS-202 C. Papachristos

Array Limitations

  • Does not know how large it is – there is no C++ size() function for arrays�(sort of).
  • No bounds checking is performed.

Arrays are static

  • Size must be known at compile time (cannot change once set).

Normally can’t do user input for array size: “How many numbers would you� like to store?”

C / C++ Benefits:

  • Efficiency.
  • Backwards Compatibility.

83 of 103

Arrays

CS-202 C. Papachristos

Array Declaration / Initialization

  • A declaration alone generally will not initialize the data stored in the memory locations.
  • They might contain “garbage” leftover data.

Declaration:

int numbers[5];

?

?

?

?

?

84 of 103

Arrays

CS-202 C. Papachristos

Array Declaration / Initialization

  • Initialization ensures specific values for the contained data.

Declaration - initialization:

int numbers[5] = { 5, 2, 6, 9, 3 };

5

2

6

9

3

85 of 103

Arrays

CS-202 C. Papachristos

Array Declaration / Initialization

  • Initialization ensures specific values for the contained data.

Declaration - initialization:

int numbers[5] = { 5, 2, 6 };

Partial initialization (fewer values than the given size) :

  • Fills values starting at the beginning.
  • Remainder are implicitly initialized with that data type’s “zero” (for built-in types).

5

2

6

0

0

86 of 103

Arrays

CS-202 C. Papachristos

Array Declaration / Initialization

If no array size is given array is created only as big as is needed: �

int yArray[] = { 5, 12, 11 };

Allocates array yArray to hold 3 integers

87 of 103

Arrays

CS-202 C. Papachristos

C-strings (as char Arrays)

  • They are char type arrays.

  • Initialization (normal way):

char name[5] = {'J', 'o', 'h', 'n', 0 };

  • Initialization (string constant literal):

char name[5] = "John" ;

Note: Different quotes have different purposes !!!

  • Double quotes are for strings
  • Single quotes are for chars (characters)

NULL-char delimited !

88 of 103

Arrays

CS-202 C. Papachristos

Array Element Access

Bracket Operator ( [•] ):

  • Access of a single element (when used on existing instance).

int numbers[5] = { 5, 2, 6, 9, 3 };

cout << " The third element is" << numbers[2] << endl;

Output:

The third element is 6

5

2

6

9

3

0

1

2

3

4

89 of 103

Arrays

CS-202 C. Papachristos

Array Element Access

  • C++ also accepts any expression as a “size”

(must evaluate to an integral value, based on values also known at compile-time).

const int start = 0, end = 4;

double dNumbers[(start + end) / 2];

Array Size using Constants

  • Use defined/named constants for your size.

#define NUMBER_OF_STUDENTS 5

const int NUMBER_OF_STUDENTS = 5;

int score[NUMBER_OF_STUDENTS];

or

Readability, Versatility, Maintainability

90 of 103

Arrays

CS-202 C. Papachristos

Array Element Access

  • And a non-Standard extension by GCC

const int start, end;

double dNumbers[(start + end) / 2];

By the GNU Compiler Collection – Online Docs

( http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html )

  • Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.

Note: Make sure you initialize these,�otherwise you might never notice�a problem until it’s too late!

int start = 0, end = 100;

cin >> start >> end;

double dNumbers[(start + end) / 2];

dNumbers[0] = -1.0;

cout << (start+end)/2 << "," << � dNumbers[0] << "," << dNumbers[100];

91 of 103

Arrays

CS-202 C. Papachristos

Arrays (passing them as Function Parameters)

  • Indexed variables (individual element of an array is passed):

Function declaration:

void myFunction(double param1);

Variables:

double n, a[10];

Function calls:

myFunction( a[3] );

myFunction( n );

Just a double in both cases

What if we want to pass an entire double array ?

92 of 103

Arrays

CS-202 C. Papachristos

Arrays (passing them as Function Parameters)

  • Entire arrays (passed by the array’s name)

Approach 1: A Function that takes an “Array of (some type) T”

Known bounds – has to agree with passed array SIZE.

Declaration: void fillUp(int (&arr)[ ARRAY_SIZE]);

Definition: void fillUp(int (&arr)[ ARRAY_SIZE ]) {

cout<<"Enter "<< ARRAY_SIZE <<" numbers:\n";

for (int i=0; i < ARRAY_SIZE; ++i ) {

cin >> arr[i]

}

cout<<"The last array index is "<< (ARRAY_SIZE - 1) <<endl;

}

93 of 103

Arrays

CS-202 C. Papachristos

Arrays (passing them as Function Parameters)

  • Entire arrays (passed by the array’s name)

Approach 1: A Function that takes an “Array of (some type) T”

Known bounds – has to agree with passed array ARRAY_SIZE.

Example code inside a program main():

const int ARRAY_SIZE = 5;

void fillUp( int (&arr)[ ARRAY_SIZE ]);

int score[ ARRAY_SIZE ];

fillUp(score);

No brackets when passing!

Brackets & SIZE in function definition.

Brackets in variable declaration.

94 of 103

Arrays

CS-202 C. Papachristos

Arrays (passing them as Function Parameters)

  • Entire arrays (passed by the array’s name)

Approach 2: A Function that takes an “Array of unknown bound of (some type T”

Should probably specify some size for the array as well.

Declaration: void fillUp(int arr[ ], int size);

Definition: void fillUp(int arr[ ], int size) {

cout<<"Enter "<< size <<" numbers:\n";

for (int i=0; i < size; ++i ) {

cin >> arr[i]

}

cout<<"The last array index is "<< (size - 1) <<endl;

}

Pass as 2nd parameter

of int-type.

95 of 103

Arrays

CS-202 C. Papachristos

Arrays (passing them as Function Parameters)

  • Entire arrays (passed by the array’s name)

Approach 2: A Function that takes an “Array of unknown bound of (some type T)”

Should probably specify some size for the array as well.

Example code inside a program main():

void fillUp( int arr[], int size);

int score[5], numberOfScores = 5;

fillUp(score, numberOfScores);

  • How does this work? What’s really passed?

The Address-Of first indexed variable ( arrName[0] ).

No brackets when passing!

Brackets in function definition.

Brackets in variable declaration.

96 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Arrays with more than one index

char array2d [DIM2][DIM1];

char page [30][100];

  • Two indices (it is an “array of arrays”)

page[0][0], page[0][1], ..., page[0][99]� page[1][0], page[1][1], ..., page[1][99]� ...� page[29][0], page[29][1], ..., page[29][99]

  • C++ allows any number of indexes

Typically no more than two or three

97 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Arrays with more than one index

char array2d [DIM2][DIM1];

char page [30][100];

  • Two indices (it is an “array of arrays”)

page[0][0], page[0][1], ..., page[0][99]� page[1][0], page[1][1], ..., page[1][99]� ...� page[29][0], page[29][1], ..., page[29][99]

  • C++ allows any number of indexes

Typically no more than two or three

COLS

98 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Arrays with more than one index

char array2d [DIM2][DIM1];

char page [30][100];

  • Two indices (it is an “array of arrays”)

page[0][0], page[0][1], ..., page[0][99]� page[1][0], page[1][1], ..., page[1][99]� ...� page[29][0], page[29][1], ..., page[29][99]

  • C++ allows any number of indexes

Typically no more than two or three

COLS

ROWS

99 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Arrays with more than one index

char array2d [DIM2][DIM1];

char page [30][100];

  • Two indices (it is an “array of arrays”)

page[0][0], page[0][1], ..., page[0][99]� page[1][0], page[1][1], ..., page[1][99]� ...� page[29][0], page[29][1], ..., page[29][99]

  • C++ allows any number of indexes

Typically no more than two or three

COLS

ROWS

Array of Arrays

100 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Indexing with Bracket Operator ( [•] )

char a = array2d [j][i];

  • Multi-Dimensional Arrays as Parameters (Similar to one-dimensional array)

1st dimension size not given (#ROWS), provided as second parameter of function

2nd dimension size is given (#COLS)

void displayPage(char page[][100], int numRows) {� for ( int i = 0; i < numRows; i++ ) {� for ( int j = 0; j < 100; j++ ) {� cout << page[i][j];

}� cout << endl;� }� }

Note:

Otherwise, error: declaration of 'page' as multidimensional array must have bounds for all dimensions except the first.

101 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Indexing with Bracket Operator ( [•] )

char a = array2d [j][i];

  • Multi-Dimensional Arrays as Parameters (Similar to one-dimensional array)

1st dimension size not given (#ROWS), provided as second parameter of function

2nd dimension size is given (#COLS)

void displayPage(char page[][100], int numRows) {� for ( int i = 0; i < numRows; i++ ) {� for ( int j = 0; j < 100; j++ ) {� cout << page[i][j];

}� cout << endl;� }� }

Note:

In fact the declared parameter type is interpreted as char (*)[100] !

102 of 103

Arrays

CS-202 C. Papachristos

Multi-Dimensional Arrays

  • Indexing with Bracket Operator ( [•] )

char a = array2d [j][i];

  • Multi-Dimensional Arrays as Parameters (Similar to one-dimensional array)

1st dimension size not given (#ROWS), provided as second parameter of function

2nd dimension size is given (#COLS)

void displayPage(char page[][100], int numRows) {� for ( int i = 0; i < numRows; i++ ) {� for ( int j = 0; j < 100; j++ ) {� cout << page[i][j];

}� cout << endl;� }� }

Note:

In fact the declared parameter type is interpreted as char (*)[100] !

103 of 103

Time for Questions !

CS-202

CS-202 C. Papachristos