C++ Chapter 4

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

increment/decrement operators

The statement i = i + 1 is so common that the language supports the shorthand ++i, with ++ known as the increment operator. (Likewise, -- is the decrement operator, --i means i = i - 1). As such, a standard way to loop N times is shown below. int i; ... for (i = 0; i < N; ++i) { ... }

Choosing for and while loops

for---Number of iterations is computable before the loop, like iterating N times. while---Number of iterations is not (easily) computable before the loop, like iterating until the input is 'q'.

for loop index

index variable's scope covers the whole for loop up to the closing brace. it is true for the equivalent while loop as well. for (int i = 0; i < 5; ++i) { x = x + i; } while loop { int i = 0; while (i < 5) { x = x + i; ++i; } }

time(0)

this is one way to keep the seed unique. This outputs the number of seconds since Jan 1, 1970.

seed; srand()

this is the built in integer rand() uses. srand(x) can be used to change the seed and output a unique random number

break statement

causes an immediate exit of the loop. A break statement can sometimes yield a loop that is easier to understand. break;

continue statement

causes an immediate jump to the loop condition check. can improve the readability of the loop. continue;

sentinel value

A ______ _______ is a special value indicating the end of a list, such as a list of positive integers ending with 0, as in 10 1 6 3 0.

Iteration

Each time through a loop's statements

random conversations

#include <iostream> #include <string> using namespace std; /* Program that has a conversation with the user. Uses a if-else statements and a random number (sort of) to mix up the program's responses. */ int main() { int randNum0_3; // Random number 0 to 3 string userText; // User input cout << "Tell me something about yourself." << endl; cout << "You can type \"Goodbye\" at anytime to quit." << endl << endl << "> "; getline(cin, userText); while (userText != "Goodbye") { randNum0_3 = userText.size() % 4; // "Random" num. %4 ensures 0-3 if (randNum0_3 == 0) { cout << endl << "Please explain further." << endl << endl << "> "; } else if (randNum0_3 == 1) { cout << endl << "Why do you say: \"" << userText << "\"?" << endl << endl << "> "; } else if (randNum0_3 == 2) { cout << endl << "I don't think that's right." << endl << endl << "> "; } else if (randNum0_3 == 3) { cout << endl << "What else can you share?" << endl << endl << "> "; } else { cout << endl << "Uh-oh, something went wrong. Try again." << endl << endl; } getline(cin, userText); } cout << endl << "It was nice talking with you. Goodbye." << endl; return 0; }

finding the max

#include <iostream> using namespace std; // Outputs max of list of integers // First value indicates list size // Ex: 4 -1 9 0 3 yields 9 int main() { int maxSoFar; int currValue; int numValues; int i; cin >> numValues; for (i = 0; i < numValues; ++i) { cin >> currValue; if (i == 0) { // First iteration maxSoFar = currValue; } else if (currValue > maxSoFar) { maxSoFar = currValue; } } if (numValues > 0) { cout << "Max: " << maxSoFar << endl; } return 0; }

saving with interest

#include <iostream> using namespace std; int main() { double initialSavings; // User-entered initial savings double interestRate; // Interest rate double currSavings; // Current savings with interest int i; // Loop variable cout << "Enter initial savings: "; cin >> initialSavings; cout << "Enter interest rate: "; cin >> interestRate; cout << endl << "Annual savings for 10 years: " << endl; currSavings = initialSavings; for (i = 0; i < 10; ++i) { cout << "$" << currSavings << endl; currSavings = currSavings + (currSavings * interestRate); } return 0; }

for loop index common error

A common error is to declare a variable inside a loop whose value should persist across iterations. Below, the programmer expects the output to be 0, 1 (0+1), 3 (0+1+2), 6 (0+1+2+3), and 10 (0+1+2+3+4), but instead the output is just 0, 1, 2, 3, 4. #include <iostream> using namespace std; int main() { int i = 0; while (i < 5) { int tmpSum = 0; tmpSum = tmpSum + i; // Logic error: Sum is always just i cout << "tmpSum: " << tmpSum << endl; i = i + 1; } return 0; }

Loop common errors

A common error is to use the opposite loop expression than desired, like using x == 0 rather than x != 0. Programmers should remember that the expression describes when the loop should iterate, not when the loop should terminate. An infinite loop is a loop that never stops iterating. A common error is to accidentally create an infinite loop, often by forgetting to update a variable in the body, or by creating a loop expression whose evaluation to false isn't always reachable. Another common error is to use the assignment operator = rather than the equality operator == in a loop expression, usually causing an unintended infinite loop.

Specific Ranges

Commonly, a programmer wants a specific range that starts with some value x that isn't 0, like 10 to 15, or -20 to 20. The programmer should first determine the number of values in the range, generate a random integer with that number of possible values, and then add x to adjust the range to start with x.

loop good practice

For the above right, good practice is to include greater than or less than along with equality in a loop expression whenever possible, such as userVal >= 0 rather than userVal != 0. Note that the earlier ancestors program used >=, not just >. A program with an infinite loop may print excessively, or just seem to stall. On some systems, the user can halt execution by pressing Control-C on the command prompt, or by selecting Stop (or Pause) from within an IDE.

Greatest Common Denominator

The following is an example of using a loop to compute a mathematical quantity. The program computes the greatest common divisor (GCD) among two user-entered integers numA and numB, using Euclid's algorithm: If numA > numB, set numA to numA - numB, else set numB to numB - numA. These steps are repeated until numA equals numB, at which point numA and numB each equal the GCD. #include <iostream> using namespace std; // Output GCD of user-input numA and numB int main() { int numA; // User input int numB; // User input cout << "Enter first positive integer: "; cin >> numA; cout << "Enter second positive integer: "; cin >> numB; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } cout << "GCD is: " << numA << endl; return 0; }

scope

a declered name is only valid within a region of code. For example, userNum declared in main() is only valid within main()

block

is a braced-enclosed {} sequence of statements such as found with an if-else, for loop, or while loop. A variable name's scope extends from the declaration to the closing brace }.

nested loop

is a loop that appears in the body of another loop. The nested loops are commonly referred to as the inner loop and outer loop.

for loop

is a loop with three parts at the top: a loop variable initialization, a loop expression, and a loop variable update. A for loop describes iterating a specific number of times more naturally than a while loop. A loop commonly must iterate a specific number of times, such as 10 times. for (initialExpression; conditionExpression; updateExpression) { // Loop body } // Statements after the loop

while loop

is a program construct that repeatedly executes a list of sub-statements (known as the loop body) while the loop's expression evaluates to true. while (expression) { // Loop expression // Loop body: Executes if expression evaluated to true // After body, execution jumps back to the "while" } // Statements that execute after the expression evaluates to false

Loop

is a program construct that repeatedly executes the loop's statements (known as the loop body) while the loop's expression is true; when false, execution proceeds past the loop. Each time through a loop's statements is called an iteration.

i++ common error

is to also have a ++i; statement in the loop body, causing the loop variable to be updated twice per iteration. // Loop variable updated twice per iteration for (i = 0; i < 5; ++i) { // Loop body ++i; // Oops }

i++ good practice

is to use a for loop's parts to count the necessary loop iterations, with nothing added or omitted. // initialExpression not related to counting iterations; move r = rand() before loop for (i = 0, r = rand(); i < 5; ++i) { // Loop body } // updateExpression not related to counting iterations; move r = r + 2 into loop body for (i = 0; i < 5; ++i, r = r + 2) { // Loop body }

do-while loop

loop construct that first executes the loop body's statements, then checks the loop condition. do { // Loop body } while (loopExpression); useful when the loop should iterate at least once

pseudo-random

rand() does choose random numbers, however, everytime the program is run the same "random" numbers appear. That's because the program keeps track of the "random" number that is output" To change the output so it is random seed() needs to be changed. seed is 1. srand() can change seed

Generating a random number; rand()

returns a random integer each time the function is called from 0 to RAND_MAX. #include <iostream> #include <cstdlib> using namespace std; int main() { cout << rand() << endl; cout << rand() << endl; cout << rand() << endl; cout << "(RAND_MAX: " << RAND_MAX << ")" << endl; return 0; } Generally, rand() % N yields N possible values, from 0 to N-1.


Ensembles d'études connexes

Delf ado B1 Dossier 10 La protection des animaux Η προστασία των ζώων

View Set

310 Elsevier Adaptive Quizzing Endocrine Alterations

View Set

GS BUSA 439 CH 8 Diversification and the Multibusiness Company

View Set

Aug. 21 Organization of Blood and Blood forming organs

View Set

Tax Chapter 8 Examples and Solutions

View Set

Halloween Traditions, Gruesome history and Culture Around the World

View Set