CMPS 147 - Computer Science I - Zybooks - Chapter Three: Branches (Conditional Statements) - Vocabulary

Ace your homework & exams now with Quizwiz!

Conditional Statements (Example)

#include <iostream> #include <string> using namespace std; int main() { bool isPen; bool isRed; //Question One: Is there a pen? cout << "Is there a pen? \n"; cin >> isPen; // Question Two: is the pen red? cout << "Is the pen red? \n"; cin >> isRed; // Output "Pen" if (isPen) is true and (isRed) is false. // Output "Red Pen" if (isPen) is true and (isRed) is true. // Otherwise, Print "Not a Pen". if (isPen && (!(isRed))) { cout << "Pen\n"; } else if (isPen && isRed) { cout << "Red Pen\n"; } else { cout << "Not a Pen\n"; } return 0; }

Multiple if statements example

#include <iostream> using namespace std; int main() { int userAge; cout << "Enter age: "; cin >> userAge; // Note that more than one "if" statement can execute. if (userAge < 16) { cout << "Enjoy your early years." << endl; } if (userAge > 15) { cout << "You are old enough to drive." << endl; } if (userAge > 17) { cout << "You are old enough to vote." << endl; } if (userAge > 24) { cout << "Most car rental companies will rent to you." << endl; } if (userAge > 34) { cout << "You can run for president." << endl; } return 0; }

Bitwise Operators (Logical Operators)

& and | represent bitwise operators, which perform AND or OR on corresponding individual bits of the operands.

Arithmetic operators

(+, -, *, /, %, //, ** or ^) The symbols +, -, *, /, %, and ^ used to denote addition, subtraction (or negation), multiplication, division, percentage, and exponentiation in an Excel formula.

append function (String)

(.append(string)) 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!!!"

Relational Operators

(<, >, <=, >=, ==, !=) Used to compare two values. Operators include =,<,>,<=,>=,<>

ASCII

(American Standard Code for Information Interchange; a code for representing English characters as numbers, with each letter assigned a number from 0 to 127) 1. a code that defines how keyboard characters are encoded into digital strings of ones and zeros 2. is a standard that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit code.

String operations

(Concatenation, Substring) You can perform different operations on string values such as concatenation, indexing, and slicing to get new string values!

insert() (Programming)

(Inserts a charterer at a certain point in a string) Inserts a specified instance of String at a specified index position in this instance.

replace() (Programming)

(The Replace() function returns a new string that has the specified string or character replaced in all occurrences.) Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Conditional Statement

(a statement that can be written in if-then form.) A programming statement that evaluates a true/false Boolean expression to determine the next steps in a program. Conditional statements are often written as "if-then" or "if-then-else" statements.

push_back()

(appends a character to the end of a string) A programmer can append a new element to the end of an existing vector using a vector's push_back() function.

Break Statement

(break;) A statement that terminates a loop or switch statement.

cctype library (#include <cctype>)

(provides access to several functions for working with characters.) A useful C library of character handling functions toupper(), tolower() Understand the boolean functions whose names start with is, for determining if a character fits in a certain given category.

Braces

({}) Sometimes redundantly called curly braces, represent a grouping, such as a grouping of statements.

String Comparison example (Extra)

- Can use relational operators directly to compare string objects: string str1 = "George", str2 = "Georgia"; if (str1 < str2) cout << str1 << " is less than " << str2; - Comparison is performed similar to strcmp function. Result is true or false

"C++ only focuses on"

... the symbols of Logical Operators (AND: &&, OR: ||, NOT: !).

Concatenation (String) example

// 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; // myString now "A B C D!A B"

find() function (example)

// 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)

String comparison (Relational) example

1) "Apples" is less than "Oranges" since 'A' is less than 'O' ("Apples" < "Oranges"). 2) "merry" is greater than "Merry" because the coded value for 'm' is greater than the coded value for 'M' ("merry" < "Merry"). 3) "banana" is less than "bananarama" because despite the existing characters being equal, the shorter string is less than.

Equality operators

1. ((equal) == and (not equal) !=) 2. (== and != operators) Operators == (is equal to) and != (is not equal to) are used to compare two values.

Character functions (Library) (#2)

3. isspace(c) -> true if whitespace. -> isspace(' ') // true, isspace('\n') // true, isspace('x') // false 4. toupper(c) -> Uppercase version -> letter = toupper('a') // A letter = toupper('A') // A letter = toupper('3') // 3 5. tolower(c) -> Lowercase version -> letter = tolower('A') // a letter = tolower('a') // a letter = tolower('3') // 3

Precedence Rules example (#2)

4. (< <= > >=) -> Relational operators -> x < 2 || x >= 10 is evaluated as (x < 2) || (x >= 10) because < and >= have precedence over ||. 5. (== !=) -> Equality and inequality operators -> x == 0 && x >= 10 is evaluated as (x == 0) && (x >= 10) because < and >= have precedence over &&. == and != have the same precedence and are evaluated left to right. 6. (&&) -> Logical AND -> x == 5 || y == 10 && z != 10 is evaluated as (x == 5) || ((y == 10) && (z != 10)) because && has precedence over ||. 7. (||) -> Logical OR -> || has the lowest precedence of the listed arithmetic, logical, and relational operators.

Boolean

A Data type that has just two values: true or false.

substring

A String method that returns a designated portion of a String. (a portion of a string)

If (branch)

A branch taken only if an expression is true. (A decision whose false branch has no statements)

Nested if-else statements

A branch's statements can include any valid statements, including another if-else statement. (When one if/else statement has inside either it's "true" section of code or it's "else/false" section of code another if/else statement that enables another condition to be checked to control execution.)

Nested if-else (Statements)

A branch's statements can include any valid statements, including another if-else statement. (if . . . if . . . else . . . else)

Changing a character (in a string)

A character in a string can be assigned. If userString is "abcde", then userString.at(3) = 'X' yields "abcXe".

Detecting ranges with branches (General)

A common programming task is to detect if a value lies within a certain range and then perform an action depending on where the value lies. Ex: If Timmy is less than 6, he can play pee-wee soccer. If Timmy is between 6 and 17, he can play junior league soccer, and if he's older than 17, he can play professional soccer.

Conditional Statement (#2)

A part of a program that most often has an if...then statement; for example, "If it is raining, then I'll bring an umbrella." In this example, the presence of rain is the condition that can change to affect the next action.

"multiple if statements"

A programmer can use ___________________________________________________ in sequence to detect multiple features with independent actions. Multiple sequential if statements looks similar to a multi-branch if-else statement but has a very different meaning. Each if-statement is independent, and thus more than one branch can execute, in contrast to the multi-branch if-else arrangement.

String

A sequence of characters; the primary data type for text.

Branch

A sequence of statements only executed under a certain condition. (a program path taken only if an expression's value is true.)

Switch (statement)

A switch statement can more clearly represent multi-branch behavior involving a variable being compared to constant values.

If-elseif-else (branch)

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. (Note: The else part is optional. If omitted, then if none of the previous expressions are true, no branch executes.) (can test many different values or combinations of values. While maintaining a default action if none are met.)

If-else (branch)

An if-else has two branches: The first branch is executed IF an expression is true, ELSE the other branch is executed. (The first branch is taken if an expression is true, else the other branch is taken.)

If-else (Statement)

An if-else statement executes one group of statements when an expression is true, and another group of statements when the expression is false.

Boolean Example (#2)

Balloon Example: #include <iostream> using namespace std; int main() { bool isRed; bool isBalloon; cin >> isRed; cin >> isBalloon; if (isBalloon && !(isRed) { cout << "Balloon\n"; } else if (isBalloon && isRed) { cout << "Red balloon\n"; } else { cout << "Not a balloon\n"; } return 0; }

Boolean (Data type)

Boolean refers to a quantity that has only two possible values, true or false. (Allows you to create variable that may hold one of two possible values.)

Bool

C++ has the built-in data type bool for representing Boolean quantities. (A variable whose value can be either true or false is of this data type.)

Character Operations

Character.isalpha() Character.isdigit() Character.isspace() Character.toupper() Character.tolower() "is" operations return TRUE or FALSE

String Comparison

Check to see if they have the same number of characters, and each corresponding character is identical. (The operators should not be used with strings; unexpected results will occur.)

Index (Coding)

Determining where to place the original record in the file and whether it needs to be cross-referenced in another section. A chart number is typically used for this.

Index (string)

Each string character has a position number called an index, starting with 0 (not 1).

Boolean Expression

Evaluates to either true or false; used in the conditional of an if-structure. (in programming, an expression that evaluates to True or False.)

inequality operator (!=)

Evaluates to true if the left and right sides are not equal, or different. Example: int x = 5 int y = 3 x != 5 -> false. y != 7 -> true since y is not equal to 7.

Character functions

Functions that accept character data as input and can return both character and numeric values. (Those functions can be accessed via #include <cctype>)

If (branch) example

Hotel Rate Example: Start -> hotelRate = 155 -> userAge = Get next input -> Branch: userAge > 65 -> (if true): hotelRate = hotelRate - 20 -> (if false): skip the branch and move to the next line of code. -> Put "Your rate: " to output -> Put hotelRate to output -> End.

If-else (Branch) example

If-else example: Max Start -> x = Get next input -> y = Get next input -> Branch: x > y -> (if true): max = x -> (Otherwise): max = y -> Put max to output -> End.

If-elseif-else (branch) example

If-elseif-else example: Anniversaries: Start -> numYears = Get next input -> if Branch: numYears equals 1 -> (if true): Put "Newlyweds" to output -> End. -> else-if Branch: numYears equals 25 -> Put "Silver" to output -> End. -> else-if Branch: numYears equals 50 -> Put "Golden" to output -> End. -> else Branch (if all the if-elseif statements aren't true) -> Put "Congrats" to output -> End.

cctype library

Including the cctype library via #include <cctype> provides access to several functions for working with characters. The first c indicates the library is originally from the C language.

Logical Operators (General) Example (#2)

Logical AND: a: - b: - a AND b: false * false = false false * true = false true * false = false true * true = true Logical OR: a: - b: - a OR b: false or false = false false or true = true true or false = true true or true = true (Note: it will only choose the first condition if both expressions are true.) Logical NOT: a: - NOT a: false = true true = false

Logical Operators (General) Example (#1)

Logical operator -> Description: 1) a AND b -> Logical AND: true when both of its operands are true. 2) a OR b -> Logical OR: true when at least one of its two operands are true. 3) NOT a -> Logical NOT: true when its one operand is false, and vice-versa.

Logical Operators (Symbols) Example (#1)

Logical operator -> Description: i. a && b -> Logical AND (&&): true when both of its operands are true. ii. a || b -> Logical OR (||): true when at least one of its two operands are true. iii. !a -> Logical NOT (!): true when its one operand is false, and vice-versa.

"AND, OR, NOT"

Logical operators include _____________, _________, and _____________. Programming languages typically use various symbols for those operators, but below the words _____________, _________, and _____________ are used for introductory purposes.

Basic ranges with gaps

Oftentimes, ranges contain gaps. Ex: Movie theaters often give ticket discounts to children (anyone 12 and under) and seniors (anyone 65 and older). The gap is the group of people aged 13 to 64. An if-else statement can be used to detect such ranges with gaps.

Equality and inequality operators

Operator --> Description --> Example (assume x is 3): 1. == -> a == b means a is equal to b -> x == 3 is true and x == 4 is false. 2. != -> a != b means a is not equal to b -> x != 3 is false and x != 4 is true.

Precedence Rules example (#1)

Operator/Convention -> Description -> Explanation: 1. ( ) -> Items within parentheses are evaluated first -> In (a * (b + c)) - d, the + is evaluated first, then *, then -. 2. ! -> !(logical NOT) is next -> ! x || y is evaluated as (!x) || y. 3. (* / % + -) -> Arithmetic operators (using their precedence rules) -> z - 45 * y < 53 evaluates * first, then -, then <.

Relational Operators example (#1)

Relational operators -> Description -> Example (assume x is 3): 1. "<" -> a < b means a is less than b -> x < 4 is true and x < 3 is false. 2. ">" -> a > b means a is greater than b -> x > 2 is true and x > 3 is false. 3. "<=" -> a <= b means a is less than or equal to b -> x <= 4 is true, x <= 3 is true, and x <= 2 is false. 4. ">=" -> a >= b means a is greater than or equal to b -> x >= 2 is true, x >= 3 is true, and x >= 4 is false.

Logical Operators (Symbols)

Special symbols are used to represent the AND, OR, and NOT logical operators. Logical operators are commonly used in expressions of if-else statements. For example: && -> Logical AND Operator. || -> Logical OR Operator. ! -> Logical NOT Operator.

index (Example) (#1)

String -> Index a. "Mary" -> 0 1 2 3 b. "Opening Season" -> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 c. "Christmas Day" -> 0 1 2 3 4 5 6 7 8 9 10 11 12

index (Example) (#2)

String indices: 1. For string "Light", what is L's index? -> Answer: 0 2. For string "Light", what is t's index? -> Answer: 4 3. For string "You wish!", which character is at index 4? -> Answer: w 4. For string "You wish!", which character is at index 9? -> Answer: No such character (because even though the string has 9 characters, the last character '!' is at index 8. No 9th index exists in that string.)

String comparison (Relational)

Strings are sometimes compared relationally (less than, greater than), as when sorting words alphabetically. A comparison begins at index 0 and compares each character until the evaluation results in false, or the end of a string is reached. 'A' is 65, 'B' is 66, etc., while 'a' is 97, 'b' is 98, etc. So "Apples" is less than "apples" because 65 is less than 97.

Boolean Example (#1)

Teenager Example: #include <iostream> using namespace std; int main() { bool isTeenager; int kidAge; cin >> kidAge; //if the kid's age is 13 to 19, assign the boolean variable isTeenage with true. if(kidAge >= 13 && kidAge < 20){ isTeenager = true; } if (isTeenager) { cout << "Teen" << endl; } else { cout << "Not teen" << endl; } return 0; }

"exception"

The .at(index) function generates an ___________________ if the index is out of range for the string's size. An ___________________ is a detected runtime error that commonly prints an error message and terminates the program.

"string library"

The _____________ ________________ provides numerous useful functions, including functions for finding a character or string within a string, or getting a substring of a string.

size() function

The function s1.size() returns s1's length. Ex: If s1 is "Hey", s1.size() returns 3.

at() (accessing string Characters)

The notation someString.at(x) accesses the character at index x of a string. Example: string userString = "Run!"; char x; x = userString.at(0); -> R x = userString.at(3); -> ! x = userString.at(4); -> error (since index 4 doesn't exist in the string)

precedence rules

The order in which operators are evaluated in an expression.

"case, default case"

The program executes the first _____________ whose constant expression matches the value of the switch expression, executes that case's statements, and then jumps to the end. If no case matches, then the __________________ _____________ statements are executed.

order of evaluation

The sequence used to calculate the value of a formula is called the ____.

Detecting ranges with branches (Multi-Branch)

The sequential nature of multi-branch if-else statements is useful to detect ranges of numbers. In the following example, the second branch expression is only reached if the first expression is false. So the second branch is taken if userAge < 16 is false (so 16 or greater) AND userAge is < 25, meaning userAge is between 16 - 24 (inclusive).

size() and length() (functions)

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.

"zero (0)"

The starting index in C++ is...

Combining / Replacing

The string library has more functions for modifying strings. The functions include push_back(), insert(), replace() and concatenation.

Switch Statements

The switch statement is called a multiple-selection statement because it selects among many different actions (or groups of actions). (A conditional control structure in programming that functions as a multi-step if else statement, where several cases are stated and examined during execution to seek a match, and then a command is executed when a match is found.)

Logical operator

Treats operands as being true or false, and evaluates to true or false. (One of the operators that combines boolean expressions: and, or, and not.)

String Comparison (Equality)

Two strings are commonly compared for equality. Equal strings have the same number of characters, and each corresponding character is identical. Example: "Apple" == "Apple" -> True "Apple" == "apple" -> False

If-else (Statement) example

What is the final value of numItems? a) bonusVal = 12; if (bonusVal == 12) { numItems = 100; } else { numItems = 200; } Answer: numItems = 100. b) bonusVal = 11; if (bonusVal == 12) { numItems = 100; } else { numItems = 200; } Answer: numItems = 200.

equality operator (==) example

What is the final value of numItems? bonusVal = 10; numItems = 1; if (bonusVal == 10) { numItems = numItems + 3; } Answer: numItems = 13.

exception

a detected runtime error that commonly prints an error message and terminates the program.

Relational Operator

checks how one operand's value relates to another, like being greater than or less than.

Multiple if statements

each if statement is independent, so more than one branch can execute. __________________________________________________ can be combined to evaluate complex decisions.

equality operator (==)

evaluates to true if the left side and right side are equal. Example: int numCars = 10 int numBuses = 15 numCars == 10 -> true since the number of cars is equal to 10. numBuses == 20 -> false b/c the numBuses is not equal to 20.

If (Statement)

executes a group of statements if an expression is true. (A statement that executes one set of instructions if a specified condition is true and takes no action if the condition is not true.)

find() function

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). find(item, indx) starts at index indx.

Character functions (Library) (#1)

function -> description -> example: 1. isalpha(c) -> true if alphabetic: a-z or A-Z -> isalpha('x') // true, isalpha('6') // false, isalpha('!') // false 2. isdigit(c) -> true if digit: 0-9. -> isdigit('x') // false, isdigit('6') // true

insert() function

insert(indx, subStr) Inserts string subStr starting at index indx. Example: // userText is "Goodbye" userText.insert(0, "Well "); // Now "Well Goodbye" // userText is "Goodbye" userText.insert(4, "---"); // Now "Good---bye"

Logical Operators (Symbols) Example (#2)

int x = 5 int a = 8 string userAnswer = "yes" Logical AND (&&): (x >= 5) && (x < 10) -> True (a == 8) && (a == 100) -> False Logical OR (||): (x != 5) || (a != 8) -> False (userAnswer == "yes") || (userAnswer == "Yes") -> True Logical NOT (!): !((x < 5) && (x > 10)) -> True !(userAnswer == "yes") -> False

Relational Operators example (#2)

numDogs is greater than 10: numDogs > 10; numCars is greater than or equal to 5: numCars >= 5; centsLost is less than zero ((0) / is a negative number): centsLost < 0; userAge is less than or equal to 20: userAge <= 20;

Switch (statement) Example

numItems and userVal are int types. What is the final value of numItems for each userVal? switch (userVal) { case 1: numItems = 5; break; case 3: numItems = 12; break; case 4: numItems = 99; break; default: numItems = 55; break; } Example: if userVal = 1, numItems = 5. if userVal = 4, numItems = 99. if userVal = 10, numItems = 55.

push_back() function

push_back(c) Appends character c to the end of a string. Example: // userText is "Hello" userText.push_back('?'); // Now "Hello?" userText.size(); // Returns 6

replace() function

replace(indx, num, subStr) Replaces characters at indices indx to indx+num-1 with a copy of subStr. Example: // userText is "You have many gifts" userText.replace(9, 4, "a plethora of"); // Now "You have a plethora of gifts"

Concatenation (String)

str1 + str2 Returns a new string that is a copy of str1 with str2 appended. If one of str1, str2 is a string, the other may be a character (or character array).

Changing a character (in a string) example

string firstName = "Ron" string value = "Dark" What is firstName after: firstName.at(1) = '@'; Answer: "R@n" What is value after: value.at(0) = 'M'; Answer: "Mark"

Character functions example

string userStr = "Hey #1?" isalpha('7') -> false ('7' is not alphabetic (a-z or A-Z.)) isalpha(userStr.at(0)) -> true isspace(userStr.at(3)) -> true isdigit(userStr.at(6)) -> false (since that character is '?'.) toupper(userStr.at(1)) returns 'E'. -> true ('e' becomes 'E' in index 1 of userStr) tolower(userStr.at(2)) yields an error because 'y' is already lower case. -> false (No error, just returns 'y'.)

substr() function

substr(index, length) returns substring starting at index and having length characters. Example: // 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"

Switch (statement) Template

switch (a) { case 0: // Print "zero" break; case 1: // Print "one" break; case 2: // Print "two" break; default: // Print "unknown" break; } Example: if a = 1, Print "one". if a = 5, Print "unknown".

Bitwise Operators

used to manipulate individual bits of values. (&, |, ^, ~, <<, >>) (a set of operators that allow you to work with the actual bits within a number or character)


Related study sets

ESC270 Prevention/Care of Sports Injuries FINAL

View Set

History of Photography — All Readings

View Set

Chapter 6: Fats and other Lipids

View Set

Growth & Development (NB and Infant)

View Set