C++ Primer (continued)
C. Papachristos
Robotic Workers Lab
University of Nevada, Reno
CS-202
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.
Monday | Tuesday | Wednesday | Thursday | Friday |
|
|
| Lab (8 Sections) |
|
| CLASS |
| CLASS |
|
PASS Session�(Tentative) | PASS Session�(Tentative) | Project DEADLINE | NEW Project |
|
Today’s Topics
CS-202 C. Papachristos
Operators & Expressions
Scope & Resolution
Statements & Flow Control
Namespaces & Resolution
C++ Input / Output
Arrays
Operators & Expressions
CS-202 C. Papachristos
Operators (General)
A variety of operators in programming languages:
(depends on number of operands, i.e. things they operate on)
Represented by special symbolic characters
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 | Prefix increment and decrement | Right-to-left |
+a -a | Unary plus and minus | ||
! ~ | |||
(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 | << >> | Bitwise left shift and right shift | |
8 | <=> | Three-way comparison operator (since C++20) | |
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 |
Operators & Expressions
CS-202 C. Papachristos
Standard Arithmetic Operators
Left-to-Right Associativity, Standard rules of arithmetic Precedence
Operators & Expressions
CS-202 C. Papachristos
Standard Relational Operators
Testing for:
Operators & Expressions
CS-202 C. Papachristos
Standard Logical Operators
Evaluating:
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 | |
Operators & Expressions
CS-202 C. Papachristos
Standard Bitwise Operators
Useful to conduct Bitwise operations:
(Boolean , bit-by-bit operations on Registers)
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 |
Operators & Expressions
CS-202 C. Papachristos
Unary Operators
( ! true ) is false
( ! false ) is true
( x ++ ) evaluates to ( x ) , and x shall be increased by 1
( x -- ) evaluates to ( x ) , and x shall be decreased by 1
( ++ x ) evaluates to ( x + 1 ) , and x shall be increased by 1
( -- x ) evaluates to ( x – 1 ) , and x shall be decreased by 1
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).
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
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).
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 ;
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).
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 ;
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).
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 ;
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).
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 ;
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).
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)
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).
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
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).
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
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).
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
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).
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
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)
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;
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
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
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”.
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”.
Both operands are ints, hence integer division is performed.
Highest-order operand is double (17.0), hence double precision division is performed.
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”.
Both operands are ints : Integer division.
Highest-order operand is double : Double division.
double doubleVar = intVar1 / intVar2;
doubleVar is 0.0 !
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) equals 0
(0 / 3.0) equals 0.0
(0.0 / 4) equals 0.0 !
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
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 );
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)
Operators & Expressions
CS-202 C. Papachristos
Type Conversion
Done by the compiler:
17 / 5.5;� “Implicit type cast” 17 → 17.0
Programmer-enforced:
(double)17 / 5.5;
double(17) / 5.5;� static_cast<double>( 17 ) / 5.5;�
Operators & Expressions
CS-202 C. Papachristos
Shorthand Operators
Also shorthands:
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);
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?
Where a variable can be referenced from in your program
if(age >= 18) {
bool adult = true;
cout << adult;
}
cout << adult;
bool adult = false;
if(age >= 18) {
bool adult = true;
cout << adult;
}
cout << adult;
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?
Where a variable can be referenced from in your program
if(age >= 18) {
bool adult = true;
cout << adult;
}
cout << adult;
bool adult = false;
if(age >= 18) {
bool adult = true;
cout << adult;
}
cout << adult;
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?
Where a variable can be referenced from in your program
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)
Statements
CS-202 C. Papachristos
A complete unit of execution (equivalent to a sentence in a language).
Assignment expressions
Use of ( ++ ) or ( -- )
Method invocations
Object creation
Selection structures
Repetition/Iteration structures
End with semicolon ( ; )
Follow Scope rules
Statements
CS-202 C. Papachristos
Flow Control Statements
Block: a group of zero or more statements that are grouped together by delimiters
( in C++ braces “{” and “}” )
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
Statements
CS-202 C. Papachristos
Flow Control Statements
Block: a group of zero or more statements that are grouped together by delimiters�( in C++ braces “{” and “}” )
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";
Statements
CS-202 C. Papachristos
Flow Control Statements
an integer or enumerated type
a) a constant or literal, or
b) an enum value
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;
}
Statements
CS-202 C. Papachristos
Flow Control Statements
an integer or enumerated type
a) a constant or literal, or
b) an enum value
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 …
Statements
CS-202 C. Papachristos
Flow Control Statements
an integer or enumerated type
a) a constant or literal, or
b) an enum value
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…
Statements
CS-202 C. Papachristos
Flow Control Statements
Executes a block of statements while a particular condition/expression is true
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)
Statements
CS-202 C. Papachristos
Flow Control Statements
Iterate over a range of values.
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;
}
Statements
CS-202 C. Papachristos
Flow Control Statements
Iterate over a range of values.
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
Namespaces - Resolution
CS-202 C. Papachristos
Namespaces
A collection of name definitions under a top-level identifier.
Most common is namespace std
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 ?
Namespaces - Resolution
CS-202 C. Papachristos
Namespaces
A collection of name definitions under a top-level identifier.
Most common is namespace std
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
Namespaces - Resolution
CS-202 C. Papachristos
Namespaces
A collection of name definitions under a top-level identifier.
Most common is namespace std
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
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
…
…
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
…
…
#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;
}
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?
#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
#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
Input / Output
CS-202 C. Papachristos
Console Input / Output
cin, cout, cerr
Useful for:
#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
Input / Output
CS-202 C. Papachristos
Console Input / Output
cin, cout, cerr
Note:
std::cout and std::cin are Global Objects of the classes std::ostream and std::istream �
Side-Note:
Guaranteed at least past C++11
Input / Output
CS-202 C. Papachristos
Console Output ( std::cout )
Any primitive C++ data type can be output:
cout << numberOfGames << " games played.";�2 values are output:� Value of variable numberOfGames� Literal string " games played."
Note:
Insertion Operators
Input / Output
CS-202 C. Papachristos
Output
New lines in output
A second method:
Examples:
cout << "Hello World\n";
cout << "Hello World" << endl;
Table from:
Absolute C++
Copyright © 2016
Pearson, Inc.
All rights reserved.
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
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 ?
� 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
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:
Note:
no "\n" or std::endl in cout here. Prompt will “wait” for user input on the same line !
Input / Output
CS-202 C. Papachristos
Console Input ( std::cin )
No literals allowed for cin
Waits on-screen for keyboard entry
Value entered at keyboard is ‘assigned’ to num.
cin >> firstName >> lastName >> age;
Note:
Extraction Operators
Input / Output
CS-202 C. Papachristos
Console Input ( std::cin )
No literals allowed for cin
Waits on-screen for keyboard entry
Value entered at keyboard is ‘assigned’ to num.
cin >> firstName >> lastName >> age;
Example type-in: [ws][ws] 420 [ws] 911 [↵] num : 420
Input / Output
CS-202 C. Papachristos
Console Input ( std::cin )
No literals allowed for cin
Waits on-screen for keyboard entry
Value entered at keyboard is ‘assigned’ to num.
cin >> firstName >> lastName >> age;
Example type-in: [ws][ws] 420 [ws] 911 [↵] num : 420
Example type-in: christos [ws] papachristos [ws] 34 [↵]
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.
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.
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.
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;
}
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!
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')
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')
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')
Input / Output
CS-202 C. Papachristos
Error Output ( std::cerr )
cerr works same as cout
e.g., line printer, output file, error console, etc.
Input / Output
CS-202 C. Papachristos
File Input / Output
Similarly to cin, a combination of:
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
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();
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
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:
Arrays
CS-202 C. Papachristos
A collection of related data items.
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…
Arrays
CS-202 C. Papachristos
Recall simple variables:
Array declarations allocate memory
for entire array
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…
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”.
Arrays
CS-202 C. Papachristos
Array Limitations
Arrays are static
Normally can’t do user input for array size: “How many numbers would you� like to store?”
C / C++ Benefits:
Arrays
CS-202 C. Papachristos
Array Declaration / Initialization
Declaration:
int numbers[5];
? | ? | ? | ? | ? |
Arrays
CS-202 C. Papachristos
Array Declaration / Initialization
Declaration - initialization:
int numbers[5] = { 5, 2, 6, 9, 3 };
5 | 2 | 6 | 9 | 3 |
Arrays
CS-202 C. Papachristos
Array Declaration / Initialization
Declaration - initialization:
int numbers[5] = { 5, 2, 6 };
Partial initialization (fewer values than the given size) :
5 | 2 | 6 | 0 | 0 |
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
Arrays
CS-202 C. Papachristos
C-strings (as char Arrays)
char name[5] = {'J', 'o', 'h', 'n', 0 };
char name[5] = "John" ;
Note: Different quotes have different purposes !!!
NULL-char delimited !
Arrays
CS-202 C. Papachristos
Array Element Access
Bracket Operator ( [•] ):
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
Arrays
CS-202 C. Papachristos
Array Element Access
(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
#define NUMBER_OF_STUDENTS 5
const int NUMBER_OF_STUDENTS = 5;
int score[NUMBER_OF_STUDENTS];
or
Readability, Versatility, Maintainability
Arrays
CS-202 C. Papachristos
Array Element Access
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 )
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];
Arrays
CS-202 C. Papachristos
Arrays (passing them as Function Parameters)
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 ?
Arrays
CS-202 C. Papachristos
Arrays (passing them as Function Parameters)
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;
}
Arrays
CS-202 C. Papachristos
Arrays (passing them as Function Parameters)
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.
Arrays
CS-202 C. Papachristos
Arrays (passing them as Function Parameters)
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.
Arrays
CS-202 C. Papachristos
Arrays (passing them as Function Parameters)
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);
The Address-Of first indexed variable ( arrName[0] ).
No brackets when passing!
Brackets in function definition.
Brackets in variable declaration.
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char array2d [DIM2][DIM1];
char page [30][100];
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]
Typically no more than two or three
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char array2d [DIM2][DIM1];
char page [30][100];
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]
Typically no more than two or three
COLS
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char array2d [DIM2][DIM1];
char page [30][100];
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]
Typically no more than two or three
COLS
ROWS
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char array2d [DIM2][DIM1];
char page [30][100];
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]
Typically no more than two or three
COLS
ROWS
Array of Arrays
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char a = array2d [j][i];
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.
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char a = array2d [j][i];
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] !
Arrays
CS-202 C. Papachristos
Multi-Dimensional Arrays
char a = array2d [j][i];
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] !
Time for Questions !
CS-202
CS-202 C. Papachristos