C++ Exam 1 Study Guide
Constants
A variable can be declared to be constant. This means it cannot change once it's declared and initialized Use the keyword const MUST declare and initialize on the same line Ex. const int SIZE = 10; const double PI = 3.1415;
Cascading Output
Cascading is placing another operator after an output item to insert a new output item. adding multiple outputs in a cout cout <<''Average = " <<avg <<'\n'; cout <<var1 <<'\t' <<var2 <<'\t' <<var3;
Typical Code Elements
Comments - Ignored by the Compiler Directives - For preprocessing Literals - Hardcoded values. Eg: 10 Keywords - Words with special meaning to the compiler. Eg: int Identifiers - Names for variables, functions, etc. Operators - Symbols that perform certain operations. Eg: +
Statement Types (DEC)
Declaration statement Execution statement Compound statement - any set of statements enclosed in set braces { } (often called a block)
Literal types
floating point literal - an actual decimal number written in code (4.5, -12.9, 5.0) These are interpreted as type double by standard C++ compilers Can also be written in exponential (scientific) notation: (3.12e5, 1.23e-10) character literal - a character in single quotes: ('F', 'a', '\n') string literal - a string in double quotes: ("Hello", "Bye", "Wow!\n") boolean literals - true or false
Arity:
how many operands an operator takes: Unary: Negative sign (- just attaches to the negative sign) binary: most common (X+y, X*Y, out, cin, equal sign) ternary: Ex. conditional operator
if-else (Selection statement)
if (expression) { statement(s) } else { statement(s) }
if-else (Selection statement) example
if (x == 0) cout <<"Nothing here"; else cout <<"There is a value"; This example contains an else clause. The bodies are single statements.
Input Streams
int numStudents; cin >>numStudents; // read an integer double weight; cin >>weight; // read a double cin >>'\n'; // ILLEGAL. Right side must be a variable cin >>x + y; // ILLEGAL. x + y is a computation, not
Assignment Operator associates...
left to right R-value - any expression that evaluates to a single value (name comes from "right" side of assignment operator) L-value - A storage location! (not any old expression). A variable or a reference to a location. (name comes from "left" side of assignment operator Ex. x = 5; y = 10.3; z = x + y; // right side can be an expression a + 3 = b; // ILLEGAL! Left side must be a // storage location
cascading precedence associativity
linking of multiple operators, especially of related categories, together in a single statement: cascading arithmetic operators x = a + b + c - d + e; // cascading assignment operators x = y = z = 3; - rules of how operator cascade Ex. + operator goes left to right x = a + b * c; // b * c happens first, since * //has higher precedence than + rules specifying which operators are evaluated first when they have the same level of precedence. I Most (but not all) operators associate from left to right.
Statement:
smallest complete executable unit of a program
accumulation sentinel
specifying a # of values (entries, value, total, count) looping until you inout a specific value
to use streams we need to include
the iostream library into our programs. #include <iostream> using namespace std; The using statement tells the compiler that all uses of these names (cout, cin, etc) will come from the "standard" namespace.
Arithmetic Operators: Modulus
the remainder of the quotient Ex. int x = 19, y = 5 q = x / y; // q is 3 r = x % y; // r is 4
Some short-cut assignment operators (with arithmetic) v += e; means v -= e; means v *= e; means v /= e; means v %= e; means
v += e; means v = v + e; v -= e; means v = v - e; v *= e; means v = v * e; v /= e; means v = v / e; v %= e; means v = v % e;
to use these streams
we need to include the iostream library into our programs. #include <iostream> using namespace std;
Examples of Expressions
(x >0 && y >0 && z >0) // all three of (x, y, z) are positive (x <0 ||y <0 ||z <0) // at least one of the three variables is negative ( numStudents >= 20 && !(classAvg <70)) // there are at least 20 students and the class average is at least 70 ( numStudents >= 20 && classAvg >= 70) // means the same thing as the previous expression
Structure of a C++ Program
Sequence of statements, typically grouped into functions (function: a subprogram. a section of a program performing a specific task. Every function body is defined inside a block)
Flow Control Types
Sequential: Default mode. Statements are executed line by line. Selection: Used for decisions, branching - choosing between 2 or more alternative paths. - if - if else - switch - conditional statements Repetition: Used for looping - repeating a piece of code multiple times in a row. - while - do while - for Selection and repetition statements typically involve decision steps. These steps rely on conditions that are evaluated as true or false
Operators
Special built-in symbols that have functionality (meaning), and work on operands operand - an input to an operator
conditional operator
There is a special operator known as the conditional operator that can be used to create short expressions that work like if/else statements Ex. cout <<(x >y) ? "x is greater than y" : "x is less than or equal to y");
Increment and Decrement Operators
These are shortcut operators for adding or subtracting 1 from a variable. Shortcut for x=x+1 ++x; // pre-increment (returns reference to new x) x++; // post-increment (returns value of old x) Shortcut for x=x-1 --x; // pre-decrement x--; // post-decrement
Declare vs Initialize
To declare a variable is to tell the compiler it exists, and to reserve memory for it To initialize a variable is to load a value into it for the first time One common way to initialize variables is with an assignment statement. Examples: int numStudents; double weight; char letter; numStudents = 10; weight = 160.35; letter = 'A';
Identifier rules
User-defined identifiers can consist of letters, digits, and underscores Must start with a non-digit Reserved words (keywords) cannot be used as identifiers
\n \t \" \' \\
\n newline \t tab \" double quote \' single quote \\ backslash
Logical Operators
!x // the NOT operator (negation) //true if x is false x && y // the AND operator //true if both x and y are true x || y // the OR operator //true if either x or y or both are true
example of using a library
#include <iostream> (pre-processing)
Arithmetic has usual precedence
1. parentheses 2. Unary minus 3. *, /, and % 4. + and - 5. operators on same level associate left to right
The insertion operator in C++ The extraction operator in C++
<< (cout) >> (cin)
Symbolic Constants (an alternative)
A symbolic constant is created with a preprocessor directive,#define. (This directive is also used to create macros). I Examples: #define PI 3.14159 #define DOLLAR '$' #define MAXSTUDENTS 100 The preprocessor replaces all occurrences of the symbol in code with the value following it. (like find/replace in MS Word). This happens before the actual compilation stage begins
Identifiers
Identifiers are the names for things (variables, functions, etc) in the language. DECLARE BEFORE USE Ex. numStudents, firstName // good a, ns, fn // bad
primitive data type in C++
Integer (int) Character (char) or Wide Boolean (bool) Floating Point (float) Double Floating Point (double) Valueless or Void
Literals
Literals are also constants. They are literal values written in code. int x = 26; // integer value 26 int y = 032; // octal 32 = decimal value 26 int z = 0x1A; // hex 1A = decimal value 26
pre-increment post-increment
Pre-increment: incrementing is done before the value of x is used in the rest of the expression Post-increment: incrementing is done after the value of x is used in the rest of the expression
Relational Operators
Relational Operators are use for comparison. The comparison operators in C++ work much like the symbols we use in mathematics. Each of these operators returns a Boolean value: a true or a false. x == y // x is equal to y x != y // x is not equal to y x <y // x is less than y x <= y // x is less than or equal to y x >y // x is greater than y x >= y // x is greater than or equal to y
break and continue
break: This causes immediate exit from any loop (as well as from switch blocks). continue: When used in a loop, this statement causes the current loop iteration to end, but the loop then moves on to the next step. - In a while or do-while loop, the rest of the loop body is skipped, and execution moves on to the test condition. - In a for loop, the rest of the loop body is skipped, and execution moves on to the iterative statement.
Input / Output streams
cout - standard output stream - Of class type ostream (to be discussed later) - Usually defaults to the monitor cin - standard input stream - Of class type istream (to be discussed later) - Usually defaults to the keyboard cerr - standard error stream - Of class type ostream - Usually defaults to the monitor, but allows error messages to be directed elsewhere (like a log file) than normal output
A special "magic formula" for controlling how many decimal places are printed:
cout<<set.precision(4); needs #include <iomanip>