Home  Previous  Next 

CSC100 :: Lecture Note :: Week 03
Assignments 
Code 
Handouts 
Resources 
Email Thurman
{Twitter::@compufoo
Facebook::CSzero}
{GDT::Bits::
Time

Weather

Populations

Special Dates}
Assignment(s):
cout
ObjectIn order to use the C++ Streams I/O, the
iostream.h
header file must be included. In addition, inclusion ofiomanip.h
is often needed.#include <iostream> #include <iomanip>Upon program startup, the
cout
object of classostream
is instantiated.Output to the terminal screen (or the standard output) is performed using the
cout
object, and the left bitshift operator<<
in combinations.cout << EXPR; // in many instances, EXPR needs to be inside ()'sMultiple values can be output by executing the following.
cout << EXPR << EXPR << EXPR << ...;Only one EXPR is allowed after each
<<
The<<
points in the direction of the data flow tocout
(the standard output) and is referred to as the insertion operator.A
cout
object does not automatically place spaces between values being output, and it does not automatically add a newline at the end of its output.Both
"\n"
and'\n'
result in a newline being printed to the standard output. In addition, theendl
I/O manipulator can be used to print a newline. Example: the following statements all print a newline followed by the value of an EXPR followed by another newline:
cout << endl << EXPR << endl; cout << "\n" << EXPR << "\n"; cout << '\n' << EXPR << endl; cout << endl << EXPR << "\n"; cout << '\n' << EXPR << '\n';C and C++ I/O can be mixed on a percharacter basis, but to ensure data is sent/received in the proper order a call to
sync_with_stdio()
should be made.
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
cin
ObjectIn order to use the C++ Streams I/O, the iostream header file must be included.
Upon program startup, the cin object of class istream is created (instantiated).
Input from the keyboard (or the standard input stream) is performed using the cin object, and the rightshift bitwise operator >> in combinations such as:
cin >> someVariable;Multiple values can be input by executing the following.
cin >> variable1 >> variable2 >> variable3 >> ...;Only one variable is allowed after each >>. The >> points in the direction of the data flow from cin (the standard input) and is referred to as the extraction operator.
cin provides support for all of the primitive data types.
cin skips whitespace (where whitespace is defined by a call to isspace() see ctype.h).
char c; cin >> c; //reads the first nonwhitespace character into ccin.width(int) can be used to restrict the number of characters read (useful when reading strings).
char a[16]; cin.width(sizeof(a)); cin >> a; //read at most 15 characters into a and add terminating nullThe input stream has a state associated with it. They are:
 good()  previous input operation worked
 eof()  previous input operation worked; next input operation will fail
 fail()  next operation will fail
 bad()  stream is corrupted
Applying an input operation to a string that is not in the good() state is a null operation.
The insertion operator is intended for formatted input; reading objects of an expected type and format. The get() and getline() functions offer alternative ways to get input. These functions treat whitespace characters exactly like other characters.
get() leaves the terminator on the input stream; whereas, getline() doesn't.
char a[32]; cin.getline(a, sizeof(a)); // reads at most 31 characters into array a // appending a null character to the end // // the standard input stream is read until // 31 characters read or a newline is encounteredignore() reads characters but it doesn't store them anywhere. By default, ignore() reads one character and the terminator is endoffile.
clear() can be used to clear the input flags.
int i; cout << "Enter an integer: " << flush; cin >> i; if (cin.fail()) { cin.clear(); cout << "Enter an integer: " << flush; cin >> i; if (cin.fail()) cerr << "forget it..."; }
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
Escape sequences are used for the following reasons.
 you cannot otherwise write (such as
\n
) that can be difficult to read properly (such as
\t
) that might change value in different target character sets (such as
\a
) that must not change in value among different target environments (such as
\0
)C and C++
There are two types of numeric escape sequences: octal and hexadecimal.
\a Alert \b Backspace \f Formfeed \n Newline \r Carriage return \t Horizontal Tab \v Vertical Tab \" Double quote \' Single quote \\ Backslash \? Question Mark \0 Null Character
 octal: \o \oo \ooo, where 'o' is an octal digit
 hexadecimal: \xh \xhh \xhhh ... where 'h' is a hexidecimal digit
Java Escape Sequences
Java will not compile a source file if it contains invalid escape sequences. [ Example]
\b Backspace \f Formfeed \n Newline \r Carriage return \t Horizontal Tab \" Double quote \' Single quote \\ Backslash \uhhhh Unicode; 4 hexadecimal digits \ooo C style; 3 octal digits All of the Java escape sequences  except for Unicode
\u
 can only be used within string and character literals.String doubleQuote = "\""; char singleQuote = '\''; char bestGrade = '\u0041'; // set to 'A' char worstGrade = '\106'; // set to 'F'
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
We are interested in the following number systems.
 binary (base 2)
 octal (base 8)
 decimal (base 10)
 hexadecimal (base 16)
We use the decimal number system day in and day out; however, computers use the binary system.
Every number system has a set of valid digits.
 binary: 0  1
 octal: 0  7
 decimal: 0  9
 hexadecimal: 0  9 and a  f
(or A  F)Because there are not enough digits to represent a 16 hexadecimal digits, letters are used to represent digits 10  15 as follows:
 A (or a) is 10
 B (or b) is 11
 C (or c) is 12
 D (or d) is 13
 E (or e) is 14
 F (or f) is 15
Each number system uses positional notation. In the decimal number system, the rightmost digit is 10 raised to the power of 0, the 2nd rightmost digit is 10 raised to the power of 1, the 3rd rightmost digit is 10 raised to the power of 2 and so on. In the octal number system, the rightmost digit is 8 raised to the power of 0, the 2nd rightmost digit is 8 raised to power of 2, the 3rd rightmost digit is 8 raised to the power of 3 and so on. Extend this to hexadecimal (i.e. 16) and binary (i.e. 2).
Decimal number 1349 is equal to the following expression: (1 * 1000) + (3 * 100) + (4 * 10) + (9 * 1) Octal number 347 is equal to the following expression: (3 * 64) + (4 * 8) + (7 * 1)The STDC Library contains the function
pow()
that can be used to compute the value of a number raised to a power.pow(2, 0) = 1 /* 2 raised to the power of 0 */ pow(2, 1) = 2 /* 2 raised to the power of 1 */ pow(2, 2) = 4 /* 2 raised to the power of 2 */ pow(2, 3) = 8 /* 2 raised to the power of 3 */ pow(2, 4) = 16 etc... pow(8, 0) = 1 /* 8 raised to the power of 0 */ pow(8, 1) = 8 /* 8 raised to the power of 1 */ pow(8, 2) = 64 /* 8 raised to the power of 2 */ pow(8, 3) = 512 etc... pow(8, 4) = 4096 pow(10, 0) = 1 /* 10 raised to the power of 0 */ pow(10, 1) = 10 /* 10 raised to the power of 1 */ pow(10, 2) = 100 etc... pow(10, 3) = 1000 pow(10, 4) = 10000 pow(16, 0) = 1 /* 16 raised to the power of 0 */ pow(16, 1) = 16 etc... pow(16, 2) = 256 pow(16, 3) = 4096 pow(16, 4) = 65536Exercise: convert decimal 150 to octal.
150 / 8 = 18 remainder 6 18 / 8 = 2 remainder 2 2 / 8 = 0 remainder 2 decimal 150 is equal to octal 226Exercise: convert decimal 150 to hexadecimal.
150 / 16 = 9 remainder 6 9 / 16 = 0 remainder 9 decimal 150 is equal to hexadecimal 96Exercise: convert decimal 150 to binary.
150 / 2 = 75 remainder 0 75 / 2 = 37 remainder 1 37 / 2 = 18 remainder 1 18 / 2 = 9 remainder 0 9 / 2 = 4 remainder 1 4 / 2 = 2 remainder 0 2 / 2 = 1 remainder 0 1 / 2 = 0 remainder 1 decimal 150 is equal to binary 10010110 decimal positional values 100 10 1 =========== 1 5 0 (100 + 50 + 0 = 150) binary positional values 128 64 32 16 8 4 2 1 =========================== 1 0 0 1 0 1 1 0 (128 + 16 + 4 + 2 = 150)Binary numbers can be converted to octal and hexadecimal by grouping bits, righttoleft, in sets of three and four, respectively.
Decimal 150 in binary is 10010110 (10) (010) (110) 2 2 6 octal (64 * 2) + (8 * 2) + (1 * 6) octal positional values 64 8 1 ======== 2 2 6 (1001) (0110) 9 6 hexadecimal (16 * 9) * (6 * 1) hexadecimal positional values 16 1 ===== 9 6Some Number System Quotes
"Counting in binary is just like counting in decimal if you are all thumbs."  Glaser and Way "Counting in octal is just like counting in decimal, if you don't use your thumbs."  Tom Lehrer "There are only 10 types of people in the world: Those who understand binary and those who don't."  seen on ThinkGeek.com tshirtSpeaking of ThinkGeek.com tshirts... Binary Finger and Binary Dad
Binary BARS
Note: BARS are Basic Arithmetic Road Signs.
 US Hwy2 and ME Hwy100 in Bangor, Maine [15 August 2007]
 1920s Holzwarth Dude Ranch in Colorado [30 July 2007]
External Hyperlinks
 KhanAcademy.org::Binary Numbers
 CS.VT.edu:: Online CS Modules: Number Systems
 Wikipedia.org::Numeral system
 Turbulence.org::The Secret Lives of Numbers
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
All arithmetic operators are binary operators (i.e. they take two operands).
* multiply / divide % modulus (remainder) + addition  substractionImportant points.
Divide by 0 is not defined and it causes your program to abort (e.g.
10 / 0
).Dividing one integer by another (integer division) results in truncation (i.e. the fractional part, if any, is lost)
example:8 / 3
equals2
.The modulus operator
%
results in the remainder when one integer is divided by another
example:8 % 3
equals2
(note: both operands must be integral types).
* / %
have higher precedence than+ 
and associativity is lefttoright .Precedence and associativity can be altered by using parenthesis
a + b * c binds as a + (b * c) (a + b) * c ()s used to alter binding
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
Whenever you have an EXPR that contains multiple operators, then you must be aware of operator precedence and associativity.
Precedence and associativity are used to "bind" operators with operands.
Every C/C++ book that I have reviewed contains a precedence and associativity chart. Here is a chart that displays the precedence and associativity of some of the operators we learn first.
Unary +
and
have higher precedence than the binary forms.Operators Associativity () +  (type) sizeof
right to left * / %
left to right + 
left to right =
right to left Precedence determines the order in which operands are bound to operators. Operators on the same line have the same precedence; rows are in order of decreasing precedence.
Examples:
If an EXPR contains two operators of equal precedence, then associativity is used to bind operators and operands.
 The
sizeof
operator is high precedence, whereas the assignment operator=
has low precedence. The multiple operator
*
is a medium precedence operator that has slightly higher precedence that the addition operator+
.
An example using the EXPR:
a + b  c
The + and  operators have equal precedence; therefore, associativity is used. They associate lefttoright and we end up with with the binding (a + b)  cPrecedence and associativity can be altered by using parenthesis.
Example expression: a * b / c * and / have equal precedence and they associate lefttoright; therefore, we get the following binding: (a * b) / c If we want the operand b to be attached to the operand c, then we would parenthesis and code the EXPR: a * (b / c).Use parenthesis if you are ever in doubt about the precedence and associativity rules. [Note: it is possible to overuse ()'s.]
GDT::Resource::C++:: Precedence chart that includes all operators.
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
Relational operators are used to compare the value of two expressions (EXPRs).
== expr1 == expr2 equals != expr1 != expr2 not equals > expr1 > expr2 greater than < expr1 < expr2 less than >= expr1 >= expr2 greater than or equal to <= expr1 <= expr2 less than or equal to The operators that are made up of two characters cannot have any whitespace between. For example:
= =
would be treated as two separate assignment operators and would result in a compiletime error.==
is used to test two operands for equality.It is easy to sometimes use the equality operator in lieu of the assignment operator and vice versa. You must remember the following.
== is the relational equality operator; it compares two operands for equality and evaluates to either 0 (false) or 1 (true) = is the assignment operator; it copies the value of the operand on the righthand side to the operand on the lefthand side; the EXPR evaluates to the value that was copied (i.e. assigned)Examples.
int thisCourse = 100; /* 100 assigned to thisCourse */ int nextCourse = 205; /* 205 assigned to nextCourse */ thisCourse == nextCourse /* evaluates to 0 (false) */ thisCourse != nextCourse /* evaluates to 1 (true) */ thisCourse > nextCourse /* evaluates to 0 */ thisCourse < nextCourse /* evaluates to 1 */ thisCourse >= nextCourse /* evaluates to 0 */ thisCourse <= nextCourse /* evaluates to 1 */GDT::C++::Code:: RelationalOps.cpp
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
if
Statement and else
ClauseThe
if
is a selection control statement. It is a keyword of the language. It has the following syntax.if (EXPR) statement'; statement''; If EXPR evaluates to true (i.e. not zero), then statement' is executed followed by statement''; otherwise, statement' is skipped and the flow control of the program jumps to statement''. if (netWorth > 1000000) cout << "you are rich (at least money wise)"; netWorth = netWorth * 2; //let us double our net worthTypically, there is no semicolon after the
if
. If there is, then the body of theif
is simply aNULL
(empty) statement. In many cases, this is a defect with your program (i.e. it is done by accident, not design).if (netWorth < 0) ; //do nothing...If more than one statement needs to be executed when an
if
EXPR is true, then a compound statement. should be used. A compound statement is a collection of zero or more statements enclosed in braces{}
.Compound statements are terminated by the closing brace
}
 not a semicolon.if (EXPR) { statement'; statement''; } //note that there is no semicolon statement'''; If EXPR evaluates to true, then both statement' and statement'' are executed followed by statement'''; otherwise, statement' and statement'' are skipped and the flow control of the program jumps to statement'''. isSuperStar = false; bonus = 0; ... if (battingAvg > 300) { isSuperStar = true; bonus = 10000; } number = 55;Every
if
statement can have a correspondingelse
clause which is executed whenever theif
is false (i.e. 0). Syntax.if (EXPR) statement'; else statement''; statement'''; If EXPR is true, then statement' is executed, the else clause is skipped and the flow control of the program jumps to statement'''; otherwise, statement' is skipped, statement'' is executed and the flow control of the program jumps to statement'''. if (netWorth > 1000000) cout << "you are rich (with respect to money)"; else cout << "you are rich in other ways";An
else
clause cannot be used without a correspondingif
statement. Example.int i = 10; ... else //not allowed  there is no if statement cout << "this is not legal\n";The body of an
if
construct can be any type of statement. Examples.if (EXPR) EXPR; //the body is an expression statement if (EXPR) return EXIT_SUCCESS; //body is a return statement if (EXPR) ; //body is a null statement if (EXPR) { } //body is an empty compound statement if (EXPR) if (EXPR) //body is another if statementAn
if
statement containing anotherif
is referred to as a nested if. There is no limit to the amount of nesting that can occur. Examples.if (EXPR) if (EXPR') statement'; statement''; If EXPR is true, then EXPR' is evaluated; otherwise, flow control jumps to statement''. If EXPR' is evaluated and it evaluates to true, then statement' is executed; otherwise, flow control jumps to statement''. if (age >= 100) if (gender == 'M') cout << "old man look at my life"; if (age >= 100) if (gender == 'M') if (iq > 120) cout << "smart old man look at my life"; cout << endl;When using
if
statements, it is a good programming practice to use indentation to aid readability. The body of anif
statement should be indented three or four spaces.In all cases, each
if
can have a correspondingelse
clause.if (EXPR) if (EXPR') statement'; else statement''; statement'''; The topmost if does not have an else clause, whereas the innermost if does. If EXPR evaluates to false, then flow control jumps to statement'''; otherwise, EXPR' is evaluated. If it evaluates to true, then statement' is executed; otherwise, statement' is skipped and statement'' is evaluated. Regardless of which statement is executed, flow control jumps to statement'''.Caution is required to make sure that
else
clauses match up to the correctif
construct.if (age > 100) if (gender == 'M') cout << "you are an old man"; else cout << "you are a young person"; If age is greater than 100, then if (gender == 'M') will be executed. If the gender is 'M', then the correct statement will print, but if the gender is not 'M', then the "you are a young person" message will print. To correct this problem, a compound statement is needed to "tie" the else clause with the outermost if statement. if (age > 100) { if (gender == 'M') cout << "you are an old man"; } else cout << "you are a young person"; Now if age > 100, then the body of the if is executed; otherwise, flow control jumps to the else clause.
{TopOfPage} {Tutorial (text)} {C++ Programming (video)} {C at MIT (course)} {online IDEs: CodingGround  CPP.sh  jdoodle} {GDT::C/C++ Resource}
Home  Previous  Next 
