A computer is a machine that follows instructions. A program is the list of instructions for the computer to execute. Someday programs will be written in English. Until then, programs are written in simpler languages such as C or C++.
https://markmeretzky.com/INFO1-CE9264/src/hello.C
:
markmeretzky.com
,
the filename ends with
.C
(uppercase);
on your machine, the filename might end with
.CPP
or
.CXX
.
On some systems,
the files that make up the program are held in a
project.
A C++ program is
case-sensitive:
it makes a difference if you write in uppercase or lowercase.
"
double-quoted"
strings and the newline (\n
).std::cout
for standard output (the output producted by the program)std::cerr
for standard error output (error messages)std
.
No space between colons.
<<
operator points towards the destination.
No space between
<’s
;
type it exactly the way I do.
main
.
The lines
int main() {mark the start of the
main
function;
the line
}marks the end. Conventional to indent the body of the function one tab. The parentheses will not be used until later; we still have to write them even though they’re empty. This pattern will appear often:
keyword (parentheses) {curly braces}
.
int
from the
main
function to the operating system:
EXIT_SUCCESS
for success,
EXIT_FAILURE
for failure.
system("PAUSE");
markmeretzky.com
:
/usr/include/c++/11/iostream/iostream
for
cout
,
cerr
,
<<
/usr/include/c++/11/cstdlib
for
EXIT_SUCCESS
//
for single-line/* */
for multi-linecerr
is immune to
>
,
so send input prompts to
cerr
when the standard out is directed into a file.
If you said
system("PAUSE");
,
you will have to press any key to continue.
using.C
:
A
namespace
is a family of things that share the same last name.
using
gets us on a first-name basis with all the members of a namespace.
dime1.C
and
dime2.C
.flag.C
:
10 lines of output.
Later we’ll do all the output in a single statement:
cout << "* * * * * * =====================\n" << " * * * * * =====================\n" << "* * * * * * =====================\n" << " * * * * * =====================\n" << "* * * * * * =====================\n" << "=================================\n" << "=================================\n" << "=========E pluribus unum=========\n" << "=================================\n" << "=================================\n";
batman.bmp
.
My friend tried it and came up with “Cat Woman”.variable.C
:
create
int
variables and give them an initial value.
Send several items to the same destination in a single statement;
retrofit this technique into
flag.C
.
minimum.C
:
the minimum and maximum value that can be held in an
int
may be different on each platform.
INT_MIN
,
INT_MAX
.
The header file
climits
(known as
limits.h
in the languge C)
has its own
Wikipedia article.
expression.C
:
An
expression
is made of
operands
and
operators.
The operands could be
literals
(10
,
20
,
30
)
or variables
(i
,
j
,
k
).
The operators could be
+
–
*
/
etc.
Override operator precedence and associativity with parentheses.
Table of precedence and associativity on page 6 of
Chapter 1.
Examples of different associativities:
//left-to-right associativity a + b + c //order doesn't matter: you get the same sum either way cout << a << " " << b << " " << c << "\n"; //order does matter //right-to-left associativity c = b = a = 10; ++*p *++p a ? b : c ? d : eExpressions where some of the operators are executed in an unpredictable order:
a * b + c * d //can't predict which multiplication is performed first f() + g() //can't predict which function is called first int a[100]; int i = 10; a[i] = ++i; //puts the value 11 into either a[10] or a[11]
remainder.C
:
division and remainder.
Integer division truncates.
Unportable results for negative numbers.
Unpredictable behavior for division by zero;
what is the exit status?assign.C
:
Assign a new value to a variable.
The new value can be an expression,
possibly mentioning the same variable.
Integer overflow.
Can’t assign to a
const
variable.jobdone1.C
:
when will the job be done?
An i/o manipulator that takes an argument
(setfill
,
setw
)
requires
<iomanip>
.
input.C
:
std::cin
is the standard input.
Check for input failure
(e.g., a word instead of a whole number;
an integer that is too big or too small to fit in an
int
;
premature end-of-input;
or hardware failure).
if
statement has same
(
parentheses)
and
{
curly
braces}
braces as the
main
function.
EXIT_FAILURE
;
check the exit status.
age.C
,
wait.C
,
cents.C
,
turkey.C
,
change.C
.
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 |
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.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.