diff --git a/chap_advancedarith.tex b/chap_advancedarith.tex index 3e0d57b..ffd34ec 100644 --- a/chap_advancedarith.tex +++ b/chap_advancedarith.tex @@ -1,153 +1,127 @@ -Advanced arithmetic in C++ includes mathematics that can't be used in code -without the use of the \texttt{} library. -This is mathematics that goes above and beyond the primitive operations: -addition (\texttt{+}), subtraction (\texttt{-}), multiplication (\texttt{*}), -and division (\texttt{/}). +Advanced arithmetic in C++ includes mathematics that can't be used in code without the use of the \Code{} library. +This is mathematics that goes above and beyond the primitive operations: addition (\Code{+}), subtraction (\Code{-}), multiplication (\Code{*}), and division (\Code{/}). As we have seen before, some simple arithmetic might look like: -\begin{lstlisting} - int x; - x = 1; - x += 5; - return x; -\end{lstlisting} - The variable \texttt{x} is declared as an integer. +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int x; +x = 1; +x += 5; +\end{lstlisting}\end{minipage} + The variable \Code{x} is declared as an integer. The next line sets it to one. - The \texttt{+=} operator adds five to \texttt{x}, which makes \texttt{x} contain six. + The \Code{+=} operator adds five to \Code{x}, which makes \Code{x} contain six. -% -------------------------------------------------------------------------- -% TODO: NOTE: FIXME: Is the return statement in the above snippet necessary? -% -------------------------------------------------------------------------- - -Doing simple operations like these does not require any special libraries or -unusual commands. Any compiler can look at a \texttt{+}, \texttt{-}, -\texttt{*}, or \texttt{/} in a line of code and know exactly what the programmer -expects to happen. Some math requires a little extra help, though. In this case, -help is the \texttt{} library. +Doing simple operations like these does not require any special libraries or unusual commands. +Any compiler can look at a \Code{+}, \Code{-}, \Code{*}, or \Code{/} in a line of code and know exactly what the programmer +expects to happen. +Some math requires a little extra help, though. +In this case, help is the \Code{} library. -\texttt{} is a library that is needed for trigonometric, hyperbolic, -exponential, logarithmic, rounding, and absolute value functions. - The \texttt{} library is designed to make your life simple and to -make complicated mathematics easier in C++. - Using the \texttt{} library in code is as simple as including it at -the top of your source code file with the rest of your libraries. For example: - -\begin{lstlisting} +\Code{} is a library that is needed for trigonometric, hyperbolic, exponential, logarithmic, rounding, and absolute value functions. +The \Code{} library is designed to make your life simple and to make complicated mathematics easier in C++. +Using the \Code{} library in code is as simple as including it at the top of your source code file with the rest of your libraries. +For example: + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} #include #include -\end{lstlisting} +\end{lstlisting}\end{minipage} - After the inclusion of the \texttt{} library, you can use certain -mathematical functions in your code such as \texttt{pow(x, y)}, which raises -the parameter \texttt{x} to the power of parameter \texttt{y}, and -\texttt{sqrt(z)}, which returns the square root of \texttt{z}. - In your first few C++ programs you will probably not use the more advanced -mathematical functions included in the \texttt{} library, but for a full -list of the functions provided in \texttt{}, refer to ``Further Reading'' -at the end of this chapter. +After the inclusion of the \Code{} library, you can use certain mathematical functions in your code such as \Code{pow(x, y)}, which raises the parameter \Code{x} to the power of parameter \Code{y}, and \Code{sqrt(z)}, which returns the square root of \Code{z}. +In your first few C++ programs you will probably not use the more advanced mathematical functions included in the \Code{} library, but for a full list of the functions provided in \Code{}, refer to ``Further Reading'' at the end of this chapter. \LevelD{Examples} -\LevelE{\texttt{pow()}} - \texttt{pow} is the function called when you want to raise a value or -variable to a certain power. Take a look at the code below and -we'll break it down line by line. +\LevelE{\Code{pow()}} +\Code{pow} is the function called when you want to raise a value or variable to a certain power. +Take a look at the code below and we'll break it down line by line. -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int x, y; x = 4; y = pow(x + 1, 3) + 6; -\end{lstlisting} +\end{lstlisting}\end{minipage} - First, we are declaring two variables: \texttt{x} and \texttt{y}. - After that we set \texttt{x} to 4. + First, we are declaring two variables: \Code{x} and \Code{y}. + After that we set \Code{x} to 4. Now we get to a more interesting section of code. - We are asking the compiler to raise the value of \texttt{x} plus 1 to the power of 3, add 6, and then place the result in \texttt{y}. + We are asking the compiler to raise the value of \Code{x} plus 1 to the power of 3, add 6, and then place the result in \Code{y}. - To use the \texttt{pow} function, you must understand its syntax. + To use the \Code{pow} function, you must understand its syntax. Here is the breakdown: -\begin{lstlisting} - pow (starting value, power being raised) -\end{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +pow (starting value, power being raised) +\end{lstlisting}\end{minipage} - So for \texttt{pow (x + 1, 3) + 6}, we are raising the starting value -\texttt{x}~+~1 to the power of 3. - Before the power of 3 is applied, 1 is added to \texttt{x}. + So, for \Code{pow(x + 1, 3) + 6}, we are raising the starting value \Code{x}~+~1 to the power of 3. + Before the power of 3 is applied, 1 is added to \Code{x}. In this case it is the simple operation of 4+1, which yields 5. After we get 5, we raise it to the 3\textsuperscript{rd} power to get a value of 125. - After we reach the value of 125 we are finished with the \texttt{pow} -function and resume using normal operators when we add 6 to 125 resulting in -the final value of 131. + After we reach the value of 125 we are finished with the \Code{pow} function and resume using normal operators when we add 6 to 125 resulting in the final value of 131. - - Undoubtedly there are more complicated uses of the \texttt{pow} function, such as multiple uses of \texttt{pow} in the same line of code. - You might use multiple \texttt{pow} operations in code that calculates the length of one side of a triangle using the Pythagorean Theorem. + Undoubtedly there are more complicated uses of the \Code{pow} function, such as multiple uses of \Code{pow} in the same line of code. + You might use multiple \Code{pow} operations in code that calculates the length of one side of a triangle using the Pythagorean Theorem. Look at the following code and see if you can figure out what the output value would be: -\begin{lstlisting} - int x, y, z; - x = 3; - y = x + 1; - z = pow(x, 2) + pow(y, 2); - cout << z; -\end{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int x, y, z; +x = 3; +y = x + 1; +z = pow(x, 2) + pow(y, 2); +cout << z; +\end{lstlisting}\end{minipage} If you got 25, then you have the right answer! - A breakdown reveals that after initializing the variables \texttt{x} and \texttt{y} and setting their values (3 for \texttt{x} and \texttt{x}+1 for \texttt{y}), we raise each value to the power of 2. + After initializing the variables \Code{x} and \Code{y} and setting their values (3 for \Code{x} and \Code{x}+1 for \Code{y}), we raise each value to the power of 2. For visual reference, -\begin{lstlisting} - z = pow (3, 2) + pow (x+1, 2); -\end{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +z = pow (3, 2) + pow (x+1, 2); +\end{lstlisting}\end{minipage} results in -\begin{lstlisting} - z = 9 + 16; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +z = 9 + 16; +\end{lstlisting}\end{minipage} - \texttt{z}'s value is set to 25. - The \texttt{pow} function is simple to use and can make operations used in -a program simpler from both a computing and visual standpoint. + \Code{z}'s value is set to 25. + The \Code{pow} function is simple to use and can make the program simpler from a readability standpoint. -\LevelE{\texttt{sqrt()}} - Square roots are calculated using the \texttt{sqrt} function. +\LevelE{\Code{sqrt()}} + Square roots are calculated using the \Code{sqrt} function. Take a look at the example below to see how it is called in a program: -\begin{lstlisting} - int a, b; - a = 25; - b = sqrt(a); -\end{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a, b; +a = 25; +b = sqrt(a); +\end{lstlisting}\end{minipage} -%*************************** NOTE. The text below is misleading. -%sqrt() only ever returns a double; its prototype is double sqrt(double x); -%************************************************************************** - - \texttt{sqrt} is simpler than \texttt{pow} in that it only requires one parameter. - Since \texttt{sqrt} returns a \texttt{float} or \texttt{double}, you should usually assign the result to a \texttt{float} or \texttt{double} variable, but in this example, \texttt{sqrt} returns exactly 5, so it can be converted to an \texttt{int} without any issues. + \Code{sqrt} is simpler than \Code{pow} in that it only requires one parameter. + Since \Code{sqrt} returns a \Code{double}, you should usually assign the result to a \Code{double} variable, but in this example, \Code{sqrt} returns exactly 5, so it is implicitly converted to an \Code{int} without any issues. - There are cases where both \texttt{sqrt} and \texttt{pow} are used in the same formula, such as when calculating the distance between two points. + There are cases where both \Code{sqrt} and \Code{pow} are used in the same formula, such as when calculating the distance between two points. When writing such code, it is very important to keep track of the parentheses and to use correct syntax. One such syntax mistake is made when programmers think that C++ syntax is the same as algebraic syntax. This is \emph{not} the case in C++! -\begin{lstlisting} - int x = (5)(pow (3, 3)); -\end{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int x = (5)(pow(3, 3)); // Incorrect syntax! +\end{lstlisting}\end{minipage} -is NOT correct syntax. When the compiler sees this, it doesn't view it as multiplication, but instead as (according to a professional), ``function shenanigans.'' It is important to be explicit with mathematical symbols in C++. So instead of the incorrect code above, use: -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int x = 5 * (pow (3, 3)); -\end{lstlisting} +\end{lstlisting}\end{minipage} - Now, as an example, we will use code to compute the distance between two points on a plane. - Refer to the code and the diagrams if you do not understand or get lost. +As an example, we will use code to compute the distance between the two points $(4,4)$ and $(6, 10)$ on a plane. +Refer to the code and the diagrams if you do not understand or get lost. -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int x1, x2, y1, y2; float dist; x1 = 4; @@ -157,58 +131,61 @@ dist = sqrt(pow (x2 - x1, 2) + pow (y2 - y1, 2)); cout << dist; -\end{lstlisting} +\end{lstlisting}\end{minipage} - So your final answer after the calculation is executed is roughly 6.342555. + Your final answer after the calculation is executed is roughly $6.342555$. Without the help of the advanced arithmetic operations, getting to this result would be a difficult, long, drawn-out process. - \texttt{pow} and \texttt{sqrt} are handy little functions that make life easier, all with the help of the \texttt{} library. + \Code{pow} and \Code{sqrt} are handy functions that make life easier, all with the help of the \Code{} library. \LevelE{Modulo} -The modulo operator (the percent sign: \texttt{\%}) finds the remainder, or what was left over from division. -This program uses the modulo operator to find all prime numbers (all the numbers that never have a remainder of 0 when divided by every number except 1 and itself) that can be held by an \texttt{int}. +The modulo operator (the percent sign: \Code{\%}) finds the remainder, or what was left over from division. +This program uses the modulo operator to find all prime numbers (all the numbers that never have a remainder of 0 when divided by every number except 1 and itself) that can be held by an \Code{int}. -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} #include using namespace std; int main() { - int testprime = 0, divby = 0, remainder = 0; - bool isprime; - cout << "Prime Number Finder" << endl; - while(testprime < 2147483647)//The Maximum for int - { - isprime=true; - testprime++; - for(divby=2; divby < testprime; divby++) - { - remainder = testprime % divby; // store the remainder of the current number when divided by divby - if (remainder == 0)//If the number is not prime - { - isprime = false; - break; - } - } - if (isprime)//If it passes the test, it is prime. - { - cout << " " << testprime; // tell us what the prime number is. - } - } + int testprime = 0, divby = 0, remainder = 0; + bool isprime; + cout << "Prime Number Finder" << endl; + while(testprime < 2147483647) //The maximum for int + { + isprime = true; + testprime++; + for(divby = 2; divby < testprime; divby++) + { + // store the remainder of the current number when divided by divby + remainder = testprime % divby; + if (remainder == 0) //If the number is not prime + { + isprime = false; + break; + } + } + if (isprime) //If it passes the test, it is prime. + { + // tell us what the prime number is. + cout << " " << testprime; + } + } return 0; } -\end{lstlisting} +\end{lstlisting}\end{minipage} \LevelD{Review Questions} \begin{enumerate} -\item Which \texttt{\#include} library is needed to use advance arithmetic operators? +\item Which \Code{\#include} library is needed to use advance arithmetic operators? \item Write C++ code to calculate $2^9$. -\item Write a statement to set the value of a variable of type \texttt{double} to the square root of 10001. +\item Write a statement to set the value of a variable of type \Code{double} to the square root of 10001. \end{enumerate} + \LevelD{Homework Questions} -Complete the code below to find the length of the hypotenuse of a right triangle (remember that $a^2 + b^2 = c^2$) given the lengths of the other two sides. What will be the final output of the code? +Complete the code below to find the length of the hypotenuse of a right triangle (remember that $a^2 + b^2 = c^2$) given the lengths of the other two sides. What is the final output of your code? -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} #include // Add necessary libraries here @@ -216,27 +193,27 @@ int main() { - float a = 3.0, b = 4.0; - float c; - + double a = 3.0, b = 4.0; + double c; // // Finish the program... // - cout << "The hypotenuse of the right triangle is " << c << endl; + cout << "The hypotenuse of the right triangle is " + << c << endl; } -\end{lstlisting} +\end{lstlisting}\end{minipage} \LevelD{Review Answers} -\begin{itemize} -\item \texttt{\#include } must be included to include advanced operators. -\item \texttt{pow(2, 9)} -\item \texttt{double b = sqrt(10001);} -\end{itemize} +\begin{enumerate} +\item \Code{\#include } must be included to include advanced operators. +\item \Code{pow(2, 9)} +\item \Code{double b = sqrt(10001);} +\end{enumerate} \LevelD{Homework Answers} -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} #include #include @@ -244,20 +221,21 @@ int main() { - float a=3.0, b=4.0; - double c; + float a = 3.0, b = 4.0; + double c; - a=pow(a,2); - b=pow(b,2); - c=sqrt(a+b); + a = pow(a, 2); + b = pow(b, 2); + c = sqrt(a+b); - cout << "The hypotenuse of the right triangle is " << c << endl; + cout << "The hypotenuse of the right triangle is " + << c << endl; } -\end{lstlisting} +\end{lstlisting}\end{minipage} The final output of the code is: -\texttt{The hypotenuse of the right triangle is 5} +\Code{The hypotenuse of the right triangle is 5.0} \LevelD{Further Reading} diff --git a/chap_arithmetic.tex b/chap_arithmetic.tex index 66c178d..3e2c479 100644 --- a/chap_arithmetic.tex +++ b/chap_arithmetic.tex @@ -1,33 +1,33 @@ %Arithmetic One of the most important things provided by C++ is the ability to do math. -Everything a computer sees is a number. \ +Everything a computer sees is a number. To a computer, its ability to do math and manipulate numbers is as essential to it as breathing is to us. (My apologies to anything not living that may be reading this). The operators (\Code{+}, \Code{-}, \Code{*}, \Code{/}) in C++ are slightly different from what you may be used to from your second-grade math class. Addition is still a plus sign ( \Code{+} ) and subtraction is still a minus sign ( \Code{-} ). On the other hand, multiplication becomes an asterisk ( \Code{*} ) and division becomes a forward slash ( \Code{/} ). -Think of it as \textit{over} as in ``5 over 9'' is the same as the fraction $5/9$. +Think of it as \textit{over} as in ``5 over 9'' is the same as the fraction $5/9$ or $\frac{5}{9}$. To do math in C++, you will either want a variable to store the answer, or output the answer to the user. The following code directly outputs the answer to the user: -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} cout << 9 + 2; -\end{lstlisting} +\end{lstlisting}\end{minipage} This code shows how to use a variable to store the answer: -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int sum = 9 + 2; -\end{lstlisting} +\end{lstlisting}\end{minipage} Note that when you use a variable to store an answer, the variable must come first in the equation (before the equal sign) and must be the only thing on the left side of the equation. There are some other things to note. When you use more complicated equations, you can use parentheses to help. -C++ uses a familiar order of operations (Parentheses, Exponents, Multiply, Divide, Add, and Subtract, or PEMDAS), but without the exponent operation (this topic is covered in Chapter \ref{Advanced Arithmetic}). +C++ uses a familiar order of operations (Parentheses, Exponents, Multiply, Divide, Add, and Subtract, or PEMDAS), but without the exponent operation (this topic is covered in Chapter~\ref{chap_advancedarith}). However, unlike in normal arithmetic, parentheses do not imply multiplication. \Code{(4)(3)} does not mean the same as \Code{4~*~3}. \Code{(4)(3)} results in a syntax error and does not compile. @@ -43,44 +43,44 @@ Starting with similarities, \Code{C++} and \Code{++C} both increase value of \Code{C} by one. The difference lies in when another variable is being set to that incremented value, such as \Code{B = C++}. \Code{B} will be set to \Code{C} before \Code{C} is incremented. -\Code{B = ++C} will cause \Code{B} to be set to \Code{C+1}, in a similar way to \Code{B = 1 + C}. +\Code{B = ++C} will cause \Code{B} to be set to \Code{C+1}, in a similar way to \Code{B~=~1~+~C}. -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A; A = 4; A++; //A contains 5 -\end{lstlisting} -\begin{lstlisting} +\end{lstlisting}\end{minipage} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A; A = 9; A--; //A contains 8 -\end{lstlisting} -\begin{lstlisting} +\end{lstlisting}\end{minipage} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A, B; B = 7; A = B++; //A contains 7, B contains 8 -\end{lstlisting} -\begin{lstlisting} +\end{lstlisting}\end{minipage} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A, B; B = 7; A = ++B; //A contains 8, B contains 8 -\end{lstlisting} -\begin{lstlisting} +\end{lstlisting}\end{minipage} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A, B; B = 3; A = B--; //A contains 3, B contains 2 -\end{lstlisting} -\begin{lstlisting} +\end{lstlisting}\end{minipage} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} int A, B; B = 3; A = --B; //A contains 2, B contains 2 -\end{lstlisting} +\end{lstlisting}\end{minipage} Compound assignment operators can decrease the amount you type and can make your code more readable. These are the operators \Code{+=}, \Code{-=}, \Code{*=}, and \Code{/=}. @@ -105,110 +105,115 @@ Here is some sample code using the concepts we presented in this chapter: -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} #include using namespace std; int main() { - int a = 5, b = 10, c = 15, d = 20; + int a = 5, b = 10, c = 15, d = 20; - cout << "a + b = " << a + b << endl; - cout << "d - c = " << d - c << endl; - cout << "a * b = " << a * b << endl; - cout << "d / a = " << d / a << endl; + cout << "a + b = " << a + b << endl; + cout << "d - c = " << d - c << endl; + cout << "a * b = " << a * b << endl; + cout << "d / a = " << d / a << endl; } -\end{lstlisting} +\end{lstlisting}\end{minipage} The output of this code is: -\begin{lstlisting} +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} a + b = 15 d - c = 5 a * b = 50 d / a = 4 -\end{lstlisting} +\end{lstlisting}\end{minipage} \LevelD{Review Questions} \begin{enumerate} \item Write a statement declaring two integer variables \Code{a} and \Code{b} and initialize them to 6 and 3, respectively. \item Without changing the last line, fix the following code so there will be an output of 12. -\begin{lstlisting} - int a = 4, b= 2; - a = a + 2 * b; - cout << a; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a = 4, b= 2; +a = a + 2 * b; +cout << a; +\end{lstlisting}\end{minipage} \item What is the output of the following code? -\begin{lstlisting} - int a=2, b=5, c=6; - a++; - b = b*a; - c = (c-a) + 3; - cout << a << endl; - cout << b << endl; - cout << c << endl; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a=2, b=5, c=6; +a++; +b = b*a; +c = (c-a) + 3; +cout << a << endl; +cout << b << endl; +cout << c << endl; +\end{lstlisting}\end{minipage} \item What is the output of the following code? -\begin{lstlisting} - int a, b, c; - a = 2; - b = 8; - c = 1; - c = b - b; - c = a + a; - c = b * 8; - b = b + b; - c = a + c; - b = a + b; - a = a * c; - b = a - c; - c = b + a; - cout << a << endl; - cout << b << endl; - cout << c << endl; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a, b, c; +a = 2; +b = 8; +c = 1; +c = b - b; +c = a + a; +c = b * 8; +b = b + b; +c = a + c; +b = a + b; +a = a * c; +b = a - c; +c = b + a; +cout << a << endl; +cout << b << endl; +cout << c << endl; +\end{lstlisting}\end{minipage} \end{enumerate} \LevelD{Homework Exercises} \begin{enumerate} \item What is the output of the following code? -\begin{lstlisting} - int a=4, b=2, c, d; - a = b + 3; - b++; - c = (b + 4) * 2; - c = c + 2; - d = a + b - 3; - a++; - a = a + 2 - b; - b = b * 2; - cout << "a=" << a << endl; - cout << "b=" << b << endl; - cout << "c=" << c << endl; - cout << "d=" << d << endl; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a = 4, b = 2, c, d; +a = b + 3; +b++; +c = (b + 4) * 2; +c = c + 2; +d = a + b - 3; +a++; +a = a + 2 - b; +b = b * 2; +cout << "a=" << a << endl; +cout << "b=" << b << endl; +cout << "c=" << c << endl; +cout << "d=" << d << endl; +\end{lstlisting}\end{minipage} \item What is the output of the following code? -\begin{lstlisting} - int m=3, n=2, x, y; - x = m + 5; - m--; - y = (m+4) / 3; - n = n + 2; - m = m + n / 2; - m++; - x = x * 2 - 3; - y = y * 2; - n = n + y * 3 - cout << "m=" << m << endl; - cout << "n=" << n << endl; - cout << "x=" << x << endl; - cout << "y=" << y << endl; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int m=3, n=2, x, y; +x = m + 5; +m--; +y = (m+4) / 3; +n = n + 2; +m = m + n / 2; +m++; +x = x * 2 - 3; +y = y * 2; +n = n + y * 3 +cout << "m=" << m << endl; +cout << "n=" << n << endl; +cout << "x=" << x << endl; +cout << "y=" << y << endl; +\end{lstlisting}\end{minipage} \end{enumerate} \LevelD{Review Answers} @@ -216,45 +221,50 @@ \item \Code{int a = 6, b = 3;} \item -\begin{lstlisting} - int a = 4, b = 2; - a = (a + 2) * b; - cout << a; -\end{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} +int a = 4, b = 2; +a = (a + 2) * b; +cout << a; +\end{lstlisting}\end{minipage} \item -\begin{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} 3 15 5 -\end{lstlisting} +\end{lstlisting}\end{minipage} \item -\begin{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} 132 66 198 -\end{lstlisting} +\end{lstlisting}\end{minipage} \end{enumerate} \LevelD{Homework Answers} \begin{enumerate} \item -\begin{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} a=5 b=6 c=16 d=5 -\end{lstlisting} +\end{lstlisting}\end{minipage} \item -\begin{lstlisting} + +\noindent\begin{minipage}{\linewidth}\begin{lstlisting} m=5 n=16 x=13 y=4 -\end{lstlisting} +\end{lstlisting}\end{minipage} \end{enumerate} \LevelD{Further Reading} diff --git a/chap_constants.tex b/chap_constants.tex index e69de29..d1b7f6f 100644 --- a/chap_constants.tex +++ b/chap_constants.tex @@ -0,0 +1,34 @@ +We call a variable whose value we cannot change a constant. +After you declare a constant, you are unable to change it, no matter what. +There are two types of constants: literal and declared constants (\Code{const}). + +\LevelD{Literals} + +A literal is a value outide of a variable such as $5$, $9$, $103$, and $-21$. Each of those is an \Code{int}, but a literal constant can be of any data type. The point is, these are values that the C++ compiler already recognizes, and can’t be changed. In other words, you can’t convince the compiler to give the literal 3 the value of 4, because 3 is constant. The table below contains a few examples. + +13.8903 +94.2321 +-389283220.342423 +float +‘x’ +‘R’ +‘%’ +char +Be aware, that C++ interprets the difference between a char and a single-character variable name by the enclosure of (‘) single quotation marks. +true +false +bool +Notice that a bool only has two literal values, true or false. + + +Declared Constant + +So what’s the difference between declaring a normal variable and a constant? When we declare a constant, we simply place the keyword const before the data type in the declaration. This indicates that whatever declaration follows the const will be a constant and cannot be changed. Since it’s a constant, you will also need to initialize the value at the same time you declare the variable. Here is an example: + +const float pi = 3.14; +float radius = 5, area; + +area = radius * radius * pi; +cout << area; + +//program outputs 78.5 to the screen diff --git a/chap_preproc.tex b/chap_preproc.tex index 9af7696..79cf038 100644 --- a/chap_preproc.tex +++ b/chap_preproc.tex @@ -30,7 +30,7 @@ \Code{} & Mathematical functions & \Code{pow()}, \Code{sqrt()}, \Code{cos()}, \Code{tan()}, \Code{sin()}: see Chapter~\ref{chap_advancedarith} \\ \hline \Code{} & Input/output manipulation & \Code{get\_money()}, \Code{get\_time()}, \Code{put\_time()} \\ \hline \Code{} & Time-related functions & \Code{clock()}, \Code{time()}, \Code{ctime()} \\ \hline - \Code{} & The \Code{string} class & See Chapter~\ref{chap_string} \\ \hline + \Code{} & The \Code{string} class & See Chapter~\ref{chap_strings} \\ \hline \Code{} & File input and output streams & See Chapter~\ref{chap_file_io} \\ \hline \end{tabular} diff --git a/chap_strings.tex b/chap_strings.tex index 0711049..cef0e2e 100644 --- a/chap_strings.tex +++ b/chap_strings.tex @@ -184,16 +184,16 @@ \end{lstlisting}\end{minipage} \LevelD{Review Questions} \begin{enumerate} -\item Write code to declare a string and take input from a user. -\item Can a string be treated as a character array? -\item When do you use a string? -\item What is the \Code{\#include} needed to use strings? +\item Write code to declare a \Code{string} and take input from a user. +\item Can a \Code{string} be treated as a character array? +\item When do you use a \Code{string}? +\item What is the \Code{\#include} needed to use \Code{string}s? \item What function do you have to use to take an input with a space? \end{enumerate} \LevelD{Homework Questions} \begin{enumerate} -\item Write a code that takes in 5 words and outputs them 4 times. +\item Write code that takes in 5 words and outputs each of them 4 times. \item Write a program that takes in the following words: King, Queen, Knight, Bishop, Rook, Pawn. Then it has to switch the King with the Pawn, the Rook with the Queen, and the Bishop with the Knight. diff --git a/chap_variables.tex b/chap_variables.tex index e69de29..2655b6d 100644 --- a/chap_variables.tex +++ b/chap_variables.tex @@ -0,0 +1,152 @@ + +Variables are extremely important to every programmer - they will be a critical part of your programming toolkit regardless of the language you use. +Very simply put, a variable is a space in memory that can store some range of values. +Some of the basic data types are: + +\begin{table}[tb] + \centering + \begin{tabular}{| l | p{3in} |} + \hline + \Code{int} & Short for integer; stores whole numbers \\ \hline + \Code{char} & Short for character; stores a single letter, digit, or symbol \\ \hline + \Code{bool} & Short for Boolean; stores \Code{true} or \Code{false} \\ \hline + \Code{float} & Short for floating point number; stores numbers with fractional parts \\ \hline + \Code{double} & Short for double precision floating point number; stores bigger numbers with bigger fractional parts than \Code{float} \\ \hline + \end{tabular} +\end{table} + +For a deeper discussion of data types, refer to Chapter \ref{chap_datatypes}. + +\LevelD{How do I decide which data type I need?} + +What you can do with a variable depends on the type of data they contain. +For instance, you can't store the number $100000$ in a \Code{char} because a \Code{char} stores only character data. +To store $100000$ the programmer should use an $int$. +If you think you are dealing with numbers that have fractional parts, you need at least a \Code{float}. +You generally want to use the smallest variable type that will get your job done. +Simply put, if it is a round number, \Code{int} works fine; if it's a \Code{true} or \Code{false}, use \Code{bool}; for a letter, use \Code{char}; for fractional numbers, use \Code{float}; for a really big number or a number with many digits after the decimal point, use \Code{double}. + +\LevelD{Identifiers} + +Now we have an idea of what types of variables we will use in the program. +How do we have the program differentiate between multiple \Code{int}s, \Code{char}s, or \Code{double}s? +We have to name them! +The name we use will give the variable an identity, so it's known as an \Keyword{identifier}. +An identifier can be almost anything you'd like.\footnote{There are a few exceptions, including those words that describe data types (as in the table above) and other keywords such as \Code{if} and \Code{while}, which you'll learn about in later chapters.} +Remember that the variable name can only be one word long. +You may use a an underscore to replace a space if you so desire, and note that C++ is case sensitive. +That is, \Code{testresults}, \Code{TestResults}, and \Code{Test\_Results} are all different identifiers. + +\LevelD{Declaring a Variable} + +The line of code that creates a variable is called a \Keyword{declaration}. +A declaration is the program telling the computer ``save a place in memory for me with this name.'' +%Maybe irrelevant/too advanced for this chapter +%Behind the scenes, the compiler gives the variable an address, which is like a map saying ``this is where your memory is.'' + +A declaration for an integer variable named \Code{myVariable} looks like this: + +\begin{lstlisting} +int myVariable; +\end{lstlisting} + +The specific \Keyword{syntax}---the set of grammatical rules for the language---is important to follow when declaring variables. +Notice that the first part (\Code{int}) is the data type of the variable. +The second part is the identifier (\Code{myVariable}), or variable name. +The last part is the semicolon (\Code{;}) which signifies the end of a line. +You can think of the semicolon in C++ as equivalent to a period at the end of a sentence; it is the end of a complete thought. +Note that you may declare several variables of the same data type together. Consider this example: + +\begin{lstlisting} +int x, y, z; +double a; +\end{lstlisting} + +The above example creates three variables of type \Code{int} named \Code{x}, \Code{y}, and \Code{z} and one variable of type \Code{double} named \Code{a}. + + +\LevelD{Initializing Variables} + +Values can be immediately assigned to a variable at the time of its declaration. +This is known as \Keyword{initializing} a variable. +To do this, the variable's name is followed by an equals sign (\Code{=}, the \Keyword{assignment operator}), the value, and a semicolon. Consider this example: + +\begin{lstlisting} +int x = 20; +double a = 2.2; +\end{lstlisting} + +Note that uninitialized variables can cause problems if they are used anywhere before they are assigned a value. +When a variable is declared, it contains whatever was already in that space of memory, which can give them unpredictable values. +This means that is is often a good idea to initialize variables to some sensible initial value when they are declared. + +\LevelD{Assignment Statements} + +An assignment statement is a method of assigning a value to a variable after it has been declared. +All assignment statements have the variable being assigned the value on the left side of an equals sign and the value to assign on the right side. +Note that the expression on the right side of the assignment may contain arithmetic operations such as multiplication, division, addition, and subtraction, or even other variables. +Consider the following example: + +\begin{lstlisting} +int a = 1, b = 2, x = 0, y = 0; +x = a + b; +y = x; +\begin{lstlisting} + +% TODO: character values + + +\LevelD{Review Questions} + +\begin{enumerate} + \item Declare two variables of type \Code{int} and initialize them to an appropriate value. + \item Declare three integer variables: \Code{sum}, \Code{a}, \Code{b}. Initialize the variables \Code{a} and \Code{b} to an appropriate integer and use an assignment statement to assign \Code{sum} the result of \Code{a} plus \Code{b}. + \item Declare a \Code{double} variable called \Code{number} and initialize it to $13.6$. + %\item Declare a variable of type \Code{char}, then give the char a character. +\end{enumerate} + +\LevelD{Homework Questions} + +Create a program in which 3 variables are declared. +Create one \Code{float} named \Code{myFloat}, one \Code{int} named \Code{myInt}, and one \Code{double} named \Code{myDouble}. +Initialize them to $3.14$, $3$, and $3.14159$, respectively. +%Then declare a variable of type \Code{char} named \Code{myChar}, and initialize it to the character B. + +\LevelD{Review Answers} + + +\begin{enumerate} + \item \Code{int a = 6;} + \Code{int b = 0;} + + \item \Code{int sum, a = 6, b = 0;} + \Code{sum = a + b;} + + \item \Code{double number = 13.6;} +\end{enumerate} +%4. +% char myAlpha; +% myAlpha = 'A'; + +\LevelD{Homework Answers} + +\begin{lstlisting} +int main() +{ + float myFloat = 3.14; + int myInt = 3; + double myDouble = 3.14159; + + return 0; +} +\end{lstlisting} + +% char myChar = 'B'; + +\LevelD{Further Reading} + +\begin{itemize} +\item \url{http://www.cplusplus.com/doc/tutorial/variables/} +\item \url{http://www.tutorialspoint.com/cplusplus/cpp_variable_types.htm} +\item \url{~} +\end{itemize} \ No newline at end of file diff --git a/chapter-status.txt b/chapter-status.txt new file mode 100644 index 0000000..df07e32 --- /dev/null +++ b/chapter-status.txt @@ -0,0 +1,23 @@ +Advanced arithmetic - semi-final +Arithmetic - semi-final +Arrays +Assignments +Classes +Comments +Conditionals +Constants +Data types +Dynamic +File IO +Functions +History +Input +Loops +Output +Pointers +Preproc +Problems +Separate +STL +Strings +Variables diff --git a/cpp.tex b/cpp.tex index a6fc640..228ce41 100644 --- a/cpp.tex +++ b/cpp.tex @@ -306,15 +306,15 @@ \chapter*{License} % \input{chap_types.tex} % \LevelC{How Computers Use Memory} % \input{chap_memory.tex} - \LevelC{Sample Program} - \label{chap_sampleprogram} - \input{chap_sampleprogram.tex} +% \LevelC{Sample Program} +% \label{chap_sampleprogram} +% \input{chap_sampleprogram.tex} % \LevelA{Section 2} %\LevelB{Chapters:} \LevelC{Variables} \label{chap_variables} \input{chap_variables.tex} - \LevelC{Constants} + \LevelC{Literals and Constants} \label{chap_constants} \input{chap_constants.tex} \LevelC{Assignments} diff --git a/cpp.tps b/cpp.tps index 725f502..c16da0e 100644 --- a/cpp.tps +++ b/cpp.tps @@ -4,14 +4,14 @@ Version=2 [SessionInfo] ActiveTab=2 -FrameCount=3 -ActiveFrame=2 +FrameCount=5 +ActiveFrame=0 [Frame0] Columns=1 Rows=1 -Flags=0 -ShowCmd=1 +Flags=2 +ShowCmd=3 MinPos.x=-1 MinPos.y=-1 MaxPos.x=-4 @@ -24,17 +24,17 @@ Class=CLatexEdit Document=cpp.tex [Frame0_Row0] -cyCur=365 +cyCur=396 cyMin=10 [Frame0_Col0] -cxCur=895 +cxCur=1338 cxMin=10 [Frame0_View0,0] -Cursor.row=0 -Cursor.column=0 -TopSubLine=330 +Cursor.row=360 +Cursor.column=1 +TopSubLine=352 [Frame1] Columns=1 @@ -45,52 +45,110 @@ MinPos.x=-1 MinPos.y=-1 MaxPos.x=-4 MaxPos.y=-23 -NormalPos.left=110 -NormalPos.top=110 -NormalPos.right=1068 -NormalPos.bottom=526 +NormalPos.left=66 +NormalPos.top=66 +NormalPos.right=1292 +NormalPos.bottom=377 Class=CLatexEdit -Document=chap_datatypes.tex +Document=chap_preproc.tex [Frame1_Row0] -cyCur=369 +cyCur=264 cyMin=10 [Frame1_Col0] -cxCur=930 +cxCur=1198 cxMin=10 [Frame1_View0,0] -Cursor.row=89 +Cursor.row=41 Cursor.column=0 -TopSubLine=108 +TopSubLine=43 [Frame2] Columns=1 Rows=1 -Flags=2 -ShowCmd=3 +Flags=0 +ShowCmd=1 MinPos.x=-1 MinPos.y=-1 MaxPos.x=-4 MaxPos.y=-23 -NormalPos.left=132 -NormalPos.top=132 -NormalPos.right=1090 -NormalPos.bottom=548 +NormalPos.left=0 +NormalPos.top=0 +NormalPos.right=1300 +NormalPos.bottom=279 Class=CLatexEdit -Document=chap_file_io.tex +Document=chap_strings.tex [Frame2_Row0] -cyCur=435 +cyCur=232 cyMin=10 [Frame2_Col0] -cxCur=1114 +cxCur=1272 cxMin=10 [Frame2_View0,0] Cursor.row=0 -Cursor.column=15 +Cursor.column=0 +TopSubLine=37 + +[Frame3] +Columns=1 +Rows=1 +Flags=0 +ShowCmd=1 +MinPos.x=-1 +MinPos.y=-1 +MaxPos.x=-4 +MaxPos.y=-23 +NormalPos.left=22 +NormalPos.top=22 +NormalPos.right=1322 +NormalPos.bottom=301 +Class=CLatexEdit +Document=chap_testing.tex + +[Frame3_Row0] +cyCur=232 +cyMin=10 + +[Frame3_Col0] +cxCur=1272 +cxMin=10 + +[Frame3_View0,0] +Cursor.row=0 +Cursor.column=0 +TopSubLine=0 + +[Frame4] +Columns=1 +Rows=1 +Flags=0 +ShowCmd=1 +MinPos.x=-1 +MinPos.y=-1 +MaxPos.x=-4 +MaxPos.y=-23 +NormalPos.left=44 +NormalPos.top=44 +NormalPos.right=1344 +NormalPos.bottom=323 +Class=CLatexEdit +Document=chap_variables.tex + +[Frame4_Row0] +cyCur=232 +cyMin=10 + +[Frame4_Col0] +cxCur=1272 +cxMin=10 + +[Frame4_View0,0] +Cursor.row=1 +Cursor.column=0 TopSubLine=0 diff --git a/kickstarters.tex b/kickstarters.tex index de9d687..ee8f25e 100644 --- a/kickstarters.tex +++ b/kickstarters.tex @@ -10,7 +10,6 @@ Patrick Berthon, Francis Bolduc, Greg Borenstein, -Mark Braun, Patrick Breen, Igor Bronshteyn, Valdemar Bu\-{\v{c}}il\-ko,