C++ Midterm 1 Notes
C++ Midterm 1 Notes
- allows input/output capabilities #include <string> - allows use of strings #include <cctype> - allows use of string functions using namespace std; - dont have to say std::cout, std::endl etc Arithmetic operators in order of precedence * / % (% = modulus operator isolates remainder, ex: 5%2 = 1 because 5/2 = 2 r 1) + A condition checks a Boolean expression (can evaluate to T or F). In a bool, false translates to 0 and true translates to 1. 0 translates to false and anything that isnt 0 translates to true. If/else
if (condition) statement if T; else statement if F;
A do while checks the condition after it runs. As such, a do while loop always runs at least once.
in the
Various preventions/pitfalls *division of two ints = an int (i.e. 14/5 = 2). So the expression double x = 3 + 1/5 3 *division of an int and a double or two doubles is a double. double x = 3 + 1.0/5 3.2 *cout.setf(ios::fixed); - use fixed notation *cout.precision(2); - have 2 digits to right of decimal *cin.ignore(10000, \n); state somewhere after using cin >> int and before using getline *if (18 <= age <=18) always evaluates to true because the computer will evaluate 18 <= age first. This gives a bool of 0 (false) or 1 (true) which either way <= 18. *if (age == 18 || 19 || 20) always evaluates to true because 19, 20 are always true *To end a program: return 1 or return 0 *n += 7 <-> n = n+7 and n++ <-> n += 1 <-> n = n+1 <-> ++n *Variables declared within brackets are only defined within those brackets! *ints, doubles, chars dont initialize automatically, but strings initialize to the empty string String and char functions. For a string s and char c: s[k] returns the character at the kth position of s, iff k is an int. s[k] is undefined if there is no character at that position (that is, k is not a valid position in the string). s.size() returns the size of the string. Note that s[0] and s[s.size() - 1] return a strings first and final characters, respectively. s.substr(a,b) where a and b are numbers: returns a substring starting with s[a] and ending with s[a+b]. Ex: If s is toenail, s.substr(4, s.size()-4) returns nail s += c - append the char c to the string s (c must be initialized) Char functions: isdigit(c), isupper(c), islower(c), isalpha(c) return T or F toupper(c), tolower(c) return a char Some chars to know: \n newline \t tab \ sing. quote \ double quote \\ backslash e.g cout << She said, \Dont do it!\; outputs She said, Dont do it! Else/if <-> switch statement: The following two things are equivalent, where week is a declared int. Note: switch statements can ONLY evaluate ints!
switch (week) { case 0: cout << "first lecture"; break; case 4: case 8: cout << "midterm"; break; case 10: cout << "final"; break; default: cout << "nothing"; }
if (week == 0) cout << "first lecture"; else if (week == 4 || week == 8) cout << "midterm"; else if (week == 10) cout << "final"; else cout << "nothing";