    <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 27</title>
        <link>https://members.accu.org/index.php/articles/210</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>




<div class="xar-mod-head"><span class="xar-mod-title">Francis' Scribbles from CVu journal + CVu Journal Vol 16, #2 - Apr 2004</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/articles/">All</a>

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c181/">Francis' Scribbles</a>
<br />

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c103/">162</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c181-103/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c181+103/">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 27</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 01 April 2004 22:53:48 +01:00 or Thu, 01 April 2004 22:53:48 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p><em>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.</em></p>
<p><em>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.</em></p>
</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2>Before We
Start</h2>
</div>
<p>This is the last column under my beeline as setter and collator.
David Caabeiro responded to my appeal for a volunteer to take over
from me. Submissions and other material should be sent to him at
<tt class="email">&lt;<a href=
"mailto:caabeiro@vodafone.es">caabeiro@vodafone.es</a>&gt;</tt>. He
is keen that code critiques should expand beyond the purely C and
C++ ones I have provided. With that in mind any readers who spot an
apt piece of code in Java, Python or even C# should send it to him.
The intention is that there will always be a C or C++ piece of code
but where available there will be a code sample from one of the
other languages.</p>
<p>Another change is that I will keep contact with this column by
submitting a 'Teacher's Critique' of C and C++ student code. In
other words alongside the competition entries there will be an
extra critique from me which will usually include the solution that
I would have provided (which will also, of course, be open to
question and refinement).</p>
<p>I hope that everyone will give David plenty of support because
there is nothing so depressing as lack of response. In the virtual
classroom we cannot see the looks of enlightenment, puzzlement or
boredom on other faces so we have to rely on the 'students' making
their participation visible.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>Student Code
Critique 26 Entries</h2>
</div>
<p>This time the problem is still about some student code, however
it is code that works, but how do you help the student to move
forward? Yes, I know the simple answer but I am looking for
something more.</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>The following program (below my question) produces the results I
want, but I am trying to create a for-loop to replace all of the
cout statements.</p>
<p>What I have so far is:</p>
<pre class="programlisting">
for(int i = 0; i &lt;= len; i++)
  cout &lt;&lt; str[i + 1];
</pre>
<p>This will produce: &quot;eed help with C++.&quot;</p>
<p>Could someone clue me in on how to create the <tt class=
"literal">for</tt>-loop? Should I be using a nested for loop? Any
help would be appreciated.</p>
<p><span class="bold"><b>Student's Program:</b></span></p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;cstring&gt;

using namespace std;

void main (){
  const int arraySize = 20;
  char str[arraySize] = &quot;Need help with C++.&quot;;
  int len = strlen(str);

  cout &lt;&lt; &quot;The sentence \&quot;Need help with C++.\&quot; has &quot;
       &lt;&lt; len &lt;&lt; &quot; characters.&quot;
       &lt;&lt; endl &lt;&lt; endl;
  cout &lt;&lt; str &lt;&lt; endl;
  cout &lt;&lt; str + 1 &lt;&lt; endl;
  cout &lt;&lt; str + 2 &lt;&lt; endl;
  cout &lt;&lt; str + 3 &lt;&lt; endl;
  // 13 similar statements snipped
  cout &lt;&lt; str + 16 &lt;&lt; endl;
  cout &lt;&lt; str + 17 &lt;&lt; endl;
  cout &lt;&lt; str + 18 &lt;&lt; endl;
</pre></blockquote>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From Walter
Milner</h3>
</div>
<p>Dear Student</p>
<p>I think I should remind you that the set text for this course is
Accelerated C++ by Koenig and Moo, and you are supposed to read it.
I looks to me as if you haven't.</p>
<p>First of all let's look at what you have. We can see more
clearly what is happening if we also display the index, together
with the data as characters and code, as</p>
<pre class="programlisting">
for(int i=0; i&lt;=len; i++)
  cout &lt;&lt; i &lt;&lt; &quot; &quot; &lt;&lt; str[i+1]
       &lt;&lt; &quot; &quot; &lt;&lt; (int)str[i+1] &lt;&lt; endl;
</pre>
<p>which on a machine using ASCII yields -</p>
<pre class="screen">
0 e 101
1 e 101
2 d 100
3   32
4 h 104
{similar lines snipped by FG}
17 . 46
18   0
19 + -64
</pre>
<p>So your loop outputs 20 characters (0 to 19 inclusive) The 19th
is the zero marking the end of the string, and the 20th is whatever
is in memory after that. We can simply fix your loop as</p>
<pre class="programlisting">
for(int i=0; i&lt;len; i++)
  cout &lt;&lt; str[i] &lt;&lt; endl;
</pre>
<p>However there are some issues with the way you are doing this.
Firstly, how did you choose the value of <tt class=
"varname">arraySize</tt>? Did you count the letters in the string
and add <tt class="literal">1</tt> for the <tt class=
"literal">0</tt> at the end? Pretty tedious, and it makes using
<tt class="function">strlen</tt> pretty pointless.</p>
<p>Secondly, the approach is not easy to adapt to other strings -
in other words there is a close link between the algorithm and the
actual data it processes. To cope with another string, would you
have changed <tt class="varname">arraySize</tt>? To what? You could
fix it at <tt class="literal">1024</tt> and limit this to strings
of length less than that, but that would be pretty
unsatisfactory.</p>
<p>Using an array of characters is a common way to represent a
string in C. Alternatively you might have said</p>
<pre class="programlisting">
char * str = &quot;Need help with C++.&quot;;
</pre>
<p>Then said something like</p>
<pre class="programlisting">
for(char * ptr = str; *ptr; ptr++)
  cout &lt;&lt; *ptr &lt;&lt; endl;
</pre>
<p>which relies on the fact that at the end of the string *ptr is 0
and therefore false, ending the loop. In other words it depends a
lot on the way the string is stored - the details of the
implementation. This is how it is done in C - but we're supposed to
be using C++.</p>
<p>Why have you been given this as a task anyway? What is the point
of outputting a sentence one letter at a time? Hopefully you
realise that this is an exercise concerned with the two basic
questions:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>How do we have something of interest in a computer?</p>
</li>
<li>
<p>How do we do things with it?</p>
</li>
</ol>
</div>
<p>In this exercise the thing of interest is an English sentence.
We need a way of representing that inside the machine. The second
question in this case is how to 'go through' that representation -
to traverse it. This is a very common real task. You traverse
representations to search them, count them, add them up, change
them and so on.</p>
<p>We want to do this with the minimum of effort, and the maximum
of generality - so in future we can do it with even less effort. If
possible we want to avoid the <span class=
"bold"><b>details</b></span> of how it is done - we just want to
think of it as a string, not as bytes or values in RAM. In other
words we want to work at as <span class=
"bold"><b>abstract</b></span> a level as possible.</p>
<p>But the Standard C++ Library has such a thing, not surprisingly
called <tt class="classname">string</tt> (surely you got as far as
Chapter 1 in <i class="citetitle">Accelerated C++</i>?). We just
say:</p>
<pre class="programlisting">
string str = &quot;Need help with C++.&quot;;
cout &lt;&lt; &quot;The sentence \&quot; &lt;&lt; str
     &lt;&lt; &quot;\&quot; has &quot; &lt;&lt; s.length()
     &lt;&lt; &quot; characters.&quot; &lt;&lt; endl &lt;&lt; endl;
</pre>
<p>How is that string stored in memory? Who cares? Not our problem.
We want to traverse that string from start to end, so we can just
say</p>
<pre class="programlisting">
for(string::const_iterator i=s.begin();
    i!=s.end(); i++)
  cout &lt;&lt; *i &lt;&lt; endl;
</pre>
<p>If you've lost the handout on iterators, see chapter 5 in
<i class="citetitle">Accelerated C++</i>.</p>
<p>[<span class="emphasis"><em>As a teacher I would have to say
that a struggling student would almost certainly give up the course
if faced with such a critique. Of course the work might be that of
a bright but lazy student but it does not have the hallmarks of
such work. To me it looks like the work of a very conscientious
student who has completely failed to grasp a couple of important
elements, such as how for-loops work. Francis</em></span>]</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3>From Colin
Hersom &lt;<tt class="email">&lt;<a href=
"mailto:colin@hedgehog.cix.co.uk">colin@hedgehog.cix.co.uk</a>&gt;</tt>&gt;</h3>
</div>
<p>Le us solve the student's immediate problem of how to turn a
list of similarlooking statements into a for-loop to save
repetition.</p>
<p>The existing code looks like:</p>
<pre class="programlisting">
cout &lt;&lt; str &lt;&lt; endl;
cout &lt;&lt; str + 1 &lt;&lt; endl;
cout &lt;&lt; str + 2 &lt;&lt; endl;
cout &lt;&lt; str + 3 &lt;&lt; endl;
etc.
</pre>
<p>Taking this very slowly, the first thing to do is to ensure that
all the statements have a similar form, so I shall change to first
line to:</p>
<pre class="programlisting">
cout &lt;&lt; str + 0 &lt;&lt; endl;
</pre>
<p>This gives them all an addition operator, but adding zero has no
other effect. Now we can progress to producing a list of statements
that are all textually identical by introducing a variable to
replace the constants in each line:</p>
<pre class="programlisting">
int i = 0;
cout &lt;&lt; str + i &lt;&lt; endl;
i++;
cout &lt;&lt; str + i &lt;&lt; endl;
i++;
cout &lt;&lt; str + i &lt;&lt; endl;
i++;
..etc
</pre>
<p>Now that really can be replaced by a loop - provided that we
know when to stop. The final statement in the original code is</p>
<pre class="programlisting">
cout &lt;&lt; str + 18 &lt;&lt; endl;
</pre>
<p>so we need to stop when i passes 18, i.e. continue while i is
less than 19.</p>
<p>We can now wrap up all those identical statements into this:</p>
<pre class="programlisting">
int i = 0;
while(i &lt; 19) {
  cout &lt;&lt; str + i &lt;&lt; endl;
  i++;
}
</pre>
<p>and we realise that the construct:</p>
<pre class="programlisting">
<span class="emphasis"><em>iterator = start;
while(condition) {
  body-statements
  iterator++;
}</em></span>
</pre>
<p>can be replaced by a <tt class="literal">for</tt>-loop:</p>
<pre class="programlisting">
<span class=
"emphasis"><em>for(iterator = start; condition; iterator++)
  body-statements</em></span>
</pre>
<p>which gives us our <tt class="literal">for</tt>-loop:</p>
<pre class="programlisting">
for (int i=0; i&lt;19; i++)
  cout &lt;&lt; str + i &lt;&lt; endl;
</pre>
<p>&quot;Magic numbers&quot;, i.e. constants used in their numeric form,
should be avoided, except for zero in most cases. Sometimes these
constants are part of the problem domain, e.g. the acceleration due
to gravity, in which case they should be provided by a named
constant (or a macro in older C implementations). Here, the 19
output statements are due, I assume, to the length of the test
string. Since we have calculated the length, we can use it. This
also means that if the test string is changed, the number of lines
exactly equals the length:</p>
<pre class="programlisting">
for (int i=0; i&lt;len; i++)
  cout &lt;&lt; str + i &lt;&lt; endl;
</pre>
<p>Some people would argue that the pre-increment <tt class=
"literal">++i</tt> should be used in place of the post-increment
here. For integers it makes no difference. For more complex
iterators it might do, so it is possibly better to stick to a
consistent style to save surprises later.</p>
<p>If we go back to the beginning of the student's code, we spot
that the main routine has been declared to return <tt class=
"literal">void</tt>. This is incorrect - it always returns
<span class="type">int</span>. My compiler, with warnings enabled,
tells me this and kindly(?) changes it to an integer return.</p>
<p>Then comes another &quot;magic&quot; constant. Why choose 20? Ah, it must
be that string being used to test again. This is problematic
because if the string were changed to &quot;I really need a lot of help
with C++.&quot; then that array of 20 characters is not going to be big
enough and all sorts of nasty things might happen. C++ has
inherited from C the ability to dynamically size arrays from their
initialisation lists, and also to initialise an array of chars by a
string, so we can use this to create enough space
automatically:</p>
<pre class="programlisting">
char str[] = &quot;Need help with C++.&quot;;
</pre>
<p>We then wonder why we should rely on the function <tt class=
"function">strlen</tt> to find the length. The compiler has already
does this for us to allocate the size of the array &quot;str&quot;, so we can
use the <tt class="literal">sizeof</tt> operator to get the value
at compile time, remembering that the <tt class=
"literal">sizeof</tt> operator will include the trailing null,
whereas <tt class="function">strlen</tt> does not. If we put this
into a constant then the compiler should use the literal value
rather than a variable:</p>
<pre class="programlisting">
int const len = sizeof(str) - 1;
</pre>
<p>The only proviso here is that if the literal string contained
embedded nulls then <tt class="function">strlen</tt> would only
count to the first such null, whereas <tt class=
"literal">sizeof</tt> uses the real number of characters in the
string.</p>
<p>The whole program now looks like this:</p>
<pre class="programlisting">
#include &lt;iostream&gt;
using namespace std;

int main() {
  char str[] = &quot;Need help with C++.&quot;;
  int const len = sizeof(str) - 1;
  // Ignore trailing null
  cout &lt;&lt; &quot;The sentence \&quot;&quot; &lt;&lt; str
       &lt;&lt; &quot;\&quot; has &quot; &lt;&lt; len
       &lt;&lt; &quot; characters&quot; &lt;&lt; endl &lt;&lt; endl;
  for(int i=0; i&lt;len; ++i)
    cout &lt;&lt; str + i &lt;&lt; endl;
  return 0;
}
</pre>
<p>Note that I have also removed the duplication of the string
embedded in the introductory output statement. That ensures that if
we change the test string then the output is consistent. Also the
header <tt class="filename">cstring</tt> is no longer required to
declare <tt class="function">strlen</tt>.</p>
<p>Although I would prefer not to include the whole of the
<tt class="literal">std</tt> namespace and instead specify
specifically which classes or functions I want, my compiler
includes the namespace as standard and so I cannot check for errors
if I omit some declarations. Therefore I have left this statement
in place.</p>
<p>OK, so that has fixed the initial problem, of removing the
duplicate <tt class="literal">cout</tt> statements. The student
said that he wanted to write the body of the loop as:</p>
<pre class="programlisting">
cout &lt;&lt; str[i+1];
</pre>
<p>for some value of <tt class="varname">i</tt>. This statement
only puts one character from the string onto the output and there
is no <tt class="literal">endl</tt> either. This indicates that the
requirement was to print out individual characters. There is rarely
a need to do this on a string, in real life, but as an exercise it
is useful to know how to access parts of the string, so I assume
that this is what is required. The student also mentions nested
<tt class="literal">for</tt>-loops, which also suggests that
individual character writing is wanted.</p>
<p>I wonder whether the requirement was stated as &quot;replace the
<tt class="literal">cout</tt> statements with a loop?&quot;, meaning
&quot;replace all <tt class="literal">cout</tt> statements with one
inside a loop&quot; while the student understood it to be &quot;replace each
<tt class="literal">cout</tt> statement with a loop of its own&quot;.
Such a misunderstanding would not be unusual.</p>
<p>Let us assume that the student's interpretation is correct, how
do we go about this? Each iteration in the loop, in its current
form, prints the string starting from the <tt class=
"varname">i</tt>'th element. The way that <span class=
"type">char*</span> strings are handled (also an inheritance from
C) means that all characters from the pointed-to one are printed,
until a null character is found, which is the same as saying until
the string length as defined by <tt class="function">strlen</tt> is
reached.</p>
<p>The inner loop plus the end-of-line should produce exactly what
the</p>
<pre class="programlisting">
cout &lt;&lt; str+i &lt;&lt; endl
</pre>
<p>line produced earlier, i.e. in pseudo-code:</p>
<pre class="programlisting">
<span class=
"emphasis"><em>for all characters from the i'th to the len'th
  print the character
print end-of-line</em></span>
</pre>
<p>Using the conventional counter name j (when the outer counter is
<tt class="varname">i</tt>), we get:</p>
<pre class="programlisting">
for(int j=i; j&lt;len; ++j)
  cout &lt;&lt; str[j];
cout &lt;&lt; endl;
</pre>
<p>Putting this inside the existing loop, I get:</p>
<pre class="programlisting">
for(int i=0; i&lt;len; ++i) {
  for(int j=i; j &lt; len; ++j)
    cout &lt;&lt; str[j];
  cout &lt;&lt; endl;
}
</pre>
<p>The <span class="type">char*</span> (and <span class=
"type">char</span> array) style strings are very much a legacy from
C and their use should really be discouraged when teaching C++ to
new students, who should be introduced to the <tt class=
"classname">std::string</tt> class instead. This student appears to
be trying to learn about loops rather than strings and so an array
of integers might have been more appropriate. Again, a <tt class=
"classname">std::vector</tt> might be even better, since this
provides more safety than a plain C array.</p>
<p>On the other hand, the student may be in an environment where
they are using C++ as &quot;a better C&quot; and steer clear of the more
complex aspects of C++. The sample code is very much along these
lines, since it only uses cout and the stream insertion operator
from C++, all the rest is plain C. From a C-programmer's point of
view, using C++ in this way is a natural progression - I would even
own up to doing it myself - but it does mean that some C ways of
doing things need to be re-learnt to use C++ to its fullest power.
If the student is in this sort of environment, then learning better
C++ techniques will do no harm, and may well lead the student to
become the local expert on C++. Helping others with their C++ will
enhance the knowledge of the teacher too, as Francis keeps trying
to tell us.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2>The Winner of
SCC 26</h2>
</div>
<p>The editor's choice is: <span class="bold"><b>Colin
Hersom</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">
<div>
<h2>Student Code
Critique 27</h2>
</div>
<div>
<h3>&lt;<a href=
"mailto:caabeiro@vodafone.es">caabeiro@vodafone.es</a>&gt;</tt> by
May 10th)</h3>
</div>
</div>
<p><span class="emphasis"><em>There are at least two issues with
this issue's problem code. The first is finding the immediate logic
error in the code that results in false positives. The second, to
my mind more important issue, is the student's approach to solving
the problem. It is relatively easy to learn to write syntactically
correct code but that is not programming any more than writing
grammatically correct English is writing poetry or a
novel.</em></span></p>
<p><span class="emphasis"><em>Please submit a critique of the code
as it is and then append a critique of the student's approach to
the problem s/he was set.</em></span></p>
<p>In this exercise an ugly number is defined as a compound number
whose only prime factors are 2, 3 or 5. Note that a factor can
repeat so 20 (2*2*5) is an ugly number. The following program
outputs ugly numbers correctly, but also outputs prime numbers. I
can't understand why this is happening because the pointer returned
by <tt class="function">pf()</tt> points to a zeroed 1st element of
the array <tt class="varname">flist</tt> when the input to
<tt class="function">pf()</tt> is prime. It should fail the
<tt class="literal">while()</tt> test and the next number should be
factored. I can kludge this with a separate test for primes, but I
would like to understand why it's not working as is.</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;
#define SIZE 20 /* max number of prime factors */
#define TWO 2
#define THREE 3
#define FIVE 5
int *pf(int number);

int main(int argc, char *argv[]) {
  int *flist,idx, n, ugly = 0;
  int start, stop;
  if(argc != 3) exit(EXIT_FAILURE);
  start = atoi(argv[1]); /*enter a range */
  stop = atoi(argv[2]);
  for(n = start; n &lt; stop +1; ++n) {
    idx = 0;
    flist = pf(n);
    while(flist[idx]) {
      if(flist[idx]==TWO ||flist[idx]==THREE
         ||flist[idx]==FIVE) {
        ugly = 1;
        ++idx;
      }
      else {
        ugly = 0;
        ++idx;
      }
    }
    if(ugly == 1)
      printf(&quot;%d\n&quot;, n);
    free(flist);
  }
  return 0;
}

/* find the prime factors of number */
int *pf(int number) {
  int *flist, quotient=0, divisor=2, idx=0;
  flist = calloc(SIZE, sizeof(int));
  while(divisor &lt; number + 1) {
    if(divisor == number){
      flist[idx] = quotient;
      /* add last factor to list */
      break;
    }
    if(number % divisor == 0) {
      flist[idx++] = divisor;
      quotient = number/divisor;
      number = quotient;
    }
    else ++divisor;
  }
  return flist;
}
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
