A computer is a machine that follows instructions. The list of instructions you put into the computer is called a program. In the future, it will be possible to write programs in English. But that day hasn’t come yet, so for the time being we write programs in simpler languages such as C++. This is a course in writing, reading, executing, and debugging programs in C++. This language is an extension of the earlier language C. In other words, C++ is a superset of C, and C is a subset of C++.
CISC-1600 will cover the C subset of C++, except for pointers, structures, and pointers to structures. The rest of C++, including the techniques for object-oriented programming, will be covered in CISC-2000.
Our first C++ programs must tell the computer to produce output; otherwise we would never know if the programs were executed correctly, or even if they were executed at all.
storm.cis.fordham.com
,
the filename ends with
.C
(uppercase);
on other machines, the filename might end with
.CPP
or
.CXX
.
std::cout
means
“the outside world, considered as a destination for output”.
This output will be a stream of characters;
that’s what the
c
in
cout
stands for.
A
namespace
is a family of things that share the same last name,
in this case the name
std
.
Last name first, first name last.
No space between the two colons.
#include
a header file.
<<
(“put to”) operator points towards the destination.
No space between
<’s
;
type it exactly the way I do.
"
double-quoted"
strings and the invisible newline (\n
).
24 characters, followed by the newline character,
followed by the terminating zero character.
;
)
at the end of each statement.
main
.
The lines
int main() {mark the start of the
main
function;
the line
}marks the end. The body of the function is the statements between the two curly braces. Conventional to indent the body of the function by one tab. The parentheses will not be used until later; we still have to write them even though they’re empty.
int
from the
main
function to the operating system:
EXIT_SUCCESS
for success,
EXIT_FAILURE
for failure.
Another header file.
system("PAUSE");
storm.cis.fordham.edu
:
/usr/include/c++/14/iostream
/usr/include/c++/14/cstdlib
for
EXIT_SUCCESS
c++ -v
storm.cis.fordham.edu
:
find / -type f -name iostream 2> /dev/null
//
for single-line/* */
for multi-linestorm.cis.fordham.edu
and explore your account.
See below.
dime1.C
:
flag.C
:
Put in a
using directive
to get on a first-name basis with
cout
.
Do all the output with only one statement, not ten statements.
Run the program and deposit the output into a file named
flag.txt
.
Copy the program and flag.txt
into your
public_html
directory so everybody can see these two files.
//This is only one statement, not a complete C++ program. //Output three copies of the ASCII "alarm" character. std::cout << "\a\a\a\n";
return
?
//Not a complete C++ program. return EXIT_SUCCESS; std::cout << "Never reaches this point.\n"; }
You will need your Fordham credentials, i.e.,
your Fordham email name and password.
If you’ve never gotten them,
go to
my.fordham.edu
and click on the red
“New user: Claim account”.
cmd
ssh jsmith@storm.cis.fordham.edu
storm.cis.fordham.edu
.
It will ask you to change your password.
When you’re finished changing your password,
try a few simple Linux command such as
date
or
cal
.
The
@storm:~$
or the
jsmith@storm:~/public_html$
that keeps reappearing is the prompt.
Case counts.
jsmith@storm:~$ date jsmith@storm:~$ cal jsmith@storm:~$ cd (Go to your personal "home" directory on storm.cis.fordham.edu) jsmith@storm:~$ pwd (Make sure you arrived there.) jsmith@storm:~$ ls -l (See what's there. Ignore the "total".) jsmith@storm:~$ cd public_html (Go down to your public_htm directory; space before public_html, with underscore _) jsmith@storm:~/public_html$ pwd jsmith@storm:~/public_html$ ls -l jsmith@storm:~/public_html$ cd .. (Go one level upstairs; space before, but not in between, the two periods.) jsmith@storm:~$ pwd jsmith@storm:~$ ls -l
Go on an expedition to the top of the tree of directories.
“Compiler” means “translator”.
Out compiler
c++
will translate your C++ program into terms that
storm.cis.fordham.edu
can understand and execute.
The compiler will place the translation into a new file named
a.out
.
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/dime/dime1.C jsmith@storm:~$ ls -l jsmith@storm:~$ cat dime1.C (See what's in the new file dime1.C.) jsmith@storm:~$ c++ dime1.C jsmith@storm:~$ ls -l (There should be a new file named "a.out". Do not cat this file.) jsmith@storm:~$ ./a.out (Execute the a.out file in the current directory.) jsmith@storm:~$ ./a.out > dime1.txt (Execute the a.out file and deposit its output into dime1.txt) jsmith@storm:~$ ls -l (See if there's a new file named "dime1.txt" in the current directory.)
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ cp dime1.C public_html (Copy the file dime1.C into your public_html directory.) jsmith@storm:~$ cp dime1.txt public_html (Copy the file dime1.txt into your public_html directory.) jsmith@storm:~$ cd public_html jsmith@storm:~$ pwd jsmith@storm:~$ ls -l (Are there two new files in the public_html directory?)
To see the two files
dime1.C
and
dime1.txt
that you just copied into your
public_html
directory,
point your web browser at
https://storm.cis.fordham.edu/~jsmith/dime1.C
https://storm.cis.fordham.edu/~jsmith/dime1.txt
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ rm dime1.txt (Remove the dime1.txt that's in your home directory) jsmith@storm:~$ ls -l (Make sure it's gone.)
There’s even an
O’Reilly
book
and
pocket
reference
about
vi
.
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/xanadu.txt jsmith@storm:~$ ls -l jsmith@storm:~$ vi xanadu.txt jsmith@storm:~$ ls -l (Is the number of bytes in xanadu.txt different now?)
A minimal set of
vi
commands.
When in doubt, press the
ESC
ape key in the upper left corner of the keyboard,
to make sure you’re not in “insert mode”.
←
↑
↓
→
10G
x
,
4x
dd
,
4dd
i
(before)
or
a
(after
the cursor).
ESC
ape
key.
o
(below) or uppercase
O
(above the cursor).
ESC
ape
key.
:w
vi
with (lowercase) :q
jsmith@storm:~$ exit
to log off from
storm.cis.fordham.edu
.
exit
to log off from the black Microsoft
cmd
window.
A variable is a container inside the computer that can contain a value such as
true
or
false
Four definitions:
variable1.C
:
define, declare, and initialize a variable
all in one statement.
Then output the contents of the variable.
cout << "The variable contains price.\n";
variable2.C
:
Assign a new value to the variable.
variable3.C
:
Old-fashioned (pre-2011) way to define a variable.
variable4.C
:
What’s the biggest number this type of variable can hold?
maxInt
is “camel case”,
EXIT_SUCCESS
and
numeric_limits
are “snake case”.
bc
,
the Linux “binary calculator”.
The keystroke
control-d
tells
bc
that you’re not planning to type in any more arithmetic problems for it.
jsmith@storm:~$ bc -l 2^31 2147483648 control-d jsmith@storm:~$See Why do the possible values for an int go from -2,147,483,648 to +2,147,483,647?
variable5.C
:
input a value from the outside world and store it into a variable.
Check that the input was successful.
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ wget https://markmeretzky.com/fordham/1600/src/variable/variable5.C jsmith@storm:~$ c++ variable5.C jsmith@storm:~$ ls -l jsmith@storm:~$ ./a.out Please type the price and press RETURN. 13 The variable contains 13. jsmith@storm:~$ echo $? 0 (EXIT_SUCCESS stands for this number.) jsmith@storm:~$ ./a.out Please type the price and press RETURN. hello Sorry, that wasn't an acceptable number. jsmith@storm:~$ echo $? 1 (EXIT_FAILURE stands for this number.)Exercise. What happens if you try to input an out-of-bounds value such as
2147483648
or
-2147483649
into the variable?
What is the invisible exit status number?
variable5.C
)
from an input file
(thirteen.txt
),
instead of from the keyboard.
First create a very small file containing the two digits
13
and a newline,
a total of just three characters.
We could create this little file with
vi
,
but it’s easier to create it with
echo
.
jsmith@storm:~$ cd jsmith@storm:~$ pwd jsmith@storm:~$ ls -l jsmith@storm:~$ echo 13 (echo is the Linux "print" command.) 13 jsmith@storm:~$ echo 13 > thirteen.txt jsmith@storm:~$ ls -l (There should be a new file named "thirteen.txt".) jsmith@storm:~$ cat thirteen.txt 13 jsmith@storm:~$ ./a.out < thirteen.txt Please type the price and press RETURN. The variable contains 13.
jsmith@storm:~$ ./a.out < thirteen.txt > variable5.txt jsmith@storm:~$ ls -l jsmith@storm:~$ cat variable5.txt Please type the price and press RETURN. The variable contains 13.
integer.C
.
Define (i.e., create) variables of the other signed integer data types.
double.C
.
Define variables of types that can hold a number with a fraction.
format.C
.
Output more (or fewer) of the digits of a
double
.
-std=c++20
because
std::format
is a new feature available in the C++20 version of the language C++.
bool.C
.
A variable of type
int
can hold one of
4,294,967,296
different values,
from -2,147,483,648 to 2,147,483,647 inclusive.
bool
can hold one of only
2
different values.
true
to
false
in this program.
char.C
.
On
storm.cis.fordham.edu
,
a variable of type
char
can hold the code number of a single
ASCII
character.
string.C
.
A variable of type
std::string
can hold a string (series) of characters.
Definitions.
20*30
)
is how you tell the computer to perform arithmetic
(and/or other more exotic operations).
*
)
for multiplication.
20*30
is
600
.
20*30
has a value, it can be used as part of a larger expression such as
10+20*30
.
610
is of type
int
,
and the value
'A'
is of type
char
.
+
-
*
/
etc.
x
for multiplication?
10
20
3.14
i
j
k
price
10+20
price+20
i-j+10
-a
+a
a+b
a-b
b=a
cout<<a
a?b:c
places.C
:
three places where we can write an expression in a C++ program.
int i {10 + 20}; //i is born holding 30or out of variables that are currently holding a value:
int j {10}; //j is born holding 10 int k {j + 20}; //k is born holding 30Don’t do this:
int j; //j is born containing unpredictable garbage int k {j + 20}; //k is born containing bigger unpredictable garbageAnd the following snippet will be totally rejected by our C++ compiler
c++
.
The program won’t even “compile”.
int k {j + 20}; //The computer doesn't know yet what "j" means. int j {10};
precedence.C
:
multiplication
(*
)
has higher precedence than addition
(+
).
associativity.C
:
addition and subtraction have left-to-right associativity.
lobster.C
.
Example of an expression.
Then you bank the heat and let the kettle simmer—ten minutes for the first pound of lobster, then three minutes for each pound after that. (This is assuming you’ve got hard shell lobsters, which, again, if you don’t live between Boston and Halifax is probably what you’ve got. For shedders [soft-shell], you’re supposed to subtract three minutes from the total.) |
||
—David Foster Wallace, Consider the Lobster |
Some operators do nothing more than compute a value:
y + x
10 + 20
Other operators also have
side effects
such as
y = x
cout << x
cin >> x
precedence2.C
.
*
(multiplication)
has higher precedence than
=
(assignment).
*
(multiplication)
has higher precedence than
<<
(output).
associativity2.C
.
<<
and
>>
have left-to-right associativity.
=
has right-to-left associativity.
See lines 5, 16, and 7 of
this
table.
assignment.C
.
The
assignment operators:
+=
-=
*=
/=
etc.
increment.C
.
The
increment operators:
++
--
(that’s two dashes)
division.C
.
Warning.
Integer division “truncates”
(get chopped down to the next integer).
remainder.C
.
Introducing the remainder operarator
%
.
nottoprogram.C
:
how not to program.
Idiom is to count from 0 to 9 inclusive,
not from 1 to 10 inclusive.while.C
:
while
loop has same
(
parentheses)
and
{
curly
braces}
braces as the
main
function and the
if
statement.
Conventional to count from 0 to 9 inclusive,
not 1 to 10 inclusive,
because array subscripts will start at 0.
Prefix increment operator
++
.
<=
operator––
(two minus signs, no space between them)for1.C
:
put all three vital statistics on the same line.for2.C
:
make
i
local to the loop.
How long does it take to loop a billion times?beer.C
:
A Hundred Bottles of Beer
on the Wallinfinite.C
:
an infinite looppierogies.C
:
needs only one variablethruway.C
:
needs only one variabledowhile.C
:
do-while
lucy1.C
:
and
lucy2.C
:
Lucy in the Sky
With Diamondsline.C
and
rectangle.C
.
A
Scratch
script
rectangle.sb
.graph1.C
:
no loop, hardwired to do 10 rows and 10 columnsgraph2.C
:
one loop, inputs the number of rows, hardwired to do 10 columnsgraph3.C
:
nested loops, inputs the number of rows and columnsHow many rows of boxes? 2 How many columns of boxes? 4 How many rows of blanks in each box (e.g., 1)? 1 How many columns of blanks in each box (e.g., 3)? 4 +----+----+----+---- | | | | +----+----+----+---- | | | |
How many rows of boxes? 2 How many columns of boxes? 4 How many rows of blanks in each box (e.g., 1)? 3 How many columns of blanks in each box (e.g., 3)? 8 +--------+--------+--------+-------- | | | | | | | | | | | | +--------+--------+--------+-------- | | | | | | | | | | | |
factor.C
:
find the prime factors of an integer.
Only need to loop as far as
factor <= sqrt(n)
.if.C
:
if
statementif
:
else1.C
and
else2.C
:
if-else statement.
if_in_then1.C
and
if_in_then2.C
:
put a smaller
if
into the
then
section of a larger
if
that has no
else
.
if_in_else1.C
and
if_in_else2.C
:
put a smaller
if
into the
else
section of a larger
if
.
else-if
:
threeway.C
:
steer the computer in one of three possible directions.chance.C
:
keep giving the user another chance to enter valid input.if (it is possible to remain inside the train) { remain inside the train; } else if (you are able to go to next car through end doors) { go to next car through end doors; } else if (you can open the side door and get out) { open the side door and get out; } else { go out emergency windows; }
leap.C
:
steer the computer in one of four possible directions.ordinal1.C
and
ordinal2.C
:
steer the computer in one of five possible directions.
&&
means “and”.else-if
inside a loop
toolow.C
,
the
dowhile.C
guessing game with hints.
break
out of an infinite loop.range.C
:
for (;;)
loop containing three-way
if
.
Make sure input was successful and value in range.
Also
&&
,
and
break
.flag
gateway:
three-way
if
sine.C
and
sine.gif
:
three-way
if
.
Plot
sine
curve in front of axes.
Scale it vertically and horizontally.
mandelbrot.C
and
mandelbrot.gif
.switch
and
case
:
can be used only if all the comparisons are for equality to integral values
(int
,
char
,
bool
,
etc.)
that are constants, not variables.
integer.C
:
The four types of integers:
signed char
,
short
,
int
,
long
.
Use
signed char
for a small integer,
char
for a character.
Integer division truncates;
don’t divide by zero.
By default,
signed char
prints as a character;
cast (i.e., convert) it to
int
with
static_cast
to see it as a decimal integer.
One single-quoted character stands for the code number of that character
in the local character set.
limits.C
:
Include the header file
<climits>
for the macros
CHAR_BIT
,
SCHAR_MIN
,
etc.
(Better yet, we will eventually include the header file
<limits>
for the
template class
numeric_limits
.)
A data type used as the operand of
sizeof
must be in parentheses.
On my platform, the minimum and maximum values, inclusive, are as follows.
signed char: –128 to 127 short: –32,768 to 32,767 int: –2,147,483,648 to 2,147,483,647 long: –2,147,483,648 to 2,147,483,647
char1.C
:
and
char2.C
:
use the data type
char
to hold a character.
(What it really holds is the character’s code number.)
char1.C
works only for ASCII;
char2.C
works for any character set that can be held in a
char
(e.g., EBCDIC).
The cast prevents the
char
argument of
isprint
from sign extending as it is converted to
int
.
wchar_t.C
:
a wide characters is 4 bytes on my machine.
Bloodshed does not recognize the object
wcout
.
In
g++
on
i5.nyu.edu
,
wcout
stops outputting when you feed it a
wchar_t
containing a number >= 256.
bool.C
:
A
bool
can hold one of exactly two possible values.float1.C
:
float
,
double
,
long double
.
Format with
fixed
and
setprecision
;
see
Chapter 4,
pp. 355–356.
float2.C
:
minimum and maximum values.float3.C
:
static_cast
.double
arithmetic:
gallon.C
:
double
division does not truncate.
if-else
containing an assignment statement.
numeric_limits
gives value of
∞.
We could have initialized
mpg
with a
?:
expression:
const double mpg = gallons == 0 ? numeric_limits<double>::infinity() : miles / gallons;
interest.C
and the approximation
72.C
(see the Rule of 72):
how many years does it take for the principal to double?
double
arithmetic for money,
do-while
log
function.
1.06 × 1.06 × 1.06 × … | = | 2 | ||
1.06y | = | 2 | ||
(eln 1.06)y | = | eln 2 | ||
(ln 1.06)y | = | ln 2 | ||
y | = |
|
organ.C
:
organ pipes spanning one octave.
Raise a number to a power with the
pow
function.pi.C
:
random1.C
: the
rand
function returns random integers in the range 0 to
RAND_MAX
inclusive.random2.C
:
the
srand
function.
Different random numbers each time you run the program.
Convert the return value of
time
from
time_t
to
unsigned
.
random3.C
:
random integers in the range 0 to 99 inclusive.random4.C
:
random fractions in the range 0 to 1 inclusive.../../../INFO1-CE9264/src/pi.C
:
compute π by the
Monte Carlo
method.
Seed the random number generator with
time
and
srand
.
Eliminate the call to the
sqrt
function by squaring both sides of the inequality.
For
double
absolute value,
call
fabs
in C,
abs
in C++.
mother.C
:
search for a small string in a big one.
The data type
string
string
(short for
basic_string
of
char
s)
is not built into the language;
must include the header file
<string>
.
npos
has the last name
string
,
just as
cout
has the last name
std
.array1.C
and
array2.C
:
array of
int
’s.
Initial value for each array element.
Use the data type
size_t
for a variable that holds the number of elements in an array,
or that holds an array subscript.
It is probably unnecessary to include the header file
<cstddef>
for
size_t
,
since one of the other header files probably includes that one.array3.C
:
an array of
string
’smonkey1.C
: the Year of the Monkey.
Use
%
to compute the subscript of an element in an array of
string
’s.
monkey2.C
: same program, but with
if
statements instead of array.
monkey3.C
: same program, but with
switch
.
plot.C
: from the
Movie
Plot Generator
book.dependents1.C
and
dependents2.C
:
number of dependents, without and with an array.date.C
:
pretend that there is no such thing as a leap year
in the following homework.
Don’t worry about
time
and
localtime
;
we’ll do them after we do structures, functions, and pointers.
distance
into
years
and
days
,
where
days
is in the range 0 to 364 inclusive.
(Break
distance
down the same way we broke 205 minutes into 3 hours and 25 minutes,
or 205 cents into 2 dollars and 5 cents.
You fail the course if you break
distance
down like this:
int years = distance / 365 * 365; int days = distance - 365 * years;) For the time being, assume that the user will input a non-negative
distance
.
You can then add
years
to
year
,
leaping in a single bound to within one year of the destination.
distance
.
Break
distance
into
years
and
days
as above.
Then if
days
turns out to be negative
(as a result of a negative
distance
),
add 365 to
days
to make
days
non-negative
(guaranteeing that
days
will now be in the range 0 to 364 inclusive),
and compensate for the addition by subtracting 1 from
years
.
For example, on some machines a distance of
days
non-negative will make your loop much simpler.
You get no credit if there is more than one loop.
For example, do not write two loops, one to go forward and one to go back.
א
are
א) and display the output file in a web browser.
bubblesort.C
:
sort in increasing and decreasing order.
Right justify with
setw
.
bubblesortstrings.C
:
sort strings in alphabetical order.howrandom.C
:
how random are the random numbers we get from
srand
and
rand
?
Write into an uninitialized array, and then read from it.twod.C
:
a two-dimensional array.sudoku.C
:
If the top row of a
Sudoku
has exactly one missing number, fill it in.
street1.C
(no array),
street2.C
(one-dimensional array),
street3.C
(two-dimensional array).avenue.C
:
Manhattan Avenuesstruct.C
:
a structure containing two fields.
Define the structure data type outside of main,
even though we don’t need to yet.
single1.C
:
a single array of structures instead of the two parallel arrays in
parallel.C
or
avenue.C
plot.C
smart enough to know that a singular subject (“A single mom”)
takes a singular verb (“fights crime”),
while a plural subject (“Three naughty nurses”)
takes a plural verb (“fight crime”).
You’ll be able to get rid of all those parenthesized letters
(“fight(s) crime”).
Change
subject
from an array of
string
s
to an array of structures.
Each structure will have two fields:
a
size_t
(0
for singular,
1
for plural)
and a
string
giving the subject of the sentence.
Change
predicate
from a one-dimensional array of
string
s
to a two-dimensional array of
string
s
(30 or more rows and 2 columns).
Column 0 will contain
predicates with a singular verb
("fights crime"
).
Column 1 will contain the corresponding predicates with plural verbs
("fight crime"
).
You can use the idiom
sizeof arrayname / sizeof arrayname[0]
predicate
array.
Print out the predicate that agrees in number with the subject.
No
if
statements are required for this homework.
If you write
if
statements,
your code is unnecessarily complicated.
Entertain me by inventing additional subjects, predicates, and modifiers.
rose.C
:
two-dimensional array of structures draws
this picture
of
sine
in polar coördinates.function1.C
and
function2.C
:
consolidate repeated chunks of code,
with a loop if consecutive,
with a function otherwise.
Function must be declared before it is otherwise mentioned.
Secret Agent Man:
audio.
automatic.C
:
a variable defined in a function
(factorial)
is
automatically allocated:
it lives only while we are within the
{
curly braces}
of the function.
Factorial is the number of permutations.argument.C
:
pass an argument by value to a function.
retval.C
:
return a value from a function.
The
main
function has been returning
int
all along.static.C
:
a
statically allocated
variable is immortal.weekday.C
:
a function that is called from only two places.
Package code as a function
to divide the program into cleanly separated sections.
time.C
.
We saw the
time
and
localtime
functions in
date.C
.main
function.if
that does the call only if there is still part of the job remains undone.rprint.C
:
print the integers from 1 to 10 inclusive.
The starting point is passed as an argument;
the ending point 10 and the stride 1
are hard-wired into the recursive function.end.C
:
pass the ending point as a second argument.stride.C
:
pass the stride as a third argument.factorial.C
:
compute the factorial of a number without a for
loop.macguffin.C
and
macguffin1.C
:
search without a loop.gcd.C
:
can you write this without a loop?
Use GCD to find aspect ratio of screen: 1027 × 768.
samename.C
:
a global variable, and a global variable with the same name as a local
variable.
The unary scope resolution operator
::
.const
or non-const
)
or a function (inline or non-inline)
in one
.C
file,
and mention it in another.
.h
)
file#ifndef
to prevent a
.C
file from including the same header twice.const
global variable is
static
by default.
reference.C
:
pass-by-value vs. pass by reference.
One motivation for pointers is to allow a function to change the value
of its argument.pass_array.C
:
an array is always passed by reference.
This array is one-dimensional.pass_array2.C
:
pass a two-dimensional array to a function.
pp.C
:
a pointer to a pointersize_t
subscript in square brackets.
moving.C
:
compute the moving average of a series of numbers.
Replace
i
and
j
with two pointers named
p
and
q
as in the above
bubblesort.C
and the
sort.C
in
Chapter 1,
p. 48.
single1.C
and
single2.C
Chapter 1,
p. 81.
Global functions and variables,
extern
, header files.