    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Student Code Critique Competition 29</title>
        <link>https://members.accu.org/index.php/journals/688</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 16, #4 - Aug 2004 + Student Code Critiques from CVu journal.</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c101/">164</a>
                    (12)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c183/">Code Critique</a>
                    (70)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c101-183/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c101+183/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Student Code Critique Competition 29</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 August 2004 13:16:07 +01:00 or Tue, 03 August 2004 13:16:07 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a></h2>
</div>
<p><span class="bold"><b>Prizes provided by Blackwells Bookshops
&amp; Addison-Wesley</b></span></p>
<p class="c2"><span class="remark">Please note that participation
in this competition is open to all members. The title reflects the
fact that the code used is normally provided by a student as part
of their course work.</span></p>
<p class="c2"><span class="remark">This item is part of the
Dialogue section of C Vu, which is intended to designate it as an
item where reader interaction is particularly important. Readers'
comments and criticisms of published entries are always
welcome.</span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e33" id="d0e33"></a>Before We
Start</h2>
</div>
<p>Thanks to the helping hand given by our editor and by a member
of the committee, I've been able to get my hands on the only two
entries for the current issue. It's quite sad to receive
collaboration from people who contribute to ACCU in many other
ways, and not from you. Being a 1000+ members association, if
roughly 0.5% of the members participated, there could be plenty of
material to provide food for thought. Please let us change this
statistic for the better.</p>
<p>Remember that you can get the current problem set in the ACCU
website (<a href="http://www.accu.org/journals/" target=
"_top">http://www.accu.org/journals/</a>). This is aimed at people
living overseas who get the magazine much later than members in the
UK and Europe.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e43" id="d0e43"></a>Late submission
to SCC 27</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e46" id="d0e46"></a>From Tony Houghton
<tt class="email">&lt;<a href=
"mailto:h@realh.co.uk">h@realh.co.uk</a>&gt;</tt></h3>
</div>
<p>Let's start by solving the immediate problem. If <tt class=
"function">pf()</tt> encounters a prime number it returns an
&quot;empty&quot; array i.e. the first element is zero. This means that the
body of the <tt class="literal">while</tt> loop in <tt class=
"function">main()</tt> is not executed and the ugly flag is not
altered; it retains its value from the previous number in the
range, which is often ugly, at least for low ranges. The solution
is therefore to reset the <tt class="varname">ugly</tt> flag to
zero in each iteration of the enclosing for loop. Immediately
before or after the line <tt class="literal">idx = 0;</tt> is
ideal.</p>
<p>However, the code is still not performing the correct test. It
only proves whether or not the last factor in the array is ugly,
not that they all are. This may work with the defined set of ugly
factors and because of the order in which <tt class=
"function">pf()</tt> fills its arrays, but we should rewrite the
test instead of relying on this. It's easiest to prove that a
number is not ugly, so we'll start by assuming it is until we find
a non-ugly factor, not forgetting the initial problem with
primes.</p>
<p>But we have something else to take into account: 2, 3 and 5 are
prime, so <tt class="function">pf()</tt> will return an &quot;empty&quot;
array and the test will not realise they're also ugly. We could
deal with this in <tt class="function">pf()</tt> by copying
quotient's initial value from the variable number rather than 0,
but this leads to an inconsistency when the <tt class=
"function">pf()</tt> function is considered in its own right: prime
numbers have themselves listed as a factor, other numbers
don't.</p>
<p>As we're also excluding the number 1 as a factor it makes sense
to continue to exclude the number itself and explicitly check for
2, 3 and 5 in our test. Thus the main <tt class="literal">for</tt>
loop becomes:</p>
<pre class="programlisting">
for(n = start; n &lt; stop + 1; ++n) {
  idx = 0;
  flist = pf(n);
  if(flist[0] == 0 &amp;&amp; n &gt; FIVE) ugly = 0;
  else ugly = 1;
  while(flist[idx]) {
    if(flist[idx] != TWO &amp;&amp;
       flist[idx] != THREE &amp;&amp;
       flist[idx] != FIVE) {
      ugly = 0;
    }
  ++idx;
  }
  if(ugly == 1)
    printf(&quot;%d\n&quot;, n);
  free(flist);
}
</pre>
<p>Now to give the code a complete makeover, starting from the top
and working down:</p>
<p>The first issue we encounter is a number of preprocessor macros.
Macros should only be used for jobs that nothing else can do, but
these can be replaced with <tt class="type">const int</tt> and/or
<tt class="literal">enum</tt>. Furthermore, the purpose of
replacing &quot;magic numbers&quot; with named constants is so that if the
values need to be changed they only need to be changed in one
place. If we want to change this program to deal with a different
set of ugly factors, the current names of the constants will be
very confusing; if we don't ever want to change it the names are
redundant. I've rewritten these constants as:</p>
<pre class="programlisting">
const int MaxFactors = 20;
  /* Max number of prime factors to find */
enum UglyFactors {
  UglyFac1 = 2,
  UglyFac2 = 3,
  UglyFac3 = 5
};
</pre>
<p>(Sorry about the pun).</p>
<p>Next we have a prototype for <tt class="function">pf()</tt>. The
name is far too terse, let's make it more descriptive: <tt class=
"function">prime_factors()</tt>. The function is only used in the
same source file, so it should be declared static. I'm not sure
whether the student has covered linkage types yet, but I think it's
a relatively straightforward concept and a good habit to learn
early.</p>
<p>It appears to be common practice to declare all function
prototypes in advance and define static functions towards the end
of a file. However, I prefer to avoid separate prototypes except in
headers on the grounds that they are a form of repetition.
Therefore I've brought the body of the function forward to this
point. The comment that precedes it should highlight any points of
interest about its parameters and return value - in this case that
it returns an array that's been allocated on the heap and that the
array is zero-terminated.</p>
<p>Inside the function I've separated the variable declarations
because <tt class="type">int*</tt> and <tt class="type">int</tt>
are actually two quite different types and it's considered bad form
to make them share the declaration with commas. I also prefer to
give all variables their own distinct declarations unless two or
more are closely related and have no initialisers.</p>
<p>I also decided to use the variable name <tt class=
"varname">i</tt> instead of <tt class="varname">idx</tt>. There is
an argument for short variable names as well as long descriptive
ones, and while <tt class="varname">idx</tt> was a good name to
start with, being concise but still meaningful to almost any
programmer, I always use <tt class="varname">i</tt> for the
(primary) array index in loops myself and sticking to that
convention makes the code more readable to me.</p>
<p>I've changed the <tt class="literal">while</tt> loop condition
to <tt class="literal">(divisor &lt;= number);</tt> I think it's
less clutter than the original. But we should also check that we
haven't exceeded the array bounds. If we really want to know all
the prime factors we should extend the array when necessary or come
up with a rough figure that's guaranteed to be an overestimate -
e.g. the upper limit of the range given to the program - and make
the array this size in the first place. However, for this purpose
it's adequate to return when the array is filled, remembering to
leave room for the terminating zero - which does not need to be
inserted explicitly because of the use of <tt class=
"function">calloc</tt> instead of <tt class="function">malloc</tt>.
The complete condition is now <tt class="literal">(divisor &lt;=
number &amp;&amp; i &lt; MaxFactors - 1)</tt>.</p>
<p>I noticed that it's possible for the same factor to be entered
more than once in the list if its square is also a factor e.g. 2
will appear twice if number is 8 or 12. We can prevent this by
checking whether the previous entry is equal to the one we're about
to add - remembering that if i is 0 we mustn't try to check
<tt class="literal">element-1</tt>:</p>
<pre class="programlisting">
if(i == 0 || flist[i - 1] != divisor)
  flist[i++] = divisor;
</pre>
<p>I also have a rule about braces around single statements such as
a simple <tt class="literal">if</tt> or <tt class=
"literal">for</tt> body. Although these are optional I often
include them, especially if:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>the parent statement, e.g. an <tt class="literal">if</tt>
conditional, is long and I've wrapped it to fit my editor window -
the indentation makes it difficult to distinguish the conditional
from the body otherwise</p>
</li>
<li>
<p>it's an <tt class="literal">if</tt> or <tt class=
"literal">else</tt> clause and its sibling clause needs braces</p>
</li>
<li>
<p>there's any possibility that the statement is a macro which
could be switched off e.g. an assertion or extra logging in debug
builds. I mention all this because I've applied rule (2) to the
<tt class="literal">else</tt> statement here</p>
</li>
</ol>
</div>
<p>Next I've done some refactoring. Breaking programs down into
smaller functions almost invariably makes them more readable, and
providing a function to test whether a given number is ugly is a
logical step. The body of this function is pretty much as above
except that I replaced the <tt class="literal">while</tt> loop with
a <tt class="literal">for</tt> loop. Also, bearing in mind being
able to change the values of the <tt class="constant">UglyFac</tt>
constants, it's unsafe to assume that there are no non-ugly primes
below <tt class="constant">UglyFac3</tt>, so we should test against
each of them instead of testing whether <tt class="literal">n &gt;
UglyFac3</tt>.</p>
<p>I've given <tt class="function">main()</tt> a comment about its
arguments, which is basically an alternative to the &quot;enter a range&quot;
comment which I thought was misleading: it implied the range would
be read from <tt class="literal">stdin</tt> rather than arguments.
Again I've separated the variable declarations. I've kept the
variable name <tt class="varname">n</tt> because it's ideal for a
loop variable describing a number other than an index, but I've
renamed <tt class="varname">start</tt> and <tt class=
"varname">stop</tt> to <tt class="varname">first</tt> and
<tt class="varname">last</tt>, which I think makes it clearer that
the range is inclusive. The <tt class="literal">for</tt> loop
terminating condition is again changed to use &lt;= instead of
&lt;</p>
<p>Just a couple of minor semantics remaining. As <tt class=
"varname">ugly</tt> is a boolean flag, I prefer to write <tt class=
"literal">if(ugly)</tt> and <tt class="literal">if(!ugly)</tt>
rather than <tt class="literal">if(ugly==1)</tt> and <tt class=
"literal">if(ugly==0)</tt>. And as we're using <tt class=
"constant">EXIT_FAILURE</tt> we might as well use <tt class=
"constant">EXIT_SUCCESS</tt> too. Here is my first complete rewrite
(keep on reading for my description of a slightly different
approach to the problem):</p>
<pre class="programlisting">
/* Find &quot;ugly numbers&quot;: their prime factors
   are all 2, 3 or 5 */
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

const int MaxFactors = 20;
     /* Max number of prime factors to find */

enum UglyFactors {
  UglyFac1 = 2,
  UglyFac2 = 3,
  UglyFac3 = 5
};

/* Returns a zero-terminated array of number's
   prime factors, allocated on the heap */
static int *prime_factors(int number) {
  int *flist;
  int quotient = 0;
  int divisor = 2;
  int i = 0;

  flist = calloc(MaxFactors, sizeof(int));
  while(divisor &lt;= number
        &amp;&amp; i &lt; MaxFactors - 1) {
    if(divisor == number) {
      flist[i] = quotient;
      break;
    }
    if(number % divisor == 0) {
      if(i == 0 || flist[i - 1] != divisor)
        flist[i++] = divisor;
      quotient = number / divisor;
      number = quotient;
    }
    else {
      ++divisor;
    }
  }
  return flist;
}

/* Returns 1 if number is ugly, otherwise 0 */
static int is_ugly(int number) {
  int i = 0;
  int ugly;
  int *flist = prime_factors(number);
  if(flist[0] == 0 &amp;&amp; number != UglyFac1
     &amp;&amp; number != UglyFac2
     &amp;&amp; number != UglyFac3) {
    ugly = 0;
  }
  else {
    ugly = 1;
  }
  for(i = 0; flist[i]; ++i) {
    if(flist[i] != UglyFac1 &amp;&amp;
       flist[i] != UglyFac2 &amp;&amp;
       flist[i] != UglyFac3) {
      ugly = 0;
    }
  }
  free(flist);
  return ugly;
}

/* Range is given in arguments */
int main(int argc, char **argv) {
  int n;
  int first, last;
  if(argc !=3)
    exit(EXIT_FAILURE);
  first = atoi(argv[1]);
  last = atoi(argv[2]);
  for(n = first; n &lt;= last; ++n) {
    if(is_ugly(n))
      printf(&quot;%d\n&quot;, n);
  }
  return EXIT_SUCCESS;
}
</pre>
<p>This solution works, but is not the most efficient. We don't
actually need to list all the prime factors of ugly candidates,
just check them until we find a factor that proves the number isn't
ugly, again taking care not to pass primes as false positives.
Therefore the <tt class="function">prime_factors</tt> function can
be deleted and <tt class="function">is_ugly()</tt> replaced with
the version below.</p>
<pre class="programlisting">
/* Returns 1 if a number is ugly, 0 if it
   isn't */
static int is_ugly(int number) {
  int divisor = 2;
  int ugly = 0;
  for(divisor = 2; divisor &lt;= number;
      ++divisor) {
    if(number % divisor == 0) {
      if(divisor % UglyFac1 != 0 &amp;&amp;
         divisor % UglyFac2 != 0 &amp;&amp;
         divisor % UglyFac3 != 0) {
        ugly = 0;
        break;
      }
      else {
        ugly = 1;
      }
    }
  }
  return ugly;
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e269" id="d0e269"></a>Student Code
Critique 28</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e272" id="d0e272"></a>Program 1</h3>
</div>
<p><span class="emphasis"><em>I'm newbie to C++ and I would like to
know which would be the best (elegant and correct) solution for the
following small (string) read problem with <tt class=
"function">gets</tt>.</em></span></p>
<pre class="programlisting">
#include &lt;iostream&gt;
using namespace std;
#include &lt;cstdio&gt;

main() {
  int n;
  int waste; // needs this to work (read)
             // properly!!
  char name[51];
  cout &lt;&lt; &quot;Enter any integer number...\n&quot;;
  cin  &gt;&gt; n;
  cout &lt;&lt; &quot;Enter your name...\n&quot;;
  cin  &gt;&gt; waste; // 'gets' does not read the
                 // name without this line!!
  gets(name);
}
</pre>
<p>Mixing C and C++ functions doesn't seem the best way to write
this program. Please provide alternatives, taking also into account
its security implications.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e285" id="d0e285"></a>Program 2</h3>
</div>
<p><span class="emphasis"><em>If I enter 23 and 5 the answer should
be 23 * 5 = 115 my answer is off by five or whatever number 2 is. I
was told I am not including the first two numbers in the loop. I
thought when I cin the numbers it is including them. Does anyone
have any suggestions on how I can fix this?</em></span></p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;iomanip&gt;
#include&lt;string&gt;
using namespace std;
int main()
{
  while (1){
int   num1, num2, total = 0;
cout&lt;&lt;&quot;Enter two numbers: &quot;;
cin&gt;&gt;num1&gt;&gt;num2;
while (num1 != 1)
cout&lt;&lt;setw(5)&lt;&lt;num1&lt;&lt;setw(5)&lt;&lt;num2&lt;&lt;endl;
  num1 /= 2;
    num2 *= 2; 
  if (num1 % 2 != 0)
    total += num2;
}
cout&lt;&lt;&quot;the total is  &quot;&lt;&lt;total &lt;&lt;endl;
}  //End While 1
return 0;
}
</pre>
<p>There are numerous errors in both the code and the student's
understanding. Please address these comprehensively.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e295" id="d0e295"></a>From Paul F.
Johnson <tt class="email">&lt;<a href=
"mailto:editor@accu.org">editor@accu.org</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e300" id="d0e300"></a>Program 1</h4>
</div>
<p>If I ignore the obvious mistake of not having <tt class=
"type">int</tt> before <tt class="function">main()</tt>, there are
a couple of problems with the code.</p>
<p>Firstly is the use of <tt class="function">gets</tt> - it's a
licence for things going wrong with undefined behaviour the most
obvious to occur as a char array is being used to store the
person's name. A far better solution would be for the name to be
stored in a <tt class="classname">std::string</tt> variable which
does not have a boundary (well, not in the same way as a <tt class=
"type">char</tt> array does!). Buffer overflows account for more
and bloodier problems with security than enough.</p>
<p>There is also a problem with the entry of the number - as it
stands, it is possible for the user to enter just about anything
they want as there are no forms of bounds or type checking.</p>
<p>Finally, we have the &quot;dummy&quot; use of another variable which isn't
required (and again, can lead to problems without checking for the
correct type). The stream can be cleared by use of <tt class=
"methodname">cin.ignore</tt>.</p>
<p>By the simple application of <tt class=
"methodname">cin.fail()</tt> and <tt class=
"methodname">cin.getline()</tt>, the code can be transformed into
something which (a) works and (b) is relatively secure.</p>
<p>A solution may be along the lines of</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

int main() {
  int n;
  string name;
  cout &lt;&lt; &quot;Please enter a number : &quot;;
  while(cin &gt;&gt; n, cin.fail()) {
    cout &lt;&lt; &quot;I need a number!&quot; &lt;&lt; endl;
    cin.clear();
    cin.ignore(numeric_limits&lt;
               std::streamsize&gt;::max(), '\n');
    // non compliant compilers may complain
    // here. If they do use cin.ignore();
  }
  cin.ignore(numeric_limit&lt;
               std::streamsize&gt;::max(), '\n');
  cout &lt;&lt; &quot;Please enter your name : &quot;;
  cin.getline(name, '\n');
  cout &lt;&lt; &quot;Number : &quot; &lt;&lt; n &lt;&lt; &quot;, name : &quot;
       &lt;&lt; name &lt;&lt; endl;
}
</pre>
<p>As newbie code goes, the original wasn't that bad. It was well
laid out (which made debugging simpler) and contained many of the
problems faced by a newbie where the most obvious answer is not
always the correct one.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e343" id="d0e343"></a>Program 2</h4>
</div>
<p>First, the easy ones...</p>
<p><tt class="literal">#include &lt;string&gt;</tt> is not required
and somewhere, an open { is missing. This second problem would have
been obvious if the student had bothered to try to compile the
code!</p>
<p>I next come to the <tt class="function">setw()</tt> calls - what
are they there for? We are dealing with integers in <tt class=
"varname">num1</tt>, <tt class="varname">num2</tt> and <tt class=
"varname">total</tt>, therefore using <tt class=
"function">setw</tt> does seem to be a bit of a waste!</p>
<p>There doesn't seem to be a check on the entries either. There is
nothing to stop the user entering # and @ for the numbers (or even
CVu and Overload for that matter!).</p>
<p>The next couple of faults are in the logic. To start, we have
the line</p>
<pre class="programlisting">
num1 /= 2;
</pre>
<p>If the user enters 0, the result value in num1 will be 1 which
will throw the answer.</p>
<p>The line</p>
<pre class="programlisting">
if(num1 % 2 != 0)
</pre>
<p>really is bemusing! What is the point of it? Why does the
program have to check if <tt class="varname">num1</tt> is divisible
by 2 with a 0 remainder? [<i><span class="remark">The student is
trying to implement a Russian peasant multiplication algorithm. The
point is to discriminate whether num1 is even or not.
David</span></i>]</p>
<p>Finally, total only seems to be having <tt class=
"varname">num2</tt> added to it (and even then, only as a result of
a condition); <tt class="varname">num1</tt> doesn't seem to be used
anywhere other than as an entry. It is therefore completely
possible for the user to be enter as many numbers as they like
without the correct answer coming out ever.</p>
<p>Fixing the problem is simple - it requires being rewritten.
Unfortunately, the student hasn't actually said what the question
was, so it is a tad pointless trying to second guess what the
original problem set was.</p>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e399" id="d0e399"></a>From Mark
Easterbrook <tt class="email">&lt;<a href=
"mailto:mark@easterbrook.org.uk">mark@easterbrook.org.uk</a>&gt;</tt></h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e404" id="d0e404"></a>Program 1</h4>
</div>
<p>As suggested in the problem, mixing C and C++ I/O is not the
best way to write this program. As you are learning C++, it is best
to replace the Ctype parts with C++. This requires two changes:</p>
<p>Change &quot;<tt class="literal">char name[51]</tt>&quot; to &quot;<tt class=
"literal">string name</tt>&quot; (this will require an <tt class=
"literal">#include &lt;string&gt;</tt> to compile). It is nearly
always better to use one of the C++ collections rather than an
array. In this case a C++ string type will automagically expand to
the size of the input name so you have one less thing to worry
about.</p>
<p>Use C++ istream instead of <tt class="function">gets()</tt>:
<tt class="literal">cin &lt;&lt; name</tt>. The waste variable and
input is no longer required, nor is the <tt class=
"literal">#include &lt;cstdio&gt;</tt>.</p>
<p>It is worth pointing out a number of improvements that can be
made to the code. main always returns an <tt class="type">int</tt>
so this needs to be specified: <tt class="function">int
main()</tt>.</p>
<p><tt class="literal">using namespace std</tt> will import the
whole <tt class="literal">std</tt> namespace. It is often better to
only import names you actually need, or to qualify every use.</p>
<p>Single character variable names are often frowned upon. Think
how difficult it would be to search for all uses of the variable
<tt class="varname">n</tt> in a large program!</p>
<p>At this point we have &quot;fixed&quot; the program and could let it rest,
but it is worth looking at why <tt class="function">gets()</tt> is
bad, even in C code. <tt class="function">gets()</tt> will read an
unknown number of characters into a C string (<tt class=
"type">char*</tt> or <tt class="type">char[]</tt>) of predetermined
length, therefore it is possible to read more characters than are
allowed for. This is called &quot;buffer overrun&quot; and accounts for many
of the security holes in software. The result of such a buffer
overrun could be:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>It writes over memory allocated but not used by the program. No
amount of testing will show this up so the bug can remain hidden
until something else changes: a different compiler, a different
platform, or a simple code change somewhere else in the
program.</p>
</li>
<li>
<p>It writes over memory not allocated to the program. If you are
lucky your operating system will detect this and stop the
program.</p>
</li>
<li>
<p>It overwrites memory used by the program. This causes the
program to malfunction, and possibly later crash. This will be very
difficult to track down.</p>
</li>
<li>
<p>It overwrites memory used by the program in such a way that the
program does something completely different to that originally
intended. If you are unlucky you are connected to the internet and
this allows a stranger access to your computer!</p>
</li>
</ul>
</div>
<p>As you cannot use <tt class="function">gets()</tt>, what should
you use instead? There are a number of options:</p>
<p>Use <tt class="function">fgets()</tt> to read up to a line of
input. It takes as parameters a pointer to the input buffer (like
<tt class="function">gets</tt>), a maximum number of characters
(which prevents buffer overrun), and a file descriptor (e.g.
<tt class="literal">stdin</tt>). It will stop reading either when
the maximum number of characters are read, or at a new line
character.</p>
<p>Use <tt class="function">scanf()</tt> with the <tt class=
"literal">%s</tt> format string specifying a maximum length. For
example, <tt class="literal">%50s</tt> will read a maximum of 50
characters (plus a terminator!).</p>
<p>Input characters one at a time using <tt class=
"function">getchar()</tt> or <tt class="function">getc()</tt>.</p>
<p>You will need to read the documentation for each of these to see
which meets your needs best. Each has different rules as to when it
stops reading.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e515" id="d0e515"></a>Program 2</h4>
</div>
<p>Note: The program as presented will not compile because the
inner loop has a closing brace but no opening brace. This can be
corrected by adding the opening brace after the while expression. I
have assumed this is just a printing error. [<i><span class=
"remark">Actually the student provided the code as is.
David</span></i>]</p>
<p>I will take a guess that the problem set is to perform
multiplication using binary arithmetic by adding in 2n x the second
number for each bit set in the first. E.g. 23*5 is 10111 x 510 =
80+0+20+10+5.</p>
<p>The algorithm you have chosen is to shift the first number right
bit by bit, testing the least significant (right-most) bit, while
at the same time left-shifting the second number to obtain the
powers of 2. This is almost correct, but the first value of
<tt class="varname">num2</tt> you are adding to the total has
already been shifted, whereas it can be seen from the example
above, the first addition should be the original entered value (5).
This is what is meant by &quot;&hellip;not including the first two
numbers&hellip;&quot;. If you move the add-to-total to the beginning of
the loop, then the total will be accumulated as 5+10+20&hellip;,
which is what we want. We have now fixed the start-up conditions,
so let's check the exit condition. We want to include all the bits
from <tt class="varname">num1</tt>, so we want to continue the loop
while there are still bits to process, in other words, while
<tt class="varname">num1</tt> is not all zero bits. The current
test (<tt class="literal">num1!=1</tt>) does not do this, it will
stop with the last bit still not processed. Let's change the
condition to (<tt class="literal">num!=0</tt>) and give the program
a test:</p>
<pre class="screen">
Enter two numbers: 23 5
   23    5
   11   10
    5   20
    2   40
    1   80
the total is 115
</pre>
<p>We now have a working program, but the code does not quite
capture the intent: it is required to demonstrate how binary
multiply can be performed by shift and add operations, but there
are no shifts! Although we know that in C and C++ n/2 is equivalent
to n&gt;&gt;1 and n*2 is equivalent to n&lt;&lt;1, using the bit
shift operators would illustrate the intent more clearly. Similarly
testing the least significant bit would be better as a mask and
test rather than the remainder of a divide. Finally, the source
code would benefit from some comments to explain what it is
for.</p>
<p>Thus we end up with:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;iomanip&gt;
#include &lt;string&gt;

using namespace std;

// Perform binary multiply of two integers
// using shift and add.  The total is built up
// by adding the matching power of two from
// the second number for each bit set in the
// first bit. Bits are tested in the first
// number by testing the LS bit and shifting
// right. The powers of two of the second
// number are generated by shifting left on
// each iteration.
// e.g. 23(10111)*5 = 80 + 0 + 20 + 10 + 5
// (summed in reverse order).

int main() {
  while(1) {
    int num1, num2, total=0;
    cout &lt;&lt; &quot;Enter two numbers: &quot;;
    cin &gt;&gt; num1 &gt;&gt; num2;
    while(num1 != 0) {
      cout &lt;&lt; setw(5) &lt;&lt; num1
           &lt;&lt; setw(5) &lt;&lt; num2 &lt;&lt; endl;
      if((num1&amp;0x01) != 0)
        total += num2;
      num1 &gt;&gt;= 1;
      num2 &lt;&lt;= 1;
    }
    cout &lt;&lt; &quot;the total is &quot; &lt;&lt; total &lt;&lt; endl;
  }
  return 0;
}
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e550" id="d0e550"></a>The Winner of
SCC 28</h2>
</div>
<p>The editor's choice is:</p>
<p><span class="bold"><b>Tony Houghton</b></span></p>
<p>Please email <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
to arrange for your prize.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e563" id="d0e563"></a>Francis'
Commentary</h2>
</div>
<p>For my comments on the first little program for SCC28 see my
Francis' Scribbles column elsewhere (working late and meeting
deadlines resulted in my sending David some code I had already used
in my column. Fortunately that does not matter too much.)</p>
<p>Here is my commentary on the second little program.</p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;iomanip&gt;
#include&lt;string&gt;
using namespace std;
int main() {
  while(1) {
    int num1, num2, total = 0;
    cout &lt;&lt; &quot;Enter two numbers: &quot;;
    cin &gt;&gt; num1 &gt;&gt; num2;
    while (num1 != 1) {
      cout &lt;&lt; setw(5) &lt;&lt; num1 
           &lt;&lt; setw(5) &lt;&lt; num2 &lt;&lt; endl;
      num1 /= 2;
      num2 *= 2; 
      if((num1 % 2) != 0) total += num2;
    }
    cout &lt;&lt; &quot;the total is &quot; &lt;&lt; total &lt;&lt; endl;
  }  // End While 1
  return 0;
}
</pre>
<p>First, in the above restatement of the program I have
reformatted the code to make its structure more visible. Now let me
focus on that structure before turning to the root of the
problem.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e574" id="d0e574"></a>Prepare For
Exceptions</h3>
</div>
<p>I strongly advocate that the default form of the definition of
<tt class="function">main()</tt> should encapsulate its code in a
<tt class="literal">try</tt> block. That seems to me to be a good
discipline for students as soon as they are conscious that errors
may occur at runtime that result in an exception. Indeed they
should be encouraged to validate such things as input and
exceptions make it easy for them to have a default action when
validation fails. So I would start with:</p>
<pre class="programlisting">
int main() {
  try {
    // main code
  }
  catch(...) {
    cerr &lt;&lt; &quot;An exception occurred.\n&quot;;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
</pre>
<p>Now that is a fixed framework and it isn't even tedious to type
because you just copy and paste it from a text file of standard
bits of source code.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e589" id="d0e589"></a>Repetition of
Process</h3>
</div>
<p>The first problem with the student's code is that it has no
termination. He puts it all in a forever loop without any internal
exit. I have no problem with forever loops (except that I use
<tt class="literal">while(true)</tt>) as long as they have an
internal exit (that is unless you are writing a process which must
continue until the machine is switched off). In this case I would
write something such as:</p>
<pre class="programlisting">
while(true) {
  // main process
  cout &lt;&lt; &quot;Do you want another? (y/n)&quot;;
  char yn;
  cin &gt;&gt; yn;
  if(yn == 'n' || yn == 'N') break;
}
</pre>
<p>Now we can argue about the details but the general idea should
be considered as an idiom of programming (not just C++).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e601" id="d0e601"></a>Appropriate
Variable Names</h3>
</div>
<p>As an ex-maths teacher I quickly recognised the algorithm being
implemented by this program (goes under several names, try using
Google to search for 'Russian Peasant Multiplication') but the
variable names were not helpful. Let me suggest some others and
polish up the code whilst I am at it.</p>
<pre class="programlisting">
cout &lt;&lt; &quot;Enter the pair of numbers you want &quot;
     &lt;&lt; &quot;to multiply together: &quot;;
int multiplicand(getint());
int multiplier(getint());
int product(0);
</pre>
<p>Now the variable names give a hint as to what is being done.
Validation and handling bad input is all handled by the <tt class=
"function">getint()</tt> function. Actually I would use my
<tt class="function">read()</tt> set of templates but that is just
a convenience. However avoiding repetitious coding whilst always
validating input should be learnt from the very beginning.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e616" id="d0e616"></a>Getting the
Right Test</h3>
</div>
<p>Now we get to the actual reason the program does not work. Look
at that inner <tt class="literal">while</tt> loop. Look at the
test. Surely this is too early, or it is the wrong test because it
fails immediately if the multiplicand is one. In other words
multiplying one by anything will give a product of zero. There are
several solutions but I would prefer:</p>
<pre class="programlisting">
while(multiplicand)
</pre>
<p>or if you do not like that form:</p>
<pre class="programlisting">
while(multiplicand != 0)
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e630" id="d0e630"></a>Getting the
Right Order of Statements</h3>
</div>
<p>For the algorithm (which is effectively using binary for
multiplication) we add in the current value of the multiplier into
the product if the current value of the multiplicand is odd (i.e.
would end in one in binary), then the multiplicand is halved
(shifted left) and the multiplier is doubled (shifted right). The
order of these operations is vital and is the second point of error
in the student's code. Leaving aside the display of the interim
results, which I would have preferred to see include the interim
value of the product in a third column) the meat of the algorithm
is coded as:</p>
<pre class="programlisting">
if(multiplicand % 2) product += multiplier;
multiplicand /= 2;
multiplier *= 2;
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e637" id="d0e637"></a>Putting It All
Together</h3>
</div>
<p>Here is my complete program (well I have left out the front
matter of headers and using directive):</p>
<pre class="programlisting">
int main() {
  try {
    while(true) {
      cout &lt;&lt; &quot;Enter the pair of numbers you &quot;
           &lt;&lt; &quot;want to multiply together: &quot;;
      int multiplicand(getint());
      int multiplier(getint());
      int product(0);
      while(multiplicand) {
        cout &lt;&lt; setw(5) &lt;&lt; multiplicand
             &lt;&lt; setw(5) &lt;&lt; multiplier
             &lt;&lt; setw(10) &lt;&lt; product
             &lt;&lt; '\n';
        if(multiplicand % 2)
          product += multiplier;
        multiplicand /= 2;
        multiplier *= 2;
      }
      cout &lt;&lt; &quot;The product is &quot; &lt;&lt; product
           &lt;&lt; &quot;.\n\n&quot;;
      cout &lt;&lt; &quot;Do you want another? (y/n)&quot;;
      char yn;
      cin &gt;&gt; yn;
      if(yn == 'n' || yn == 'N') break;
    }
  }
  catch(...) {
    cerr &lt;&lt; &quot;An exception occurred.\n&quot;;}
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
</pre>
<p>Note that the depth of nesting for structures suggests that some
refactoring into functions might be desirable. I would probably
make the outermost loop a <tt class="literal">do</tt>-<tt class=
"literal">while</tt> one and use the return value from a function
asking about repeating the process in the while. Something
like:</p>
<pre class="programlisting">
do {
  // process
while(do_again());
</pre>
<p>I would also move out the display of the intermediate results to
a function. I would also probably replace the computation block
with a function call, but that is much more marginal because all
the arguments have to be passed by reference and I doubt that we
get much more clarity in exchange for using a function.</p>
<p>Now do feel free to comment on the coding style and anything
else that you want to criticise. Remember that this column is
supposed to be a kind of seminar and not a lecture.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e658" id="d0e658"></a>Student Code
Critique 29</h2>
</div>
<p>(Submissions to <tt class="email">&lt;<a href=
"mailto:scc@accu.org">scc@accu.org</a>&gt;</tt> by September
10th)</p>
<p>Looks like an ordinary snippet, doesn't it? Amazingly, it
contains various mistakes for such a few lines. Please provide a
correct version.</p>
<pre class="programlisting">
#include &lt;iostream&gt;
using std::cout;
using std::endl;

#include &lt;list&gt;
using std::list;

int main() {
  list&lt;double&gt;::iterator it;
    list&lt;double&gt; lst;
  *it = 34;
  *++it = 45;
    *++it = 87;
    it = lst.begin();
    for (;it &lt; lst.end(); ++it){
      cout &lt;&lt; it &lt;&lt; '\t' &lt;&lt; *it &lt;&lt; endl;
  }
    system(&quot;pause&quot;);
  return 0;
}
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
