<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Cole Challand on Medium]]></title>
        <description><![CDATA[Stories by Cole Challand on Medium]]></description>
        <link>https://medium.com/@ctchalland?source=rss-973d9b175e70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r-DNurd-LagYBC06WRGgDQ.jpeg</url>
            <title>Stories by Cole Challand on Medium</title>
            <link>https://medium.com/@ctchalland?source=rss-973d9b175e70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 24 May 2026 04:26:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ctchalland/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Writing Data to Files]]></title>
            <link>https://medium.com/@ctchalland/files-b75bb27606e6?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/b75bb27606e6</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Sun, 26 Nov 2017 20:09:53 GMT</pubDate>
            <atom:updated>2017-11-27T19:44:17.780Z</atom:updated>
            <content:encoded><![CDATA[<p>The programs you have written so far require the user to reenter data each time the program runs, because data kept in variables and control properties are stored in RAM and disappears once the program stops running. If a program is to retain data between the times it runs, it must have a way of saving it. Data is saved in a file, which is usually stored on a computer’s disk. Once the data is saved in a file, it will remain there after the program stops running. Data that is stored in a file can be then retrieved and used at a later time. Programmers usually refer to the process of saving data in a file as <em>writing data </em>to the file. When a piece of data is written to a file, it is copied from a variable in RAM to the file. The process of retrieving data from a file is known as <em>reading data </em>from the file. When a piece of data is read from a file, it is copied from the file into a variable in RAM.</p><p>There’s three ways to create programs that write data to files and read data from files. When a file is used by a program, three steps must be taken.</p><ol><li><strong>Open the file — </strong>Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the disk and allows the program to write data to it. Opening an input file allows the program to read data from the file.</li><li><strong>Process the file — </strong>Data is either written to the file (if it is an output file) or read from the file (if it is an input file).</li><li><strong>Close the file — </strong>After the program is finished using the file, the file must be closed. Closing a file disconnects the file from the program.</li></ol><h4>File Access Methods</h4><p>There are two general ways to access data stored in a file: <em>sequential access</em> and <em>direct access</em>. When you work with a <em>sequential access file</em>, you access data from the beginning of the file to the end of the file. If you want to read a piece of data that is stored at the very end of the file, you have to read all of the data that comes before it — you cannot jump directly to the desired data. This is similar to the way cassette tape players work. If you want to listen to the last song on a cassette tape, you have to either fast-forward over all of the songs that come before it or listen to them. There is no way to jump directly to a specific song.</p><p>When you work with a <em>random access file </em>(also known as a <em>direct access file</em>), you can jump directly to any piece of data in the file without reading the data that comes before it. This is similar to the way a CD player or an MP3 player works. You can jump directly to any song that you want to listen to.</p><p>In order for a program to work with a file on the computer’s disk, the program must create a <em>file stream object</em> in memory. A <em>file stream object </em>is an object that is associated with a specific file and provides a way for the program to work with that file. It is called a “stream” object because a file can be thought of as a stream of data.</p><p><em>File stream objects</em> work very much like the cin and cout objects. A stream of data may be sent to cout, which causes values to be displayed on the screen. A stream of data may be read from the keyboard by cin, and stored in variables. Likewise, streams of data may be sent to a <em>file stream object</em>, which writes the data to a file. When data is read from a file, the data flows from the <em>file stream object</em> that is associated with the file, into variables.</p><h4>Setting Up a Program for File Input/Output</h4><p>Just as cin and cout require the iostream file to be included in the program, C++ file access requires another header file. The file fstream contains all the declarations necessary for file operations. It is included with the following statement:</p><p>#include &lt;fstream&gt;</p><p>The fstream header file defines the data types ofstream, ifstream, and fstream. Before a C++ program can work with a file, it must define an object of one of these data types. The object will be “linked” with an actual file on the computer’s disk, and the operations that may be performed on the file depend on which of these three data types you pick for the file stream object. Table below lists and describes the file stream data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PiWbX3FDQnGywx8JcuYOVw.png" /></figure><h4><strong>Creating a File Object and Opening a File</strong></h4><p>Before data can be written to or read from a file, the following things must happen:</p><ul><li>A file stream object must be created</li><li>The file must be opened and linked to the file stream object.</li></ul><p>The following code shows an example of opening a file for input (reading).</p><pre>ifstream inputFile;<br>inputFile.open(“Customers.txt”);</pre><p>The first statement defines an ifstream object named inputFile. The second statement calls the object’s open member function, passing the string “Customers.txt” as an argument. In this statement, the open member function opens the Customers.txt file and links it with the inputFile object. After this code executes, you will be able to use the inputFile object to read data from the Customers.txt file.</p><p>The following code shows an example of opening a file for output (writing).</p><pre>ofstream outputFile;<br>outputFile.open(“Employees.txt”);</pre><p>The first statement defines an ofstream object named outputFile. The second statement calls the object’s open member function, passing the string “Employees.txt” as an argument. In this statement, the open member function creates the Employees.txt file and links it with the outputFile object. After this code executes, you will be able to use the outputFile object to write data to the Employees.txt file. It’s important to remember that when you call an ofstream object’s open member function, the specified file will be created. If the specified file already exists, it will be erased, and a new file with the same name will be created.</p><p>It is possible to define a <em>file stream object</em> and open a file in one statement. Here is an example:</p><p>ifstream inputFile(“Customers.txt”);</p><p>This statement defines an ifstream object named inputFile and opens the Customer.txt file. Here is an example that defines an ofstream object named outputFile and opens the Employees.txt file:</p><p>ofstream outputFile(“Employees.txt”);</p><h4><strong>Closing a File</strong></h4><p>The opposite of opening a file is closing it. Although a program’s files are automatically closed when the program shuts down, it is a good programming practice to write statements that close them. Here are two reasons a program should close files when it is finished using them:</p><ul><li>Most operating systems temporarily store data in a <em>file buffer </em>before it is written to a file. A file buffer is a small “holding section” of memory that file-bound data is first written to. When the buffer is filled, all the data stored there is written to the file. This technique improves the system’s performance. Closing a file causes any unsaved data that may still be held in a buffer to be saved to its file. This means the data will be in the file if you need to read it later in the same program.</li><li>Some operating systems limit the number of files that may be open at one time. When a program closes files that are no longer being used, it will not deplete more of the operating system’s resources than necessary.</li></ul><p>Calling the <em>file stream object</em>’s close member function closes a file. Here is an example:</p><p>inputFile.close();</p><h4><strong>Writing Data to a File</strong></h4><p>The program demonstrates an example that reads strings as input from the keyboard and then writes those strings to a file. The program asks the user to enter the first names of three friends, and then it writes those names to a file named Friends.txt. After this code has executed, we can open the Friends.txt file using a text editor and look at its contents.</p><pre>// This program writes user input to a file.<br>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;string&gt;<br>using namespace std;</pre><pre>int main()<br>{<br>    ofstream outputFile;<br>    string name1, name2, name3;</pre><pre>// Open an outputFile;<br>    outputFile.open(&quot;Friends.txt&quot;);</pre><pre>// Get the names of three friends.<br>    cout &lt;&lt; &quot;Enter the names of three friends.\n&quot;;<br>    cout &lt;&lt; &quot;Frind #1: &quot;;<br>    cin &gt;&gt; name1;<br>    cout &lt;&lt; &quot;Frind #2: &quot;;<br>    cin &gt;&gt; name2;<br>    cout &lt;&lt; &quot;Frind #3: &quot;;<br>    cin &gt;&gt; name3;</pre><pre>// Where the names to the file.<br>    outputFile &lt;&lt; name1 &lt;&lt; endl;<br>    outputFile &lt;&lt; name2 &lt;&lt; endl;<br>    outputFile &lt;&lt; name3 &lt;&lt; endl;<br>    cout &lt;&lt; &quot;The names were saved to a file.\n&quot;;</pre><pre>// Close the file<br>    outputFile.close();<br>    return 0;<br>}</pre><h4>Reading Data from a File</h4><p>The &gt;&gt; operator not only reads user input from the cin object, but also data from a file. Assuming inputFile is an ifstream object, the following statement shows the &gt;&gt; operator reading data from the file into the variable name:</p><pre>inputFile &gt;&gt; name;</pre><p>Let’s look at an example. The program below assumes the file Friends.txt exists, opens the file, reads the names and displays them on the screen, and then closes the file.</p><pre>// This program reads data from a file.<br>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br>#include &lt;string&gt;<br>using namespace std;</pre><pre>int main()<br>{<br>    ifstream inputFile;<br>    string name;</pre><pre>inputFile.open(&quot;Friends.txt&quot;);<br>    cout &lt;&lt; &quot;Reading data from the file.\n&quot;;</pre><pre>inputFile &gt;&gt; name;          // Read name 1 from the line<br>    cout &lt;&lt; name &lt;&lt; endl;       // Display name 1</pre><pre>inputFile &gt;&gt; name;          // Read name 2 from the line<br>    cout &lt;&lt; name &lt;&lt; endl;       // Display name 2</pre><pre>inputFile &gt;&gt; name;          // Read name 3 from the line<br>    cout &lt;&lt; name &lt;&lt; endl;       // Display name 3</pre><pre>inputFile.close();          // Close the file<br>    return 0;<br>}</pre><h4><strong>Using Loops to Process Files</strong></h4><p>Although some programs use files to store only small amounts of data, files are typically used to hold large collections of data. When a program uses a file to write or read a large amount of data, a loop is typically involved.</p><p>Quite often a program must read the contents of a file without knowing the number of items that are stored in the file. For example, suppose you need to write a program that displays all of the items in a file, but you do not know how many items the file contains. You can open the file and then use a loop to repeatedly read an item from the file and display it. However, an error will occur if the program attempts to read beyond the end of the file. The program needs some way of knowing when the end of the file has been reached so it will not try to read beyond it.</p><p>Fortunately, the &gt;&gt; operator not only reads data from a file, but also returns a true or false value indicating whether the data was successfully read or not. If the operator returns true, then a value was successfully read. If the operator returns false, it means that no value was read from the file.</p><p>There is a way to determine whether the open member function successfully opened the file. After you call the open member function, you can test the file stream object as if it were a Boolean expression.</p><p>In each of the previous examples, the name of the file that is opened is hard-coded as a 11 string literal into the program. In many cases, you will want the user to specify the name of a file for the program to open. In C++ 11, you can pass a string object as an argument to a file stream object’s open member function.</p><p>The program below shows an example. This version prompts the user to enter the name of the file. In line 15, the name that the user enters is stored in a string object named filename. In line 18, the filename object is passed as an argument to the open function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23c1df3b992a2a6c0dab36cdd5b060bf/href">https://medium.com/media/23c1df3b992a2a6c0dab36cdd5b060bf/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b75bb27606e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which Loops to Choose]]></title>
            <link>https://medium.com/@ctchalland/which-loops-to-choose-edfc38afb558?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/edfc38afb558</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[cpp11]]></category>
            <category><![CDATA[loop]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Tue, 21 Nov 2017 05:18:15 GMT</pubDate>
            <atom:updated>2017-11-23T06:21:49.639Z</atom:updated>
            <content:encoded><![CDATA[<p>In previous post, we went over the concept of control structures, which direct the flow of a program. <em>A loop </em>is a control structure that causes a statement or group of statements to repeat. C++ has three looping control structures: the <em>while</em> loop, the <em>do-while</em> loop, and the <em>for</em> loop. The difference between these structures is how they control the repetition.</p><p><strong>The <em>while</em> Loop</strong></p><p>The while loop has two important parts: (1) an expression that is tested for a true or false value, and (2) a statement or block that is repeated as long as the expression is true. The figure below shows the logic of a while loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SY7flg4GidEH-UZrsmjHg.png" /></figure><p>Here is the general structure of the <em>while</em> loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4k4FJPqIt0tQx9SA6aDMFg.png" /></figure><p>In the general format, (expression)<em> </em>is any expression that can be evaluated as true or false, and statement;<em> </em>is any valid C++ statement. The first line shown in the figure above is called the <em>loop header</em>. It consists of the key word while followed by an <em>expression </em>enclosed in parentheses. Here’s how the loop works: the (expression)<em> </em>is tested, and if it is true, the <em>statement(s) are </em>executed. Then, the (expression)<em> </em>is tested again. If it is true, the <em>statement(s) </em>are<em> </em>executed. This cycle repeats until the (expression)<em> </em>is false. The <em>statement(s)</em> that is repeated is known as the <em>body </em>of the loop. The <em>while</em> loop works like an <em>if</em> statement that executes over and over. As long as the <em>expression</em> inside the parentheses is true, the <em>body </em>of the loop will repeat. The program below uses the while loop to print “Hello” five times.</p><pre>// This program demonstrates a simple while loop.<br>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>int main()<br>{<br>    int number = 0;</pre><pre>while (number &lt; 5)<br>    {<br>        cout &lt;&lt; &quot;Hello\n&quot;;<br>        number++;<br>    }<br>    cout &lt;&lt; &quot;That&#39;s all!\n&quot;;<br>    return 0;<br>}</pre><p>This program tests the variable number to determine whether it is less than 5. If it is, then the statements in the <em>body</em> of the loop are executed. The statement number++; in the <em>body</em> of the loop uses the increment operator to add one to number. This is the last statement in the <em>body</em> of the loop, so after it executes, the loop starts over. It tests the expression (number &lt; 5) again, and if it is true, the statements in the <em>body</em> of the loop are executed again. This cycle repeats until the expression (number &lt; 5) is false. Each repetition of a loop is known as an <em>iteration</em>. This loop will perform five iterations because the variable number is initialized with the value 0, and it is incremented each time the <em>body</em> of the loop is executed. When the expression (number &lt; 5) is tested and found to be false, the loop will terminate and the program will resume execution at the statement that immediately follows the loop. The figure below shows the logic of this loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOb57Bw2kcl_HCW5VhYbWg.png" /></figure><p>In this example, the number variable is referred to as the <em>loop control variable </em>because it controls the number of times that the loop iterates. The while loop is known as a <em>pretest </em>loop, which means it tests its expression before each iteration.</p><p><strong>Infinite Loops</strong></p><p>Loops must contain within themselves a way to terminate. This means that something inside the loop must eventually make the test expression false. The loop in the example above stops when the expression (number &lt; 5) is false. If a loop does not have a way of stopping, it is called an infinite loop. An <em>infinite loop </em>continues to repeat until the program is interrupted. Here is an example of an infinite loop:</p><pre>int number = 0;<br>while (number &lt; 5)<br>{<br>    cout &lt;&lt; &quot;Hello\n&quot;;<br>}</pre><p>This is an <em>infinite loop</em> because it does not contain a statement that changes the value of the number variable. Each time the expression (number &lt; 5) is tested, number will contain the value 0. It’s also possible to create an infinite loop by accidentally placing a semicolon after the first line of the while loop.</p><pre>int number = 0;<br>while (number &lt; 5)<br>{<br>    cout &lt;&lt; &quot;Hello\n&quot;;  // This semicolon is an ERROR!<br>    number++<br>}</pre><p>The semicolon at the end of the first line is assumed to be a null statement and disconnects the while statement from the block that comes after it. To the compiler, this loop looks like:</p><pre>while (number &lt; 5);</pre><p>This while loop will forever execute the null statement, which does nothing. The program will appear to have “gone into space” because there is nothing to display screen output or show activity.</p><p><strong>The <em>do-while</em> Loop</strong></p><p>The <em>do-while </em>loop looks something like an inverted while loop. The figure below shows the logic of a <em>do-while</em> loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIrLk0AWKaiHND6OvMGq2Q.png" /></figure><p>Here is the <em>do-while</em> loop’s structure when the body of the loop contains multiple statements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*ElQZ24hzsAmUT8grWxTajg.png" /></figure><p>The do-while loop is a <em>posttest </em>loop. This means it does not test its expression until it has completed an iteration. As a result, the do-while loop always performs at least one iteration, even if the expression is false to begin with. This differs from the behavior of a while loop, which you will recall is a pretest loop.</p><p><strong>The <em>for</em> Loop</strong></p><p>In general, there are two categories of loops: conditional loops and count-controlled loops. A <em>conditional loop </em>executes as long as a particular condition exists. For example, an input validation loop executes as long as the input value is invalid. When you write a conditional loop, you have no way of knowing the number of times it will iterate.</p><p>Sometimes you know the exact number of iterations that a loop must perform. A loop that repeats a specific number of times is known as a <em>count-controlled </em>loop. For example, if a loop asks the user to enter the sales amounts for each month in the year, it will iterate twelve times. In essence, the loop counts to twelve and asks the user to enter a sales amount each time it makes a count. A count-controlled loop must possess three elements:</p><ol><li>It must initialize a counter variable to a starting value.</li><li>It must test the counter variable by comparing it to a maximum value. When the counter variable reaches its maximum value, the loop terminates.</li><li>It must update the counter variable during each iteration. This is usually done by incrementing the variable.</li></ol><p>Count-controlled loops are so common that C++ provides a type of loop specifically for them. It is known as the for loop. The <em>for</em> loop is specifically designed to initialize, test, and update a counter variable. Here is the format of the for loop when it is used to repeat a block is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*5R9LzBw8w00ocEgpYVcI8g.png" /></figure><p>The first line of the for loop is the <em>loop header</em>. After the key word for, there are three expressions inside the parentheses, separated by semicolons. (Notice there is not a semi- colon after the third expression.) The first expression is the <em>initialization expression</em>. It is normally used to initialize a counter variable to its starting value. This is the first action performed by the loop, and it is only done once. The second expression is the <em>test expression</em>. This is an expression that controls the execution of the loop. As long as this expression is true, the body of the for loop will repeat. The for loop is a pretest loop, so it evaluates the test expression before each iteration. The third expression is the <em>update expression</em>. It executes at the end of each iteration. Typically, this is a statement that increments the loop’s counter variable.</p><p>Here is an example of a simple for loop that prints “Hello” five times:</p><pre>for (int count = 0; count &lt; 5; count++)<br>{<br>    cout &lt;&lt; &quot;Hello&quot; &lt;&lt; endl;<br>}</pre><p>In this loop, the initialization expression is count = 0, the test expression is count &lt; 5, and the update expression is count++. The <em>body</em> of the loop has one statement, which is the cout statement. Figure below illustrates the sequence of events that takes place during the loop’s execution. Notice that Steps 2 through 4 are repeated as long as the test expression is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKiWGwA34sla4JKoNPG2-Q.png" /></figure><p>Notice how the counter variable, count, is used to control the number of times that the loop iterates. During the execution of the loop, this variable takes on the values 1 through 5, and when the test expression count &lt; 5 is false, the loop terminates. Also notice that in this example the count variable is used only in the <em>loop header</em>, to control the number of loop iterations. It is not used for any other purpose. It is also possible to use the counter variable within the body of the loop. Because the <em>for</em> loop tests its test expression before it performs an iteration, it is a pretest loop.</p><h3><strong>Deciding Which Loop to Use</strong></h3><p>Each of the three C++ loops is ideal to use in different situations. Here’s a short summary of when each loop should be used.</p><ul><li><strong>The <em>while</em> loop. </strong>The <em>while</em> loop is a conditional loop, which means it repeats as long as a particular condition exists. It is also a pretest loop, so it is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. For example, validating input that has been read and reading lists of data terminated by a sentinel value are good applications of the while loop.</li><li><strong>The <em>do-while</em> loop. </strong>The <em>do-while</em> loop is also a conditional loop. Unlike the <em>while</em> loop, however, <em>do-while</em> is a posttest loop. It is ideal in situations where you always want the loop to iterate at least once. The <em>do-while</em> loop is a good choice for repeating a menu.</li><li><strong>The <em>for</em> loop. </strong>The <em>for</em> loop is a pretest loop that has built-in expressions for initializing, testing, and updating. These expressions make it very convenient to use a counter variable to control the number of iterations that the loop performs. The initialization expression can initialize the counter variable to a starting value, the test expression can test the counter variable to determine whether it holds the maximum value, and the update expression can increment the counter variable. The for loop is ideal in situations where the exact number of iterations is known.</li></ul><h3><strong>Optional Topics: Breaking and Continuing a Loop</strong></h3><p>Sometimes it’s necessary to stop a loop before it goes through all its iterations. The break statement, which was used with switch in Chapter 4, can also be placed inside a loop. When it is encountered, the loop stops, and the program jumps to the statement immediately following the loop.</p><p>The while loop in the following program segment appears to execute 10 times, but the break statement causes it to stop after the fifth iteration.</p><pre>int count = 0;<br>while (count++ &lt; 10) <br>{<br>    cout &lt;&lt; count &lt;&lt; endl;<br>    if (count == 5)<br>        break;<br>}</pre><p><strong>Using <em>break</em> in a Nested Loop</strong></p><p>In a nested loop, the break statement only interrupts the loop it is placed in. The following program segment displays five rows of asterisks on the screen. The outer loop controls the number of rows, and the inner loop controls the number of asterisks in each row. The inner loop is designed to display 20 asterisks, but the break statement stops it during the eleventh iteration.</p><pre>for (int row = 0; row &lt; 5; row++) <br>{<br>    for (int star = 0; star &lt; 20; star++)<br>    {<br>        cout &lt;&lt; ‘*’;<br>        if (star == 10)<br>            break;<br>    }<br>    cout &lt;&lt; endl;<br>}</pre><p><strong>The <em>continue</em> Statement</strong></p><p>The continue statement causes the current iteration of a loop to end immediately. When continue is encountered, all the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.</p><p>In a while loop, this means the program jumps to the test expression at the top of the loop. As usual, if the expression is still true, the next iteration begins. In a do-while loop, the program jumps to the test expression at the bottom of the loop, which determines whether the next iteration will begin. In a for loop, continue causes the update expression to be executed and then the test expression to be evaluated.</p><p>The following program segment demonstrates the use of continue in a while loop:</p><pre>int testVal = 0;<br>while (testVal++ &lt; 10)<br>{<br>    if (testVal == 4) <br>        continue;<br>    cout &lt;&lt; testVal &lt;&lt; “ “;<br>}</pre><p>This loop looks like it displays the integers 1 through 10. When testVal is equal to 4, however, the continue statement causes the loop to skip the cout statement and begin the next iteration. The output of the loop is</p><p>1 2 3 5 6 7 8 9 10</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edfc38afb558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[To Execute or To Not Execute]]></title>
            <link>https://medium.com/@ctchalland/to-execute-or-to-not-execute-6f072ad6be27?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f072ad6be27</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[conditional]]></category>
            <category><![CDATA[relational-expressions]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Sat, 18 Nov 2017 19:43:57 GMT</pubDate>
            <atom:updated>2017-11-18T19:43:57.180Z</atom:updated>
            <content:encoded><![CDATA[<p>If you can’t tell by the subtle hint in the title, this post is about conditionals. In the previous post, we talked about true states, false states, and how the relational expressions are evaluated. How they’re evaluated is important when using if/else statements, if/else if statements, <em>conditional</em> operator, and <em>switch</em> statements in programming.</p><p><strong>The <em>if</em>/<em>else</em> Statement</strong></p><p>The <em>if</em>/<em>else</em> statement will execute one group of statements if the expression is true, or another group of statements if the expression is false. The <em>if</em>/<em>else</em> statement is an expansion of the <em>if</em> statement. Here is its format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*kTiR-cvY6XdOb75QWOYZ9Q.png" /></figure><p>If the (expression) is true, a statement or block of statements is executed. If the (expression) is false, a separate group of statements is executed. Note that the program will only take one of the two paths in the <em>if</em>/<em>else</em> statement. If you think of the statements in a computer program as steps taken down a road, consider the <em>if</em>/<em>else</em> statement as a fork in the road. Instead of being a temporary detour, like an <em>if</em> statement, the <em>if</em>/<em>else</em> statement causes program execution to follow one of two exclusive paths.</p><p><strong>Nested <em>if</em> statements</strong></p><p>To test more than one condition, an <em>if</em> statement can be nested inside another <em>if</em> statement. Sometimes an <em>if</em> statement must be nested inside another <em>if</em> statement. For example, consider a banking program that determines whether a bank customer qualifies for a special, low interest rate on a loan. To qualify, two conditions must exist: (1) the customer must be currently employed, and (2) the customer must have recently graduated from college. The figure blow show’s how a nested <em>if </em>statement would be coded for the banking program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dkri1KJsl_l06V2TvgEVQ.png" /></figure><p><strong>The <em>if</em>/<em>else if</em> Statement</strong></p><p>The <em>if</em>/<em>else if</em> statement tests a series of conditions. It is often simpler to test a series of conditions with the <em>if</em>/<em>else if</em> statement than with a set of nested <em>if</em>/<em>else</em> statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEb17fQue5-xG6KdnrLgQw.png" /></figure><p>When the statement executes, (expression_1)<em> </em>is tested. If (expression_1)<em> </em>is true, the block of statements that immediately follows is executed, and the rest of the structure is ignored. If (expression_1)<em> </em>is false, the program jumps to the very next <em>else if</em> clause and tests (expression_2). If it is true, the block of statements that immediately follows is executed, and then the rest of the structure is ignored. This process continues, from the top of the structure to the bottom, until one of the expressions is found to be true. If none of the expressions are true, the last else clause takes over, and the block of statements immediately following it is executed. The last else clause is referred to as the <em>trailing else</em>. The <em>trailing</em> <em>else</em> clause, which appears at the end of the <em>if</em>/<em>else if</em> statement, is optional, but in many situations you will use it to catch errors.</p><p><strong>The <em>if</em>/<em>else if</em> Statement Compared to a Nested <em>if</em> Statement</strong></p><p>You never have to use the <em>if</em>/<em>else if</em> statement because its logic can be coded with nested <em>if</em>/<em>else</em> statements. However, a long series of nested <em>if</em>/<em>else</em> statements has two particular disadvantages when you are debugging code:</p><ul><li>The code can grow complex and become difficult to understand.</li><li>Because indenting is important in nested statements, a long series of nested <em>if</em>/<em>else</em> statements can become too long to be displayed on the computer screen without horizontal scrolling. Also, long statements tend to “wrap around” when printed on paper, making the code even more difficult to read.</li></ul><p>The logic of an <em>if</em>/<em>else if </em>statement is usually easier to follow than that of a long series of nested <em>if</em>/<em>else</em> statements. And, because all of the clauses are aligned in an <em>if</em>/<em>else if</em> statement, the lengths of the lines in the statement tend to be shorter.</p><p><strong>The <em>Conditional</em> Operator</strong></p><p>You can use the <em>conditional</em> operator to create short expressions that work like <em>if</em>/<em>else</em> statements. The conditional operator is powerful and unique. It provides a shorthand method of expressing a simple <em>if</em>/<em>else</em> statement. The operator consists of the question-mark (?) and the colon (:). Its format is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*cRRm88iDHF_Y-9mrHSQWLw.png" /></figure><p>Here is an example of a statement using the <em>conditional</em> operator:</p><pre>x &lt; 0 ? y = 10 : z = 20;</pre><p>The <em>conditional</em> expression above performs the same operation as the following <em>if</em>/<em>else</em> statement:</p><pre>if (x &lt; 0)<br>  y = 10;<br>else<br>  z = 20;</pre><p>The part of the <em>conditional</em> expression that comes before the question mark is the expression to be tested. It’s like the expression in the parentheses of an <em>if</em> statement. If the expression is true, the part of the statement between the ? and the : is executed. Otherwise, the part after the : is executed. Figure below illustrates the roles played by the three sub-expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4vgmgpXKNW6SPWWJSu3Eg.png" /></figure><p>If it helps, you can put parentheses around the sub-expressions, as in the following:</p><pre>(x &lt; 0) ? (y = 10) : (z = 20);</pre><p><strong>The <em>switch</em> Statement</strong></p><p>The <em>switch</em> statement lets the value of a variable or expression determine where the program will branch. A branch occurs when one part of a program causes another part to execute. The <em>if</em>/<em>else if</em> statement allows your program to branch into one of several possible paths. It performs a series of tests (usually relational) and branches when one of these tests is true. The <em>switch</em> statement is a similar mechanism. It tests the value of an integer expression and then uses that value to determine which set of statements to branch to. Here’s the structure of the <em>switch</em> statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5e3LrJq43vT3eA0OGbyIPQ.png" /></figure><p>The first line of the statement starts with the word switch, followed by an integer expression inside parentheses. This can be either of the following:</p><ul><li>a variable of any of the integer data types (including char)</li><li>an expression whose value is of any of the integer data types</li></ul><p>On the next line is the beginning of a block containing several <em>case</em> statements. After the word case, is a constant expression followed by a colon. The constant expression may be an integer value or an integer named constant. The <em>case</em> statement marks the beginning of a section of statements. The program branches to these statements if the value of the <em>switch</em> expression matches that of the <em>case</em> expression. An optional <em>default</em> section comes after all the <em>case</em> statements. The program branches to this section if none of the <em>case</em> expressions match the <em>switch</em> expression. So, the <em>defaults </em>section is like a <em>trailing else</em> in an <em>if</em>/<em>else if</em> statement.</p><p>Here is an example of a <em>switch</em> statement:</p><pre>// The switch statement in this program tells the user the data just<br>// entered<br>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>int main()<br>{<br>    char choice;</pre><pre>cout &lt;&lt; &quot;Enter A, B, or C: &quot;;<br>    cin &gt;&gt; choice;<br>    switch (choice)<br>    {<br>        case &#39;a&#39;:<br>        case &#39;A&#39;: cout &lt;&lt; &quot;You entered A.\n&quot;;<br>                  break;<br>        case &#39;b&#39;:<br>        case &#39;B&#39;: cout &lt;&lt; &quot;You entered B.\n&quot;;<br>                  break;<br>        case &#39;c&#39;:<br>        case &#39;C&#39;: cout &lt;&lt; &quot;You entered C.\n&quot;;<br>                  break;<br>        default:  cout &lt;&lt; &quot;You did not enter A, B, or C!\n&quot;;<br>    }<br>    return 0;<br>}</pre><p>The case statements show the program where to start executing in the block and the break statements show the program where to stop. Without the break statements, the program would execute all of the lines from the matching case statement to the end of the block.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f072ad6be27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Want the Truth? You Can’t Handle the Truth!!]]></title>
            <link>https://medium.com/@ctchalland/you-want-the-truth-you-cant-handle-the-truth-f6211eba285f?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6211eba285f</guid>
            <category><![CDATA[turthly]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[boolean]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[if-statements]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Sat, 18 Nov 2017 06:03:37 GMT</pubDate>
            <atom:updated>2017-11-18T06:08:07.443Z</atom:updated>
            <content:encoded><![CDATA[<p>The question “What is truth?” is one you would expect to find in a philosophy book, not in programming text. It’s a good question for us to consider, though. If a relational expression can be either true or false, how are those values represented internally in a program? How does a computer store <em>true </em>in memory? How does it store <em>false</em>?</p><pre>// This program demonstrates values stored in true and false<br>#include &lt;iostream&gt;<br>using namespace std;</pre><pre>int main()<br>{<br>  bool boolValue;<br>  boolValue = true;<br>  cout &lt;&lt; boolValue &lt;&lt; endl;<br>  boolValue = false;<br>  cout &lt;&lt; boolValue &lt;&lt; endl;<br>  return 0;<br>}</pre><p>If you were to demo this program you would see that those two abstract states are converted to numbers. In C++, relational expressions represent true states with the number 1 and false states with the number 0.</p><p>In the world of the if statement, however, the concept of truth is expanded. 0 is still false, but all values other than 0 are considered true. This means that any value, even a negative number, represents true as long as it is not 0. Just as in real life, truth is a complicated thing. Here is a summary of the rules you have seen so far:</p><ul><li>When a relational expression is true it has the value 1.</li><li>When a relational expression is false it has the value 0.</li><li>Any expression that has the value 0 is considered false by the <em>if</em> statement. This includes the <em>bool</em> value <em>false</em>, which is equivalent to 0.</li><li>Any expression that has any value other than 0 is considered true by the <em>if</em> statement. This includes the <em>bool</em> value <em>true</em>, which is equivalent to 1.</li></ul><p>The fact that the if statement considers any nonzero value as true opens many possibilities. Relational expressions are not the only conditions that may be tested. For example, the following <em>if</em> statement in C++ are legal:</p><pre>if (value)<br>  cout &lt;&lt; &quot;It&#39;s True&quot;;</pre><p>The <em>if</em> statement above does not test a relational expression, but rather the contents of a variable. If the variable’s value contains any number other than 0, the message “It’s True” will be displayed. If value is 0, the cout statement will be skipped.</p><pre>if (x + y)<br>  cout &lt;&lt; &quot;It&#39;s True&quot;;</pre><p>In this statement the sum of x and y is tested like any other value in an <em>if </em>statement: if the sum is 0, then it’s false. If the sum is any other values, then it’s true. You may also use the return value of function calls as conditional expressions.</p><pre>if (pow(a, b))<br>  cout &lt;&lt; &quot;It&#39;s True&quot;;</pre><p>This <em>if</em> statement uses the pow function to raise a to the power of b. If the result is anything other than 0, the cout statement is executed. This is a powerful programming technique that you can use for evaluating conditionals as in determining the range of a variable, selecting through menu options, and flagging errors in your program.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6211eba285f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When You Mix Nuts and Bolts: Type Conversion]]></title>
            <link>https://medium.com/@ctchalland/when-you-mix-nuts-and-bolts-type-conversion-c5f4f07e4d83?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f4f07e4d83</guid>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[conversion]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Sat, 18 Nov 2017 01:07:48 GMT</pubDate>
            <atom:updated>2017-11-18T06:06:54.684Z</atom:updated>
            <content:encoded><![CDATA[<p>When an operator’s variables or values are of different data types, C++ will automatically convert them to the same data type. This can affect the result of mathematical expressions and cause subtle errors creeping into your program. Let’s go under the hood and see data type rankings work.</p><p>What happens when an <em>int</em> is multiplied by a <em>float</em>, what data type will the result be? What about a <em>double</em> divided by an <em>int</em>? Is there a way to predict which data type will be assigned to the result? The answer is yes, C++ follows a set of rules when performing mathematical operations on variables of different data types. Just like officers in the military, data types are ranked too. One data type outranks another if it can hold a larger number. For example, a <em>double</em> outranks a <em>float</em>, and a <em>float</em> outranks an <em>int</em>. The table below list the data types in order of their rank, from highest to lowest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*dtzcnl4qp9pKyByUiUbMiw.png" /></figure><p>One exception to the ranking in the table is when an <em>int</em> and a <em>long</em> are the same size. In that case, an <em>unsigned int</em> outranks <em>long</em> because it can hold a higher value. When a value is converted to a higher data type, it’s known as <em>promoted</em>. To <em>demote</em> a value means to convert it to a lower data type. Let’s look at some specific rules that dictate the evaluation of mathematical expressions.</p><p><strong>Rule 1:</strong> <em>chars</em>, <em>shorts</em>, and <em>unsigned shorts</em> are automatically promoted to <em>int</em>.</p><p>You will notice that <em>char</em>, <em>short</em>, and <em>unsigned short</em> do not appear in the table. That’s because anytime they’re used in a mathematical expression, they’re promoted to an <em>int</em>. The only exception to this rule is when an <em>unsigned short </em>holds a value larger than can be held by an <em>int</em>. This can happen on systems where a <em>short</em> is the same size an <em>int</em>. In this case, the <em>unsigned short</em> is promoted to <em>unsigned int</em>.</p><p><strong>Rule 2:</strong> When an operator works with two different data types, the lower-ranking value is promoted to the type of the higher-ranking value.</p><p>In the following expression, assume that <em>length </em>is an <em>int</em> and <em>width</em> is a <em>float</em>:</p><pre>length * width</pre><p>Before the multiplication take place, <em>length</em> will be promoted to a float.</p><p><strong>Rule 3: </strong>When the final value of an expression is assigned to a variable, it will be converted to the data type of that variable.</p><p>In the following statement, assume that <em>area</em> is a <em>double</em>, while <em>length</em> and <em>width</em> are both <em>float</em>s:</p><pre>area = length * width</pre><p>Since <em>length</em> and <em>width</em> are both <em>float</em>s but area is a <em>double</em>, the result from the multiplication will be convert to a <em>double</em> because <em>area</em> was initialized as a <em>double</em>.</p><p>Watch out for situations where an expression results in a fractional value being assigned to an integer variable. Here is an example:</p><pre>int x, y = 4; <br>float z = 2.7; <br>x = y * z;</pre><p>In the expression y * z, y will be promoted to <em>float</em> and 10.8 will be the result from the multiplication. Since x is an integer, however, 10.8 will be truncated and 10 will be stored in x.</p><p>When you divide an integer by another integer in C++, the result is always an integer. If there is a remainder, it will be discarded. For example, in the following code, parts is assigned the value 2.0:</p><pre>double parts;<br>parts = 15 / 6;</pre><p>Even though 15 divided by 6 is really 2.5, the .5 part of the result is discarded because we are dividing an integer by an integer. It doesn’t matter that parts was initialized as a <em>double</em> because the decimal part of the result was discarded before the result was assigned to parts. In order for a division operation to return a floating-point value, at least one of the values must be a floating-point data type. For example, the previous code could be written as:</p><pre>double parts; <br>parts = 15.0 / 6;</pre><p>In this code the value 15.0 is interpreted as a floating-point number, so the division operation will return a floating-point number. The value 2.5 will be assigned to parts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f4f07e4d83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ST3 keyboard shortcuts]]></title>
            <link>https://medium.com/@ctchalland/my-blog-post-191f893e0641?source=rss-973d9b175e70------2</link>
            <guid isPermaLink="false">https://medium.com/p/191f893e0641</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[sublimetext]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <dc:creator><![CDATA[Cole Challand]]></dc:creator>
            <pubDate>Sun, 12 Nov 2017 19:37:03 GMT</pubDate>
            <atom:updated>2017-11-12T19:54:37.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Learned Sublime Text 3 keyboard shortcuts on OSX. These are not all the available keyboard shortcuts for sublime but the most handy that I have found:</p><p><strong>Keyboard shortcuts for text:</strong><br>⌘ + ↩ (command + return) will insert line after<br>⌘ + ⇧ + ↩ (command + shift +return) will insert line before<br>⌘ + ⌃ + ↑ (command + control + down) will move current line up<br>⌘ + ⌃ + ↓ (command + control + up) will move current line down<br>⌘ + Left (command + left-arrow) will move to beginning of text on line to<br>⌘ + Right (command + rigth-arrow) will move to end of line<br>⌘ + L (command + L) will select(highlight) current line. (p.s. multiple command entries will select the line below too)<br>⌘ + D (command + D) will select(highlight) current word. (p.s. multiple command entries will select recurrences of the selected word)<br>⌘ + ] (command + ]) will indent the current line<br>⌘ + [ (command + [) will un-indent the current line<br>⌘ + ⇧ + D (command + shift + D) will dupilcate the current line below<br>⌘ + K, ⌘ + K (command + K, command + K) will delete from cursor to end line</p><p><strong>These keyboard shortcuts are associated tabs:</strong><br>⌘ + ⇧ + [ (command + shift + ]) will go to the tab left of the open tab<br>⌘ + ⇧ + ] (command + shift + [) will go to the tab right of the open tab</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191f893e0641" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>