3.1 C++

¡Supera tus tareas y exámenes ahora con Quizwiz!

Function to randomize the results of rand(): srand()

it accepts an unsigned int argument, which acts as a seed value for the algorithm.

fixed manipulator

it forces cout to print the digits in fixed-point notation, or decimal.

cin.ignore Ex: int main() { char ch; int number; cout << "Enter a number: "; cin >> number; cin.ignore(); // Skip the newline character cout << "Enter a character: "; ch = cin.get(); cout << "Thank You!\n"; return 0;

it tells the cin object to skip one or more characters in the keyboard buffer. Result: Enter a number: 100 [Enter] Enter a character: Z [Enter] Thank You!

Pow

its purpose is to raise a number to a power. ex: area = pow(4.0, 2.0); area=16

showpoint manipulator

used if you want trailing zeroes Ex: double x = 123.4, y = 456.0; cout << setprecision(6) << showpoint << x << endl; cout << y << endl; Result: 123.400 456.000

More example of multiple assignment

x = x + 4; Adds 4 to x x = x − 3; Subtracts 3 from x x = x * 10; Multiplies x by 10 x = x / 2; Divides x by 2 x = x % 4 Makes x the remainder of x / 4

Rule 1

chars, shorts, and unsigned shorts are automatically promoted to int.

Function: sqrt Y = sqrt(x);

Returns the square root of the argument. The return type and argument are doubles.

Function: tan Y = tan (x);

Returns the tangent of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles.

Function: fmod y = fmod (x, z);

Returns, as a double, the remainder of the first argument divided by the second argument. Works like the modulus operator, but the arguments are doubles. (The modulus operator only works with integers.) Take care not to pass zero as the second argument. Doing so would cause division by zero.

chapter 3.8 concept

Special functions exist for working with characters and string objects.

Chapter 3.9 concept

The C++ runtime library provides several functions for performing complex mathematical operations.

Formula: y = (rand() % ( maxValue − minValue + 1)) + minValue ;

if you wish to limit the range of the random number, use the formula minValue is the lowest number in the range maxValue is the highest number in the range

More examples of the rules

int x, y = 4; float z = 2.7; x = y * z; In the expression y * z, y will be promoted to float and 10.8 will result from the multiplication. Since x is an integer, however, 10.8 will be truncated and 10 will be stored in x.

Hand Tracing

-a debugging process where you pretend that you are the computer executing a program. You step through each of the program's statements one by one.

-rand() will generate different sequences of random numbers/

-srand() will generate different result of rand()

Uses of Random numbers

1. Random numbers are useful in simulation programs 2. Formulas can be constructed in which a random number is used to determine various actions and events that take place in the program. 3. Random numbers are useful in statistical programs that must randomly select data for analysis. 4. Random numbers are commonly used in computer security to encrypt sensitive data

string concatenation Ex: string greeting1 = "Hello "; string greeting2; string name1 = "World"; string name2 = "People";

Because strings cannot be added, when this operator (+) is used with string operands it concatenates them, or joins them together Results: greeting2 = greeting1 + name1; // greeting2 now holds "Hello World" greeting1 = greeting1 + name2; // greeting1 now holds "Hello People" Another way to write this: greeting2 += name1

The left and right Manipulators Ex: double x = 146.789, y = 24.2, z = 1.783; cout << left << setw(10) << x << endl; cout << setw(10) << y << endl; cout << setw(10) << z << endl;

Causes subsequent output to be left justified. Causes subsequent output to be right justified. Result: 146.789 24.2 1.783

Function: exp y = exp (x);

Computes the exponential function of the argument, which is x. The return type and the argument are doubles.

Function: sin Y = sin (x);

Returns the sine of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles.

C++ string objects also have a number of member functions. For example, if you want to know the length of the string that is stored in a string object, you can call the object's length member function

Ex: string state = "Texas"; int size = state.length(); Result: 5

A stream manipulator, setw, can be used to establish print fields of a specified width.

Ex: value = 23; cout << setw(5) << value; Result: ( 23)

Inputting a character -The simplest way to read a single character is with cin and the >> operator, as illustrated

Ex: int main() { char ch; cout << "Type a character and press Enter: "; cin >> ch; cout << "You entered " << ch << endl; Result: Type a character and press Enter: A [Enter] You entered A

A type cast expression lets you manually promote or demote a value

Ex: static_cast< DataType >( Value ) Ex 1: double number = 3.7; int val; val = static_cast<int>(number); Even though number was a double, it was changed to int because of type cast expression

setprecision Manipulator

Floating-point values may be rounded to a number of significant digits, or precision, which is the total number of digits that appear before and after the decimal point

Chapter 3.10 concept:

Hand tracing a program

You might wonder what will happen if the number is too large to fit in the field, as in the following statement: value = 18397; cout << setw(2) << value;

In cases like this, cout will print the entire number. setw only specifies the minimum number of positions in the print field. Any number larger than the minimum will cause cout to override the setw value.

ex: cout << setprecision(2) << fixed; cout << "Day 1: " << setw(8) << day1 << endl; cout << "Day 2: " << setw(8) << day2 << endl; cout << "Day 3: " << setw(8) << day3 << endl; cout << "Total: " << setw(8) << total << endl;

Input: Result 1321.87 1321.87 1869.26 1869.26 1403.77 1403.77

Chapter 3.6 concept

Multiple assignment means to assign the same value to several variables with one statement.

combined assignment operators, aka. compound operators, and arithmetic assignment opperators

Operator Example usage Equivalent to += x += 5; x = x + 5; −= y −= 2; y = y − 2; *= z *= 10; z = z * 10; /= a /= b; a = a / b; %= c %= 3; c = c % 3;

Example: using both srand()/rand(), Time function/the formula // This program simulates rolling dice. #include <iostream> #include <cstdlib> // For rand and srand #include <ctime> // For the time function using namespace std; int main() { // Constants const int MIN_VALUE = 1; // Minimum die value const int MAX_VALUE = 6; // Maximum die value // Variables int die1; // To hold the value of die #1 int die2; // To hold the value of die #2 // Get the system time. unsigned seed = time(0); // Seed the random number generator. srand(seed); cout << "Rolling the dice...\n"; die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; cout << die1 << endl; cout << die2 << endl; return 0;

Program Output: Rolling the dice... 5 2 Program Output Rolling the dice... 4 6 Program Output Rolling the dice... 3 1

Function for Random number: rand()

Rand() requires cstdlib header file

Random Numbers

Random numbers are commonly used in games. For example, computer games that let the player roll dice use random numbers to represent the values of the dice.

setprecision Manipulator Ex: int main() { double quotient, number1 = 132.364, number2 = 26.91; quotient = number1 / number2; cout << quotient << endl; cout << setprecision(5) << quotient << endl; cout << setprecision(4) << quotient << endl; cout << setprecision(3) << quotient << endl; cout << setprecision(2) << quotient << endl; cout << setprecision(1) << quotient << endl;

Result: 4.91877 4.9188 4.919 4.92 4.9 5

Example of finding the hypotenuse of a triangle: // This program asks for the lengths of the two sides of a // right triangle. The length of the hypotenuse is then // calculated and displayed. #include <iostream> #include <iomanip> // For setprecision #include <cmath> // For the sqrt and pow functions using namespace std; int main() { double a, b, c; cout << "Enter the length of side a: "; cin >> a; cout << "Enter the length of side b: "; cin >> b; c = sqrt(pow(a, 2.0) + pow(b, 2.0)); cout << "The length of the hypotenuse is "; cout << setprecision(2) << c << endl; return 0;

Result: Enter the length of side a: 5.0 [Enter] Enter the length of side b: 12.0 [Enter] The length of the hypotenuse is 13 Explanation: pow function twice: once to calculate the square of a, and again to calculate the square of b. These two squares are then added together, and the sum is sent to the sqrt function.

Another example of setw Ex: int num1 = 2897, num2 = 5, num3 = 837, num4 = 34, num5 = 7, num6 = 1623, num7 = 390, num8 = 3456, num9 = 12; // Display the first row of numbers cout << setw(6) << num1 << setw(6) << num2 << setw(6) << num3 << endl; cout << setw(6) << num4 << setw(6) << num5 << setw(6) << num6 << endl; // Display the third row of numbers cout << setw(6) << num7 << setw(6) << num8 << setw(6) << num9 << endl;

Result: 2897 5 837 34 7 1623 390 3456 12

Ex: of all 3 functions // This program demonstrates random numbers. #include <iostream> #include <cstdlib> // For rand and srand #include <ctime> // For the time function using namespace std; int main() { // Get the system time. unsigned seed = time(0); // Seed the random number generator. srand(seed); (program continues) // Display three random numbers. cout << rand() << endl; cout << rand() << endl; cout << rand() << endl; return 0; }

Result: 23861 20884 21941

Example of Sqrt function: cout << "Enter a number: "; cin >> num; s = sqrt(num); cout << "The square root of " << num << " is " << s << endl;

Result: Enter a number: 25 The square root of 25 is 5

Getling funciton Ex: int main() { string name; string city; cout << "Please enter your name: "; getline(cin, name); cout << "Enter the city you live in: "; getline(cin, city); cout << "Hello, " << name << endl; cout << "You live in " << city << endl; return 0;

Result: Please enter your name: Kate Smith [Enter] Enter the city you live in: Raleigh [Enter] Hello, Kate Smith You live in Raleigh

When the fixed and setprecision manipulators are used together, the value specified by the setprecision manipulator will be the number of digits to appear after the decimal point, not the number of significant digits. Ex: double x = 123.4567; cout << setprecision(2) << fixed << x << endl;

Result: 123.46 This is because the fixed manipulator is used, the setprecision manipulator will cause the number to be displayed with two digits after the decimal point.

mathematical functions ex: Function: abs y = abs (x);

Returns the absolute value of the argument. The argument and the return value are integers.

Function: log10 Y = log10 (x);

Returns the base-10 logarithm of the argument. The return type and the argument are double s.

Function: cos y = cos (x);

Returns the cosine of the argument. The argument should be an angle expressed in radians. The return type and the argument are doubles.

Function: log y = log (x);

Returns the natural logarithm of the argument. The return type and the argument are doubles.

Chapter 3.7 concept

The cout object provides ways to format data as it is being displayed. This affects the way data appears on the screen.

Exception to rule 1

The only exception to this rule is when an unsigned short holds a value larger than can be held by an int. This can happen on systems where shorts are the same size as ints. In this case, the unsigned short is promoted to unsigned int.

cin.get ( ); Result: This program has paused. Press Enter to continue. [Enter] It has paused a second time. Please press Enter again. [Enter] It has paused a third time. Please press Enter again. [Enter] Thank you!

The program will not continue past the cin statement until some character other than the spacebar, tab key, or [Enter] key has been pressed. Ex:int main() { char ch; cout << "This program has paused. Press Enter to continue."; cin.get(ch); cout << "It has paused a second time. Please press Enter again."; ch = cin.get(); cout << "It has paused a third time. Please press Enter again."; cin.get(); cout << "Thank you!";

Ex of rand(): cout << rand() << endl; cout << rand() << endl; cout << rand() << endl;

The three numbers displayed will appear to be random, but each time the program runs, the same three values will be generated

formatting

The way a value is printed Ex: 720 720.0 720.00000000 7.2e+2 +720.0

#include <iomanip>

This is required to use for setw

Chapter 3.5 concept

Type casting allows you to perform manual data type conversion.

type coercion

When C++ is working with an operator, it strives to convert the operands to the same type known as

chapter 3.4 concept

When a variable is assigned a value that is too large or too small in range for that variable's data type, the variable overflows or underflows.

Rule 2

When an operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher-ranking value. Ex: In the following expression, assume that years is an int and interestRate is a float : years * interestRate Before the multiplication takes place, years will be promoted to a float.

Rule 3

When the final value of an expression is assigned to a variable, it will be converted to the data type of that variable. Ex: In the following statement, assume that area is a long int, while length and width are both ints: area = length * width; Since length and width are both ints, they will not be converted to any other data type. The result of the multiplication, however, will be converted to long so it can be stored in area.

NOTE:

With most compilers, trailing zeroes are displayed when the setprecision and fixed manipulators are used together.

When using pow, First, the program must include the cmath header file. Second, the arguments that you pass to the pow function should be doubles. Third, the variable used to store pow's return value should be defined as a double.

ex: #include <iostream> #include <cmath> // needed for pow function

More examples

number manipulator value 28.92786 setprecision(3) 28.9 21 setprecision(5) 21 109.5 setprecision(4) 109.5 34.28596 setprecision(2) 34

getline function

reads an entire line, including leading and embedded spaces, and stores it in a string object.

Mathematical functions

requires cmath as the header file

result *= a + 5; Figure this out!

result = result * (a + 5); because: you must realize the precedence of the combined assignment operators is lower than that of the regular math operators. More ex: examples Equivalent x += b + 5; x = x + (b + 5); y −= a * 2; y = y − (a * 2); z *= 10 − c; z = z * (10 − c); a /= b + c; a = a / (b + c); c %= d − 3; c = c % (d − 3);

Time function Requires the (ctime) as a headerfile, and you pass 0 as an arugment to the function

returns the number of seconds that have elapsed since midnight, January 1, 1970.

>>

stream extraction operator -It gets characters from the stream object on its left and stores them in the variable whose name appears on its right.

Multiple assignment example: If a program has several variables, such as a, b, c, and d, and each variable needs to be assigned a value, such as 12,

the following statement may be constructed: a = b = c = d = 12;


Conjuntos de estudio relacionados

CURRENT PSYCHOTHERAPIES all chs excluding 12,13

View Set

Chapter 18: regulation of gene expression

View Set

BIOL 171 Chapter 5 Mastering Biology

View Set

Chapter 11- Biotech | Part 2: Gene Cloning

View Set

Chapter 13: Managing Linux Processes

View Set

Architecture Semester 1 Exam Review

View Set