If statements


WIP: Need to convert my LaTeX file to orgmode

\begin{figure}[h] \begin{center} \includegraphics[width=12cm]{images/controlflow.png} \end{center} \end{figure}

\section{Boolean Expressions} %-------------------------------–—%

\subsection{Introduction}

In order to start writing questions that a computer can understand, we need to understand \textbf{boolean expressions}. ~

A math expression looks like this:

\[ 2 + 3 \]

A boolean expression is a statement that result in either \textbf{true} or \textbf{false}:

\begin{center} \textit{ ``is it daytime?'' } \textit{ ``did the user save the document?'' } \textit{ ``is the user's age greater than 12 and less than 20?'' } \end{center} \begin{center} \includegraphics[width=4cm]{images/cat.png} \begin{verbatim} if ( iHaveNotBeenFed && itIs6am ) { MakeLotsOfNoise(); } \end{verbatim} \end{center}

\newpage Logic in computer programs are based around these types of questions: something that can only be \textbf{true} or \textbf{false}. Statements include:

\begin{center} \begin{tabular}{p{3cm} c p{7cm}} \textbf{Type} & \textbf{Example} & \textbf{Description} \\ \hline Is true? & \texttt{ a } & If \texttt{a} is a boolean variable, we can ask if it's true. \\ \\ Is false? & \texttt{ !a } & If \texttt{a} is a boolean variable, we can ask if it's false. \\ \\ Equivalence? & \texttt{ a == b } & Are the values of \texttt{a} and \texttt{b} the same? \\ \\ Not equivalent? & \texttt{ a != b } & Are the values of \texttt{a} and \texttt{b} different? \\ \\ Less than? & \texttt{ a < b } & Is \texttt{a} less than \texttt{b}? \\ \\ Less than or equal to? & \texttt{ a <= b } & Is \texttt{a} less than or equal to \texttt{b}? \\ \\ Greater than? & \texttt{ a > b } & Is \texttt{a} greater than \texttt{b}? \\ \\ Greater than or equal to? & \texttt{ a >= b } & Is \texttt{a} greater than or equal to \texttt{b}? \end{tabular} \end{center}

For the first two, we can check the value of a \textbf{boolean variable}. The rest of them, we can use any data type to compare if two values are equal, greater than, less than, etc. \texttt{a} and \texttt{b} can be replaced with variables and/or values…

\begin{itemize} \item \texttt{ if ( age < 18 ) } ... \item \texttt{ if ( myState == yourState ) } ... \item \texttt{ if ( word1 < word2 ) } ... ~\\ When using $<$ and $>$ with strings or chars, it will compare them based on alphabetical order - if they're both the same case (both uppercase or both lowercase). \item \texttt{ if ( documentSaved == false ) }... ~\\ For boolean variables, you can check to see if they are equal to \texttt{true} or \texttt{false}. \end{itemize}

\newpage \subsection{And, Or, and Not operators}

We can also combine boolean expressions together to ask more sophisticated questions.

\paragraph{Not operator: \texttt{!}} If we're checking a boolean variable, or a boolean expression, and we happen to want to execute some code for when that result is \textbf{false}, we can use the not operator…

~\\ Using with \textbf{boolean variable \texttt{documentSaved}:}

\begin{lstlisting}[style=code] // Just checking documentSaved = true if ( documentSaved ) { Quit(); } // Checking if documentSaved = false with the not operator if ( !documentSaved ){ Save(); Quit(); } \end{lstlisting}

~\\ Using with \textbf{boolean expressions \texttt{( age >= 21 )}:}

\begin{lstlisting}[style=code] // If the age is not 21 or over... if ( !( age >= 21 ) ) { NoBeer(); } \end{lstlisting}

\paragraph{And operator: \texttt{\&\&}}

When using the and operator, we can check to see if \textbf{all boolean variables/expressions are true}. The full question of ``is this and this and this true?'' only results to \textbf{true} if \textbf{all boolean variables/expressions are true}. If even one of them are false, then the entire statement is false.

\begin{lstlisting}[style=code] if ( wantsBeer && isAtLeast21 ) { GiveBeer(); } \end{lstlisting}

To break it down, the customer would only get beer if they \textit{want beer} AND if \textit{they are over 21}. If they don't want beer but are 21 or over, they don't get beer. If they want beer but are under 21, then they don't get beer.

\paragraph{Or operator: \texttt{||}}

For an or operator, we can check to see if \textbf{at least one boolean variable/expression is true}. If at least one item is true, then the whole statement is true. The only way for it to be false is when each boolean variable/expression is false.

\begin{lstlisting}[style=code] if ( isBaby || isSenior || isVet ) { GiveDiscount(); } \end{lstlisting}

In this case, discounts are given to babies, seniors, and vets. A customer wouldn't have to be all three to qualify (and clearly, couldn't be all three at the same time!). If the customer is \textit{not} a baby and \textit{not} a senior and \textit{not} a vet, then they don't get the discount - all three criteria have to be false for the entire expression to be false.

\subsection{Truth tables}

We can use \textbf{truth tables} to help us visualize the logic that we're working with, and to validate if our assumptions are true. Truth tables are for when we have an expression with more than one variable (usually) and want to see the result of using ANDs, ORs, and NOTs to combine them.

\paragraph{Truth table for NOT:} ~

On the top-left of the truth table we will have the boolean variables or expressions written out, and we will write down all its possible states. With just one variable \(p\), we will only have two states: when it's true, or when it's false. ~

On the right-hand side (I put after the double lines) will be the result of the expression - in this case, ``not-p'' \(!p\). The not operation simply takes the value and flips it to the opposite: true \(\to\) false, and false \(\to\) true.

\begin{center} \begin{tabular}{c | | c} $p$ & $!p$ \\ \hline \true & \false \\ \false & \true \end{tabular} \end{center}

\newpage

\paragraph{Truth table for AND:} ~
For a truth table that deals with two variables, \(p\) and \(q\), the total amount of states will be 4:

\begin{enumerate} \item $p$ is true and $q$ is true. \item $p$ is true and $q$ is false. \item $p$ is false and $q$ is true. \item $p$ is false and $q$ is false. \end{enumerate} \begin{center} \begin{tabular}{c | c | | c} $p$ & $q$ & $p \&\& q$ \\ \hline \true & \true & \true \\ \true & \false & \false \\ \false & \true & \false \\ \false & \false & \false \end{tabular} \end{center}

This is just a generic truth table. We can replace the values with boolean expressions in C++ to check our logic.

~
For example, we will only quit the program if the game is saved and the user wants to quit:

\begin{center} \begin{tabular}{c | c | | c} \texttt{gameSaved} & \texttt{wantToQuit} & \texttt{gameSaved \&\& wantToQuit} \\ \hline \true & \true & \true \\ \true & \false & \false \\ \false & \true & \false \\ \false & \false & \false \end{tabular} \end{center}

The states are:

\begin{enumerate} \item \texttt{gameSaved} is true and \texttt{wantToQuit} is true: Quit the game. \checkmark \item \texttt{gameSaved} is true and \texttt{wantToQuit} is false: The user doesn't want to quit; don't quit. \xmark \item \texttt{gameSaved} is false and \texttt{wantToQuit} is true: The user wants to quit but we haven't saved yet; don't quit. \xmark \item \texttt{gameSaved} is false and \texttt{wantToQuit} is false: The user doesn't want to quit and the game hasn't been saved; don't quit. \xmark \end{enumerate}

\newpage \paragraph{Truth table for OR:} ~
Generic form:

\begin{center} \begin{tabular}{c | c | | c} $p$ & $q$ & $p$ \texttt{||} $q$ \\ \hline \true & \true & \true \\ \true & \false & \true \\ \false & \true & \true \\ \false & \false & \false \end{tabular} \end{center}

Again, if at least one of the expressions is \textbf{true}, then the entire expression is true.

~\\ Example: If the store has cakes OR ice cream, then suggest it to the user that wants dessert.

\begin{center} \begin{tabular}{c | c | | c} \texttt{hasCake} & \texttt{hasIcecream} & \texttt{hasCake || hasIceCream} \\ \hline \true & \true & \true \\ \true & \false & \true \\ \false & \true & \true \\ \false & \false & \false \end{tabular} \end{center}

The states are:

\begin{enumerate} \item \texttt{hasCake} is true and \texttt{hasIcecream} is true: The store has desserts; suggest it to the user. \checkmark \item \texttt{hasCake} is true and \texttt{hasIcecream} is false: The store has cake but no ice cream; suggest it to the user. \checkmark \item \texttt{hasCake} is false and \texttt{hasIcecream} is true: The store has no cake but it has ice cream; suggest it to the user. \checkmark \item \texttt{hasCake} is false and \texttt{hasIcecream} is false: The store doesn't have cake and it doesn't have ice cream; don't suggest it to the user. \xmark \end{enumerate}

\newpage \subsection{DeMorgan's Laws}

Finally, we need to cover DeMorgan's Laws, which tell us what the \textit{opposite} of an expression means. ~

For example, if we ask the program \textbf{``is a $>$ 20?''} and the result is \textbf{false}, then what does this imply? If \(a > 20\) is false, then \(a \leq 20\) is true… notice that the opposite of ``greater than'' is ``less than OR equal to''!

\paragraph{Opposite of \texttt{a \&\& b}:}

\begin{center} \begin{tabular}{c | c | | c} \texttt{a} & \texttt{b} & \texttt{a \&\& b} \\ \hline \true & \true & \true \\ \true & \false & \false \\ \false & \true & \false \\ \false & \false & \false \end{tabular} \end{center}

If we're asking ``is \(a\) true and is \(b\) true?'' together, and the result is \textbf{false}, that means either:

\begin{enumerate} \item $a$ is false and $b$ is true, or \item $a$ is true and $b$ is false, or \item $a$ is false and $b$ is false. \end{enumerate}

These are the states where the result of \texttt{a \&\& b} is false in the truth table.

In other words,

\begin{center} \texttt{!( a \&\& b ) $\equiv$ !a || !b} \end{center}

If \(a\) is false, or \(b\) is false, or both are false, then the result of \texttt{a \&\& b} is false.

\newpage \paragraph{Opposite of \texttt{a || b}:}

\begin{center} \begin{tabular}{c | c | | c} \texttt{a} & \texttt{b} & \texttt{a || b} \\ \hline \true & \true & \true \\ \true & \false & \true \\ \false & \true & \true \\ \false & \false & \false \end{tabular} \end{center}

If we're asking ``is \(a\) true or \(b\) true?'', if the result of that is \textbf{false} that means only one thing:

\begin{enumerate} \item Both $a$ and $b$ were false. \end{enumerate}

This is the only state where the result of \texttt{a || b} is false.

In other words,

\begin{center} \texttt{!( a || b ) $\equiv$ !a \&\& !b} \end{center}

\texttt{a \&\& b} is false only if \(a\) is false AND \(b\) is false.

\subsection{Summary}

In order to be able to write \textbf{if statements} or \textbf{while loops}, you need to understand how these boolean expressions work. If you're not familiar with these concepts, they can lead to you writing \textbf{logic errors} in your programs, leading to behavior that you didn't want.

\begin{center} \includegraphics[width=5cm]{images/evilbug.png} \end{center}

\section{Branching}

Branching is one of the core forms of \textbf{controlling the flow of the program}. We ask a question, and based on the result we perhaps do \textit{this code over here} or maybe \textit{that code over there} - the program results change based on variables and data accessible to it. ~

We will mostly be using \textbf{if / else if / else statements}, though \textbf{switch} statements have their own use as well. Make sure to get a good understanding of how each type of branching mechanism ``flows''.

\subsection{If statements} If statements (usually the general term encompassing if / else if / else as well) are a way we can ask a question and respond: If \(a\) is less than \(b\) then… or if \(a\) is greater than \(c\) then… Otherwise do this default thing… ~

Let's look at some examples while ironing out how it works.

\newpage \subsubsection{If statements}

For a basic \textbf{if statement}, we use the syntax:

\begin{lstlisting}[style=code] // Do things 1 if ( CONDITION ) { // Do things 1-a } // Do things 2 \end{lstlisting}

The CONDITION will be some \textbf{boolean expression}. If the boolean expression result is \textbf{true}, then any code within this if statement's \textbf{code block} (what's between \{ and \}) will get executed. If the result of the expression is \textbf{false}, then the entire if statement's code block is skipped and the program continues.

~\\ Example:

\begin{lstlisting}[style=code] cout << "Bank balance: " << balance; if ( balance < 0 ) { cout << " (OVERDRAWN!)"; } cout << " in account #" << accountNumber << endl; \end{lstlisting}

~\\ Output with \texttt{balance = -50}

\begin{lstlisting}[style=output] Bank balance: -50 (OVERDRAWN!) in account #1234 \end{lstlisting}

~\\ Output with \texttt{balance = 100}

\begin{lstlisting}[style=output] Bank balance: 100 in account #1234 \end{lstlisting} \begin{itemize} \item The special message ``OVERDRAWN!'' only gets displayed when the balance is less than 0. \item The following \texttt{cout} that gives the account number is displayed in all cases. \end{itemize}

~\\ Diagram:

\begin{center} \begin{tikzpicture} \draw (-5,10) -- (5,10) -- (5,12) -- (-5,12) -- (-5,10); \node at (0, 11) { \texttt{ cout << "Bank balance: " << balance; } }; \draw (-5, 8) -- (0, 7) -- (5, 8) -- (0, 9) -- (-5,8); \node at (0, 8) { \texttt{balance < 0} ? }; \draw[-stealth,ultra thick] (0,10) -- (0,9); \draw (-7,4) -- (-1,4) -- (-1,6) -- (-7,6) -- (-7,4); \node at (-4, 5) { \texttt{ cout << " (OVERDRAWN!)"; } }; \draw[-stealth,ultra thick] (0, 7) -- (-3, 6); \draw[-stealth,ultra thick] (0, 7) -- (0,2); \draw[-stealth,ultra thick] (-3,4) -- (-1,2); \node at (-2, 6.7) {true}; \node at (0.5, 5) {false}; \draw (-6,0) -- (6,0) -- (6,2) -- (-6,2) -- (-6,0); \node at (0, 1) { \texttt{ cout << " in account \#" << accountNumber << endl; } }; \end{tikzpicture} \end{center}

\newpage \subsubsection{If/Else statements}

In some cases, we will have code that we want to execute for the \textbf{false} result as well. For an \textbf{if/else} statement, either the \textbf{if} code block will be entered, or the \textbf{else} code block will be.

~
\textbf{NOTE:} The else statement NEVER has a CONDITION.

\begin{lstlisting}[style=code] // Do things 1 if ( CONDITION ) { // Do things 1-a } else { // Do things 1-b } // Do things 2 \end{lstlisting}

The \textbf{else} block is executed when the \textbf{if} check fails. If the CONDITION is false, we can use \textbf{DeMorgan's Laws} to figure out what the program's state is during the \textbf{else}.

~\\ Example:

\begin{lstlisting}[style=code] cout << "Enter your age: "; cin >> age; if ( age < 18 ) { result = "can't vote"; } else { result = "can vote"; } cout << "Result: " << result << endl; \end{lstlisting}

If the \texttt{age} is less than 18, it will set the \texttt{result} variable to ``can't vote''. If that boolean expression is \textbf{false}, that means \texttt{age} is \(\geq\) 18, and then it will set the \texttt{result} to ``can vote''. Finally, either way, it will display ``Result: '' with the value of the \texttt{result} variable.

~\\ Diagram:

\begin{center} \begin{tikzpicture} \draw (-5,10) -- (5,10) -- (5,12) -- (-5,12) -- (-5,10); \node at (0, 11) { \texttt{ cout << "Enter your age: "; cin >> age; } }; \draw (-5, 8) -- (0, 7) -- (5, 8) -- (0, 9) -- (-5,8); \node at (0, 8) { \texttt{age < 18} ? }; \draw[-stealth,ultra thick] (0,10) -- (0,9); \draw (-7,4) -- (-1,4) -- (-1,6) -- (-7,6) -- (-7,4); \node at (-4, 5) { \texttt{ result = "can't vote"; } }; \draw (7,4) -- (1,4) -- (1,6) -- (7,6) -- (7,4); \node at (4, 5) { \texttt{ result = "can vote"; } }; \draw[-stealth,ultra thick] (0, 7) -- (-3, 6); \draw[-stealth,ultra thick] (0, 7) -- (3, 6); \draw[-stealth,ultra thick] (-3,4) -- (-1,2); \draw[-stealth,ultra thick] (3,4) -- (1,2); \node at (-2, 6.7) {true}; \node at (2, 6.7) {false}; \draw (-6,0) -- (6,0) -- (6,2) -- (-6,2) -- (-6,0); \node at (0, 1) { \texttt{ cout << "Result: " << result << endl; } }; \end{tikzpicture} \end{center}

\newpage \subsubsection{If/Else if/Else statements}

In some cases, there will be multiple scenarios we want to search for, each with their own logic. We can add as many \textbf{else if} statements as we want - there must be a starting \textbf{if} statement, and each \textbf{else if} statement will have a condition as well.

~
We can also end with a final \textbf{else} statement as a catch-all: if none of the previous if / else if statements are true, then \textbf{else} gets executed instead. However, the else is not required.

\begin{lstlisting}[style=code] // Do things 1 if ( CONDITION1 ) { // Do things 1-a } else if ( CONDITION2 ) { // Do things 1-b } else if ( CONDITION3 ) { // Do things 1-c } else { // Do things 1-d } // Do things 2 \end{lstlisting}

~\\ Example:

\begin{lstlisting}[style=code] cout << "Enter grade: "; cin >> grade; if ( grade >= 90 ) { letterGrade = 'A'; } else if ( grade >= 80 ) { letterGrade = 'B'; } else if ( grade >= 70 ) { letterGrade = 'C'; } else if ( grade >= 60 ) { letterGrade = 'D'; } else { letterGrade = 'F'; } cout << "Grade: " << letterGrade << endl; \end{lstlisting}

With this example, I'm first checking if the grade is 90 or above. If it is, then I know the letter grade is \texttt{'A'}. ~

However, if it's false, it will go on and check the next \textbf{else if} statement. At this point, I know that since \texttt{grade >= 90} was FALSE, that means \texttt{grade < 90}. Since the next statement checks if \texttt{grade >= 80}, if this one is true I know that \texttt{grade < 90 AND grade >= 80}.

~\\ Diagram:

\begin{center} \includegraphics[width=12cm]{images/diagrams/branching.png} \end{center}

\newpage \subsection{Switch statements}

Switch statements are a special type of branching mechanism that \underline{only} checks if the value of a variable is \textbf{equal to} one of several values. Switch statements can be useful when implementing a menu in a program, or something else where you only have a few, finite, discrete options. ~
In C++, switch statements only work with primitive data types, like integers and chars - not strings.

\begin{lstlisting}[style=code] switch ( VARIABLE ) { case VALUE1: // Do thing break; case VALUE2: // Do thing break; default: // Default code } \end{lstlisting}

With a switch statement, each \textbf{case} is one equivalence expression. The \texttt{default} case is executed if none of the previous cases are.

\begin{itemize} \item \texttt{ case VALUE1: } is equivalent to \texttt{ if (VARIABLE == VALUE1) } \item \texttt{ case VALUE2: } is equivalent to \texttt{ else if (VARIABLE == VALUE2) } \item \texttt{ case default: } is equivalent to \texttt{ else } \end{itemize}

\paragraph{The default case} is not required, just like how the \textbf{else} clause is not required in an if statement.

\paragraph{The break; statement} The end of each case should have a \texttt{break;} statement at the end. If the \texttt{break} is not there, then it will continue executing each subsequent case's code until it \textit{does} hit a break. ~
This behavior is ``flow-through'', and it can be used as a feature if it matches the logic you want to write.

\newpage ~
Example: Perhaps you are implementing a calculator, and want to get an option from the user: (A)dd, (S)ubtract, (M)ultiply, or (D)ivide. You could store their choice in a \texttt{char} variable called \texttt{operation} and then use the \texttt{switch} statement to decide what kind of computation to do:

\begin{lstlisting}[style=code] switch ( operation ) { case 'A': // if ( opreation == 'A' ) result = num1 + num2; break; case 'S': // else if ( operation == 'S' ) result = num1 - num2; break; case 'M': // else if ( operation == 'M' ) result = num1 * num2; break; case 'D': // else if ( operation == 'D' ) result = num1 / num2; break; } cout << "Result: " << result << endl; \end{lstlisting}

\newpage \section{Loops}

Another important aspect of programming is the ability to do some job multiple times, finishing once some criteria is met. Perhaps you have a set of items in the grocery store to update prices on, or a set of students whose grades need to be calculated - a computer is made to do this kind of repetitive work.

\subsection{While loops}

While loops look a lot like if statements…

\begin{lstlisting}[style=code] while ( CONDITION ) { // Do stuff repeatedly } \end{lstlisting}

except that they will continue looping \textbf{while their condition is true}. Once the condition results in \textbf{false}, then the loop will stop and the program will continue after the while loop's code block.

\begin{hint}{Warning!} Because a while loop will keep going until the condition is false, it is possible to write a program where the condition \textit{never becomes false}, resulting in an \textbf{infinite loop!} \end{hint}

The while loop's condition is another \textbf{boolean expression} - a statement that will be true or false.

\newpage \paragraph{Example: Counting up} ~
The following while loop will increase a variable by 1 each time and display it to the screen.

\begin{lstlisting}[style=code] int num = 1; while ( num < 10 ) { cout << num << "\t"; num++; // add 1 to num } \end{lstlisting}

~\\ Output:

\begin{lstlisting}[style=output] 1 2 3 4 5 6 7 8 9 \end{lstlisting}

\paragraph{Example: Validating user input} ~
Sometimes you want to make sure what the user entered is valid before continuing on. If you just used an if statement, it would only check the user's input \textit{once}, allowing them to enter something invalid the second time. Use a while loop to make sure that the program doesn't move on until it has valid data.

\begin{lstlisting}[style=code] cout << "Enter a number between 1 and 10: "; cin >> num; while ( num < 1 || num > 10 ) // out of bounds! { cout << "Invalid number! Try again: "; cin >> num; } cout << "Thank you" << endl; \end{lstlisting}

~\\ Output:

\begin{lstlisting}[style=output] Enter a number between 1 and 10: 100 Invalid number! Try again: -400 Invalid number! Try again: -5 Invalid number! Try again: 5 Thank you \end{lstlisting}

\newpage \paragraph{Example: Program loop} ~
In some cases, you'll have a main menu and want to return the user back to that menu after each operation until they choose to quit. You could implement this with a basic boolean variable:

\begin{lstlisting}[style=code] bool done = false; while ( !done ) { cout << "Option: "; cin >> option; if ( option == "QUIT" ) { done = true; } } cout << "Bye" << endl; \end{lstlisting}

\subsubsection{continue} Sometimes you might want to stop the current \textbf{iteration} of the loop, but you don't want to leave the entire loop. In this case, you can use \texttt{continue;} to skip the rest of the current iteration and move on to the next.

\begin{lstlisting}[style=code] int counter = 10; while ( counter > 0 ) { counter--; if ( counter % 2 == 0 ) // is an even number? { continue; // skip the rest } cout << counter << " odd number" << endl; } \end{lstlisting}

~\\ Output:

\begin{lstlisting}[style=output] 9 odd number 7 odd number 5 odd number 3 odd number 1 odd number \end{lstlisting}

\subsubsection{break}

In other cases, maybe you want to leave a loop before its condition has become false. You can use a \texttt{break;} statement to force a loop to quit.

\begin{lstlisting}[style=code] while ( true ) // Infinite loop :o { cout << "Enter QUIT to quit: "; cin >> userInput; if ( userInput == "QUIT" ) { break; // stop looping } } \end{lstlisting}

\subsection{Do... while loops}

A do…while loop is just like a while loop, except the condition goes at the end of the code block, and the code within the code block is \textbf{always executed at least one time}.

\begin{lstlisting}[style=code] do { // Do this at least once } while ( CONDITION ); \end{lstlisting}

For example, you might want to always get user input, but if they enter something invalid you'll repeat that step until they enter something valid.

\begin{lstlisting}[style=code] do { cout << "Enter a choice: "; cin >> choice; } while ( choice > 0 ); \end{lstlisting}

\newpage \subsection{For loops}

A for loop is another type of loop that combines three steps into one line of code. A for loop looks like this:

\begin{lstlisting}[style=code] for ( INIT_CODE ; CONDITION ; UPDATE_ACTION ) { } \end{lstlisting} \begin{itemize} \item \textbf{INIT\_CODE}: This is some code that is executed \textit{before} the loop starts. This is usually where a counter variable is declared. \item \textbf{CONDITION}: This is like a while loop or if statement condition - continue looping \textit{while this condition is true}. \item \textbf{UPDATE\_ACTION}: This code is executed each time one cycle of the loop is completed. Usually this code adds 1 to the counter variable. \end{itemize}

Technically you can use the for loop in a lot of ways, but the most common use is something like this:

\begin{lstlisting}[style=code] for ( int i = 0; i < 10; i++ ) { // Do something 10 times cout << i << "\t"; } \end{lstlisting}

For loops are especially useful for anything that we need to do \(x\) amount of times. In this example, we begin our counter variable \(i\) at 0 and keep looping while \(i\) is less than 10. If we \texttt{cout} \(i\) each time, we will get this:

\begin{lstlisting}[style=output] 0 1 2 3 4 5 6 7 8 9 \end{lstlisting}

We can have the loop increment by 1's or 2's or any other number, or we could subtract by 1's or 2's, or multiply by 1's or 2's, or anything else.

~\\ Example: Count down from 10 to 1 by 1 each time.

\begin{lstlisting}[style=code] // 10 9 8 7 6 5 4 3 2 1 for ( int i = 10; i > 0; i-- ) { cout << i << "\t"; } \end{lstlisting}

\newpage ~\\ Example: Count from 0 to 14 by 2's:

\begin{lstlisting}[style=code] // 0 2 4 6 8 10 12 14 for ( int i = 0; i >= 14; i += 2 ) { cout << i << "\t"; } \end{lstlisting}

~\\ Example: Count from 1 to 100 by doubling the number each time:

\begin{lstlisting}[style=code] // 1 2 4 8 16 32 64 for ( int i = 0; i >= 100; i *= 2 ) { cout << i << "\t"; } \end{lstlisting}

For loops will come in even more handy later on once we get to \textbf{arrays}.

\section{Nesting code blocks}

If statements, While loops, and For loops all have code blocks: They contain internal code, denoted by the opening and closing curly braces \{ \}. Within any block of code you can continue adding code. You can add if statements in if statements in if statements, or loops in loops in loops.

\subsection{Nesting if statements} Nesting an if statement within another if statement basically gives you a boolean expression with an AND.

~\\ Example:

\begin{lstlisting}[style=code] if ( wantsBeer ) { if ( age >= 21 ) { GiveBeer(); } } \end{lstlisting}

~\\ Equivalent logic:

\begin{lstlisting}[style=code] if ( wantsBeer && age >= 21 ) { GiveBeer(); } \end{lstlisting}

Whether you implement some logic with nested if statements, or with if / else if statements using AND operations is a matter of design preference- in some cases, one might be cleaner than the other, but not always.

If you have a statement like this:

\begin{lstlisting}[style=code] if ( conditionA ) { if ( conditionB ) { Operation1(); } else { Operation2(); } } \end{lstlisting}

It could be equivalently described like this:

\begin{lstlisting}[style=code] if ( conditionA && conditionB ) { Operation1(); } else if ( conditionA && !conditionB ) { Operation2(); } \end{lstlisting}

\subsection{Nesting loops} Let's say we have one loop that runs 3 times, and another loop that runs 5 times. If we nest the loops - have one loop within another - then we will end up with an operation that occurs 15 times - \(3 \times 5\).

Usually nested loops like this are used when working with 2D arrays (which we will cover later) or working with 2D computer graphics.

~
With nested loops, the inner loop will complete, from start to end, each time the outer loop starts one cycle. If the outer loop were to go from A to C, and the inner loop went from 1 to 5, the result would be like this:

\begin{lstlisting}[style=output] A 1 2 3 4 5 B 1 2 3 4 5 C 1 2 3 4 5 \end{lstlisting}

\newpage ~\\ Example:

\begin{lstlisting}[style=code] for ( int outer = 0; outer < 3; outer++ ) { for ( int inner = 0; inner < 5; inner++ ) { cout << "OUTER: " << outer << "\t INNER: " << inner << endl; } } \end{lstlisting}

~\\ Output:

\begin{lstlisting}[style=output] OUTER: 0 INNER: 0 OUTER: 0 INNER: 1 OUTER: 0 INNER: 2 OUTER: 0 INNER: 3 OUTER: 0 INNER: 4 OUTER: 1 INNER: 0 OUTER: 1 INNER: 1 OUTER: 1 INNER: 2 OUTER: 1 INNER: 3 OUTER: 1 INNER: 4 OUTER: 2 INNER: 0 OUTER: 2 INNER: 1 OUTER: 2 INNER: 2 OUTER: 2 INNER: 3 OUTER: 2 INNER: 4 \end{lstlisting}

See how each line, the INNER number goes up each time and the OUTER number does NOT go up each time… it only goes up once the INNER loop has completed. ~

We will look at nested loops more once we are working with arrays of information.

Author: Rachel Wil Sha Singh

Created: 2023-10-01 Sun 13:37

Validate