0% found this document useful (0 votes)
40 views

First Lesson C++

Computer Science Notes.

Uploaded by

far
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

First Lesson C++

Computer Science Notes.

Uploaded by

far
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1/29/2014

C++ Primer I
CMSC 202

Topics Covered

Our first Hello world program


Basic program structure
main()
Variables, identifiers, types
Expressions, statements
Operators, precedence, associativity
Comments
C-strings, C++ string class
Simple I/O: cin, cout, cerr
2

A Sample C++ Program

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-3

1/29/2014

Using the C Compiler at UMBC


Invoking the compiler is system dependent.
At UMBC, we have two C compilers available, cc
and gcc.
For this class, we will use the gcc compiler as it is
the compiler available on the Linux system.

Invoking the gcc Compiler


At the prompt, type
g++ -Wall program.cpp o program.out
where program.cpp is the C++ program source file
(the compiler also accepts .cc as a file extension for
C++ source)
-Wall is an option to turn on all compiler warnings
(best for new programmers).

The Result : a.out


If there are no errors in program.cpp, this command
produces an executable file, which is one that can be
executed (run).
If you do not use the -o option, the compiler names
the executable file a.out .
To execute the program, at the prompt, type
./program.out
Although we call this process compiling a program,
what actually happens is more complicated.
6

1/29/2014

UNIX Programming Tools


We will be using the make system to
automate what was shown in the previous few
slides
This will be discussed in lab

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-7

Variable Declaration

Syntax:

Examples:
int sum;
float average;
double grade = 98;

<type> <legal identifier>;

Semicolon required!

Must be declared before being used


May appear in various places and contexts (described later)
Must be declared of a given type (e.g. int, float, char, etc.)

Variable Declarations (cont)


When we declare a variable, we tell C++:
When and where to set aside memory space for
the variable
How much memory to set aside
How to interpret the contents of that memory: the
specified data type
What name we will be referring to that location by:
its identifier

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.

Cannot be a keyword, or other reserved


10

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

We have our own CMSC 202 standards, given in


detail on the course website, to be used on all
projects

11

Naming Conventions in C++


Variables:
Start with a lowercase letter
Indicate "word" boundaries with an uppercase letter
Restrict the remaining characters to digits and lowercase
letters
topSpeed

bankRate1

timeOfArrival

Classes and functions


Start with an uppercase letter
Otherwise, adhere to the rules above

FirstProgram

MyClass

BankAccount
12

1/29/2014

Naming Conventions in C++


Class members:
Must have a m_ prefix
Then start with a lowercase letter
Rest of the rules the same as for variables
m_name

m_dailyRate

Other rules as given on class web site

13

Data Types:
Display 1.2 Simple Types (1 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-14

Data Types:
Display 1.2 Simple Types (2 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-15

1/29/2014

Assigning Data
Initializing data in declaration statement
Results "undefined" if you dont!
int myValue = 0;

Assigning data during execution


Lvalues (left-side) & Rvalues (right-side)
Lvalues must be variables
Rvalues can be any expression
Example:
distance = rate * time;
Lvalue: "distance"
Rvalue: "rate * time"

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-16

Data Assignment Rules


Compatibility of Data Assignments
Type mismatches
General Rule: Cannot place value of one type into variable of
another type

intVar = 2.99;

// 2 is assigned to intVar!

Only integer part "fits", so thats all that goes


Called "implicit" or "automatic type conversion"

Literals
2, 5.75, "Z", "Hello World"
Considered "constants": cant change in program

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-17

Display 1.3
Some Escape Sequences (1 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-18

1/29/2014

Display 1.3
Some Escape Sequences (2 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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?

Instead, you should use named constants


Represent the constant with a meaningful name
Also allows you to change multiple instances in a
central place
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-20

Constants
There are two ways to do this:
Old way: preprocessor definition:
#define WEEKS_PER_YEAR 52

This textually replaces the name with the value


(Note: there is no =)
New, better way: constant variable:
Looks just like variable declaration, including type
Just add the keyword const to the declaration
const float PI = 52;

Compiler enforces immutability


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-23

Binary Operators

What is a binary operator?

An operator that has two operands

<operand> <operator> <operand>

Arithmetic Operators

Relational Operators

+ - * / %
<

>

==

<=

>=

Logical Operators

&&

||
24

1/29/2014

Relational Operators

In C++, all relational operators evaluate to a boolean value of either


true or false .

x = 5;
y = 6;

x > y will always evaluate to false .

C++ has a ternary operator the general form is:

For example:

(conditional expression) ? true case : false case ;

Cout << (( x > y ) ? "X is greater" : "Y is greater");

25

Unary Operators
Unary operators only have one operand.
!

++

--

++ and -- are the increment and decrement operators


x++ a post-increment (postfix) operation
++x a pre-increment (prefix) operation

What is the difference between these segments?

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:

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


Unary operators: + - ++ -- ! (right to left)
* / % (left to right)
+ - (left to right)
< > <= >=
== !=
&&
||
?:
Assignment operator: = (right to left)
27

1/29/2014

Arithmetic Precision
Precision of Calculations
VERY important consideration!
Expressions in C++ might not evaluate as
youd "expect"!

"Highest-order operand" determines type


of arithmetic "precision" performed
Common pitfall!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-28

Arithmetic Precision Examples


Examples:
17 / 5 evaluates to 3 in C++!
Both operands are integers
Integer division is performed!

17.0 / 5 equals 3.4 in C++!


Highest-order operand is "double type"
Double "precision" division is performed!

int intVar1 =1, intVar2=2;


intVar1 / intVar2;
Performs integer division!
Result: 0!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-29

Individual Arithmetic Precision


Calculations done "one-by-one"
1 / 2 / 3.0 / 4 performs 3 separate divisions.
First 1 / 2 equals 0
Then 0 / 3.0 equals 0.0
Then 0.0 / 4 equals 0.0!

So not necessarily sufficient to change


just "one operand" in a large expression
Must keep in mind all individual calculations
that will be performed during evaluation!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Explicit type conversion


Programmer specifies conversion with cast operator
(double)17 / 5.5
Same expression as above, using explicit cast
(double)myInt / myDouble
More typical use; cast operator on variable

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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!

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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;

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-33

11

1/29/2014

Shorthand Operators: Two Options


Post-Increment
intVar++
Uses current value of variable, THEN increments it

Pre-Increment
++intVar
Increments variable first, THEN uses new value

"Use" is defined as whatever "context"


variable is currently in
No difference if "alone" in statement:
intVar++; and ++intVar; identical result
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Assigning Data: Shorthand Notations


Display, page 14

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Comments (especially program header


comments) are critical to good programming,
and will be stressed in class projects
Look at the class web page for the required
contents of our header comment.
39

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;
// */

What about this?


// /* Comments
cout << Hello;
*/

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

C-strings are terminated with a null character


(\0)
char myString[80];
would declare a variable with enough space
for a string with 79 usable characters, plus null
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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)

cout << numberOfGames << " games played.";


2 values are outputted:
"value" of variable numberOfGames,
literal string " games played."

Cascading: multiple values in one cout


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-47

Separating Lines of Output


New lines in output
Recall: "\n" is escape sequence for the
char "newline"

A second method: object endl


Examples:
cout << "Hello World\n";
Sends string "Hello World" to display, & escape
sequence "\n", skipping to next line

cout << "Hello World" << endl;


Same result as above

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-48

16

1/29/2014

Input/Output (1 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-49

Input/Output (2 of 2)

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

We must explicitly tell C++ how to output


numbers in our programs!
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

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

Can modify precision "as you go" as well!


Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-52

Error Output
Output with cerr
cerr works same as cout
Provides mechanism for distinguishing
between regular output and error output

Re-direct output streams


Most systems allow cout and cerr to be
"redirected" to other devices
e.g., line printer, output file, error console, etc.

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-53

Input Using cin


cin for input, cout for output
Differences:
">>" (extraction operator) points opposite
Think of it as "pointing toward where the data goes"

Object name "cin" used instead of "cout"


No literals allowed for cin
Must input "to a variable"

cin >> num;


Waits on-screen for keyboard entry
Value entered at keyboard is "assigned" to num
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-54

18

1/29/2014

Prompting for Input: cin and cout


Always "prompt" user for input
cout << "Enter number of dragons: ";
cin >> numOfDragons;
Note no "\n" in cout. Prompt "waits" on same
line for keyboard input as follows:
Enter number of dragons: ____
Underscore above denotes where keyboard entry
is made

Every cin should have cout prompt


Maximizes user-friendly input/output
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-55

Reading from the Console


int n1, n2;
cout << "Enter 2 numbers to sum: ";
cin >> n1 >> n2;
cout << n1 << "+" << n2 << =" << (n1 + n2);

\n

Lets assume the user has entered 128 10 .


The first << reads the characters 128 leaving 10\n in
the input buffer.
The second << (same expression) reads the 10 and leaves
the \n in the buffer. THIS WILL BE IMPORTANT LATER.
56

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

C++ has many libraries


Input/output, math, strings, etc.
Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-57

19

1/29/2014

Namespaces
Namespaces defined:
Collection of name definitions

For now: interested in namespace "std"


Has all standard library definitions we need

Examples:
#include <iostream>
using namespace std;
Includes entire standard library of name definitions

#include <iostream>using std::cin;


using std::cout;
Can specify just the objects we want

Copyright 2012 Pearson Addison-Wesley. All rights reserved.

1-58

20

You might also like