Variables and Decisions Flashcards
In a program, a (_____) is a named item, such as x or numPeople, used to hold a value.
variable
An (_______) assigns a variable with a value, such as x = 5. That assignment means x is assigned with 5, and x keeps that value during subsequent assignments, until x is assigned again.
assignment
In programming, = is an (______) of a left-side variable with a right-side value. = is NOT equality as in mathematics. Thus, x = 5 is read as “x is assigned with 5”, and not as “x equals 5”. When one sees x = 5, one might think of a value being put into a box.
assignment
What are the basic fundamental data types in C++?
Name Description Size* Range*
char Character or small integer. 1byte signed: -128 to 127
unsigned: 0 to 255
short int (short) Short Integer. 2bytes signed: -32768 to 32767 unsigned: 0 to 65535
int Integer. 4bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int (long) Long integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295
bool Boolean value. It can take one of two values: true or false. 1byte true or false
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t Wide character. 2 or 4 bytes 1 wide character
A(n) ________ represents a storage location in the computer’s memory.
Variable
Data items whose values do NOT change while the program is running are
literals
You must have a ________ for every variable you intend to use in a program
variable definition
What are the rules of a variable identifier
Neither spaces nor punctuation marks or symbols can be part of an identifier.
Only letters, digits and single underscore characters are valid.
In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case can they begin with a digit
Besides the decimal number system that is most common (base 10), two other number systems that can be used in C++ programs are
octal and hexadecimal
Which of the following lines must be included in a program that has string variables?
include
As you may see in the previous example, strings can be initialized with any valid string literal just like numerical type variables can be initialized to any valid numerical literal. Both initialization formats are valid with strings:
string mystring = "This is a string"; string mystring ("This is a string");
A programmer should choose a variable’s type based on the type of value held.
Integer variables are typically used for values that are counted, like 42 cars, 10 pizzas, or -95 days.
Floating-point variables are typically used for measurements, like 98.6 degrees, 0.00001 meters, or -55.667 degrees.
Floating-point variables are also used when dealing with fractions of countable items, such as the average number of cars per household.
Branch basics (If)
In a program, a branch is a sequence of statements only executed under a certain condition. Ex: A hotel may discount a price only for people over age 60. An if branch is a branch taken only IF an expression is true.
If-elseif-else branches
s. An if-else can be extended to an if-elseif-else structure. Each branch’s expression is checked in sequence; as soon as one branch’s expression is found to be true, that branch is taken. If no expression is found true, execution will reach the else branch, which then executes.
What is a flag?
Generally flag is a variable which signels that some event happened (flag raised) or not.
isalpha(c) true if alphabetic:
a-z or A-Z
isalpha(‘x’) // true
isalpha(‘6’) // false
isalpha(‘!’) // false
isdigit(c) true if digit: 0-9.
isdigit(‘x’) // false
isdigit(‘6’) // true
isspace(c) true if whitespace.
isspace(‘ ‘) // true
isspace(‘\n’) // true
isspace(‘x’) // false
toupper(c) Uppercase version
letter = toupper('a') // A letter = toupper('A') // A letter = toupper('3') // 3
tolower(c) Lowercase version
letter = tolower('A') // a letter = tolower('a') // a letter = tolower('3') // 3
Given string userString is “Run!”. Indicate char x’s value.
x = userString.at(0);
0 is the index of the string’s first character, which is R.
A character in a string can be assigned. If userString is “abcde”, then userString.at(3) =
‘X’ yields “abcXe”.
Determining the last character in a string is often useful. If a string’s length is known, the last character is at index length - 1.
Ex: “Hey” has length 3, with y at index 2. The function s1.size() returns s1’s length. Ex: If s1 is “Hey”, s1.size() returns 3.
A common task is to append (add to the end) a string to an existing string.
The function s1.append(s2) appends string s2 to string s1. Ex: If s1 is “Hey”, s1.append(“!!!”) makes s1 “Hey!!!”.
The size() and length() functions both return a string's length. Ex: For the string firstName = "Tosi", firstName.size() and firstName.length() both return
4.
A common error is to access an invalid string index, especially exactly one larger than the largest index. Given userText with size 8, the range of valid indices are 0 … 7; accessing with index 8
is an error
The .at(index) function generates an exception if the index is out of range for the string’s size. An exception is
a detected runtime error that commonly prints an error message and terminates the program.
C++ also supports C-style access of a string using brackets [] rather than .at(), as in: someString[0]. However, such C-style access does
not provide such error checking. Good practice is to use .at() rather than brackets for accessing a string’s characters, due to .at()’s error checking.
More string operations
find() find(item) returns index of first item occurrence, else returns string::npos (a constant defined in the string library). Item may be char, string variable, string literal (or char array).
substr() substr(index, length) returns substring starting at index and having length characters.
find(item, indx) starts at index indx.
// userText is “Help me!”
userText.find(‘p’) // Returns 3
userText.find(‘e’) // Returns 1 (first occurrence of e only)
userText.find(‘z’) // Returns string::npos
userText.find(“me”) // Returns 5
userText.find(‘e’, 2) // Returns 6 (starts at index 2)
// userText is “http://google.com”
userText.substr(0, 7) // Returns “http://”
userText.substr(13, 4) // Returns “.com”
userText.substr(userText.size() - 4, 4) // Last 4: “.com”
Table 3.16.2: String modify functions, invoked as myString.push_back(c). Each increases/decreases string’s length appropriately.
push_back() push_back(c) appends character c to the end of a string.
// userText is “Hello”
userText.push_back(‘?’); // Now “Hello?”
userText.size();
insert() insert(indx, subStr) Inserts string subStr starting at index indx.
// userText is “Goodbye”
userText.insert(0, “Well “);
// userText is “Goodbye”
userText.insert(4, “—”); // Now “Good—bye”
replace() replace(indx, num, subStr) replaces characters at indices indx to indx+num-1 with a copy of subStr.
// userText is “You have many gifts”
userText.replace(9, 4, “a plethora of”);
// Now “You have a plethora of gifts”
str1 + str2
If one of str1, str2 is a string, the other may be a character (or character array). // userText is "A B" myString = userText + " C D"; // myString is "A B C D" myString = myString + '!'; // myString now "A B C D!" myString = myString + userText;
// Returns 6
// Now “Well Goodbye”
Returns a new string that is a copy of str1 with str2 appended.
// myString now “A B C D!A B”
if else syntax
if (condition) { myVar = expr1; } else { myVar = expr2; }
If-else statements with the form shown below are so common that the language supports the shorthand notation shown.
if (condition) { myVar = expr1; } else { myVar = expr2; }
myVar = (condition) ? expr1: expr2
A conditional expression has the form condition ? exprWhenTrue : exprWhenFalse.
Floating-point numbers should be compared for “close enough” rather than exact equality. Ex: If (x - y) < 0.0001, x and y are deemed equal.
Because the difference may be negative, the absolute value is used: fabs(x - y) < 0.0001. fabs() is a function in the math library. The difference threshold indicating that floating-point numbers are equal is often called the epsilon. Epsilon’s value depends on the program’s expected values, but 0.0001 is common.
The std::abs() function is overloaded to support floating-point and integer types. However, good practice is to use the fabs() function to make the operation clear.