First Lesson C++
First Lesson C++
C++ Primer I
CMSC 202
Topics Covered
1-3
1/29/2014
1/29/2014
1-7
Variable Declaration
Syntax:
Examples:
int sum;
float average;
double grade = 98;
Semicolon required!
1/29/2014
Identifiers
Identifier naming rules apply to all variables,
methods, class names, enumerations, etc.:
Typically consist of letters, digits, and underscores
(_)
Must not start with a digit
Can be of any length
Are case-sensitive:
Rate, rate, and RATE are the names of three different
variables.
Naming Conventions
Naming conventions are additional rules that restrict
the names of variables to improve consistency
and readability
Most places of work and education have a set of naming
conventions
These are not language or compiler enforced
11
bankRate1
timeOfArrival
FirstProgram
MyClass
BankAccount
12
1/29/2014
m_dailyRate
13
Data Types:
Display 1.2 Simple Types (1 of 2)
1-14
Data Types:
Display 1.2 Simple Types (2 of 2)
1-15
1/29/2014
Assigning Data
Initializing data in declaration statement
Results "undefined" if you dont!
int myValue = 0;
1-16
intVar = 2.99;
// 2 is assigned to intVar!
Literals
2, 5.75, "Z", "Hello World"
Considered "constants": cant change in program
1-17
Display 1.3
Some Escape Sequences (1 of 2)
1-18
1/29/2014
Display 1.3
Some Escape Sequences (2 of 2)
1-19
Constants
You should not use literal constants directly in
your code
It might seem obvious to you, but not so:
limit = 52: is this weeks per year or cards in a deck?
1-20
Constants
There are two ways to do this:
Old way: preprocessor definition:
#define WEEKS_PER_YEAR 52
1-21
1/29/2014
Operators, Expressions
Recall: most programming languages have a
variety of operators: called unary, binary, and
even ternary, depending on the number of
operands (things they operate on)
Usually represented by special symbolic
characters: e.g., + for addition, * for
multiplication
There are also relational operators, and
Boolean operators
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
1-22
Operators, Expressions
Simple units of operands and operators
combine into larger units, according to strict
rules of precedence and associativity
Each computable unit (both simple and larger
aggregates) are called expressions
1-23
Binary Operators
Arithmetic Operators
Relational Operators
+ - * / %
<
>
==
<=
>=
Logical Operators
&&
||
24
1/29/2014
Relational Operators
x = 5;
y = 6;
For example:
25
Unary Operators
Unary operators only have one operand.
!
++
--
x = 5;
cout << "x's value is << x++;
x = 5;
cout << "x's value is << ++x;
26
Precedence, Associativity
Order of operator application to operands:
1/29/2014
Arithmetic Precision
Precision of Calculations
VERY important consideration!
Expressions in C++ might not evaluate as
youd "expect"!
1-28
1-29
1-30
10
1/29/2014
Type Casting
Two types
Implicitalso called "Automatic"
Done FOR you, automatically
17 / 5.5
This expression causes an "implicit type cast" to
take place, casting the 17 17.0
1-31
Type Casting
Casting for Variables
Can add ".0" to literals to force precision
arithmetic, but what about variables?
We cant use "myInt.0"!
static_cast<double>intVar
Explicitly "casts" or "converts" intVar to
double type
Result of conversion is then used
Example expression:
doubleVar = static_cast<double>intVar1 / intVar2;
Casting forces double-precision division to take place
among two integer variables!
1-32
Shorthand Operators
Increment & Decrement Operators
Just short-hand notation
Increment operator, ++
intVar++; is equivalent to
intVar = intVar + 1;
Decrement operator, -intVar--; is equivalent to
intVar = intVar 1;
1-33
11
1/29/2014
Pre-Increment
++intVar
Increments variable first, THEN uses new value
1-34
Post-Increment in Action
Post-Increment in Expressions:
int
n = 2,
valueProduced;
valueProduced = 2 * (n++);
cout << valueProduced << endl;
cout << n << endl;
This code segment produces the output:
4
3
Since post-increment was used
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
1-35
Pre-Increment in Action
Now using Pre-increment:
int
n = 2,
valueProduced;
valueProduced = 2 * (++n);
cout << valueProduced << endl;
cout << n << endl;
This code segment produces the output:
6
3
Because pre-increment was used
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
1-36
12
1/29/2014
1-37
Commenting Programs
A comment is descriptive text used to help a
reader of the program understand its content.
C++ supports two different styles of comments
Style 1: multi-line comments:
Comment begins with the characters /* and end
with the characters */
These are called comment delimiters
As the name implies, these comments can span
multiple lines
38
Commenting Programs
Style 2: single-line comments:
Comment begins anywhere in a line with a // (a
double forward-slash)
Everything from the // to the end of the line is
ignored as a comment
13
1/29/2014
Comment Examples
End of line comment:
vol = x * y * z; // compute the volume
Multi-line comment:
/*
* sort the array using
* selection sort
*/
40
Tricky Comments
What will this do?
/* Comments
cout << Hello;
// */
1-41
C-strings
C++ has two different kinds of string of
characters:
the original C-string: array of characters
The object-oriented string class
1-42
14
1/29/2014
C-strings
You can initialize a C-string variable:
char myString[80] = Hello world;
This will set the first 11 characters as given, make
the 12th character \0, and the rest unused for
now
1-43
String type
C++ added a data type of string to store
sequences of characters
Not a primitive data type; distinction will be made
later
Must add #include <string> at the top of the
program
The + operator on strings concatenates two
strings together
cin >> str where str is a string only reads up to the
first whitespace character
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
1-44
String Equality
In Python, you can use the simple ==
operator to compare two strings:
if name == Fred:
In C++, you can use == to compare two
string class items, but not C-strings!
To compare two C-strings, you have to use the
function strcmp(); it is not syntactically
incorrect to compare two C-strings with ==,
but it does not do what you expect
Copyright 2012 Pearson Addison-Wesley. All rights reserved.
1-45
15
1/29/2014
Console Input/Output
I/O objects cin, cout, cerr
Defined in the C++ library called
<iostream>
Must have these lines (called preprocessor directives) near start of file:
#include <iostream>
using namespace std;
Tells C++ to use appropriate library so we can
use the I/O objects cin, cout, cerr
1-46
Console Output
What can be outputted?
Any data can be outputted to display screen
Variables
Constants
Literals
Expressions (which can include all of above)
1-47
1-48
16
1/29/2014
Input/Output (1 of 2)
1-49
Input/Output (2 of 2)
1-50
Formatting Output
Formatting numeric values for output
Values may not display as youd expect!
cout << "The price is $" << price << endl;
If price (declared double) has value 78.5, you
might get:
The price is $78.500000 or:
The price is $78.5
1-51
17
1/29/2014
Formatting Numbers
"Magic Formula" to force decimal sizes:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
These stmts force all future couted values:
To have exactly two digits after the decimal place
Example:
cout << "The price is $" << price << endl;
Now results in the following:
The price is $78.50
1-52
Error Output
Output with cerr
cerr works same as cout
Provides mechanism for distinguishing
between regular output and error output
1-53
1-54
18
1/29/2014
1-55
\n
Libraries
C++ Standard Libraries
#include <Library_Name>
Directive to "add" contents of library file to
your program
Called "preprocessor directive"
Executes before compiler, and simply "copies"
library file into your program file
1-57
19
1/29/2014
Namespaces
Namespaces defined:
Collection of name definitions
Examples:
#include <iostream>
using namespace std;
Includes entire standard library of name definitions
1-58
20