    <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</title>
        <link>https://members.accu.org/index.php/articles/1255</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">Student Code Critiques from CVu journal. + CVu Journal Vol 15, #6 - Dec 2003</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/c183/">Code Critique</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/c105/">156</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+105/">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</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 December 2003 13:16:02 +00:00 or Sat, 06 December 2003 13:16:02 +00:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a>The
problem</h2>
</div>
<p><span class="emphasis"><em>Curious what novices set out to do
but that should not stop us from trying to help them achieve their
objectives. I suspect that the writer of this is trying to grab the
console output and paste it into a file. Now we know what he should
be doing, but while helping him try to raise the code
quality.</em></span></p>
<p>I want to copy my C++ program output to an ASCII text file.</p>
<p>I store my data in arrays and then use cout to output the data
in DOS... as I generate data in the order of 1000's ...I am having
a problem with physically copy pasting the data into notepad (an MS
Windows pure text editor).</p>
<p>Here is my code...please suggest what changes are necessary. My
coding is not really that efficient. Please bear with me:</p>
<pre class="programlisting">
# include&lt;iostream.h&gt;
# include&lt;conio.h&gt;
# include&lt;math.h&gt;
# include&lt;iomanip.h&gt;
void main(){
  void clrscr();
  int i,r,j,m,x;
  static Sum[5000][5000];
  Sum[1][1]=25000;
  Sum[2][1]=35000;
// input the data into arrays
  for(j=2; j&lt;=11; j++)
    for(i=1; i&lt;=pow(2,j); i++) {
      if(i==1) {
        Sum[i][j] = Sum[i][j-1] + 25000;
        Sum[i+1][j] = Sum[i][j-1] + 35000;
      }
      if(i&gt;1) {
        Sum[i][j] = Sum[r][j-1] + 25000;
        r=r+1;
        Sum[i+1][j] =
              Sum[(i+1)/2][j-1] + 35000;
      }
      i=i+1;
      r=2;
    }
// output the data
  for(m=2; m&lt;=11; m++) {
    for(x=1;x &lt;= pow(2,m); x++) {
       for(i=1; i&lt;=2; i++) {
         cout &lt;&lt; x &lt;&lt; m
              &lt;&lt; setw(10) &lt;&lt; Sum[x][m] &lt;&lt; '\n';
       }
    }
    getch();
  }
}
</pre>
<p>My output reads:</p>
<pre class="screen">
  11 25000
  11 25000
  12 35000
  12 35000
</pre>
<p>so on..so forth</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e40" id="d0e40"></a>My
Comments</h2>
</div>
<p>This time our esteemed editor does not have to spend valuable
time offending those whose submissions are considered inferior to
the winner's because there was only one submission, which by
definition, has to be the winner. That is sad because I guess that
many more of you could have had a go. Yes, many winners write well
but so do many who do not win and as I have written before, it is
participating that is the biggest reward. In order to provide an
alternative I asked my friend who writes as the Harpist to have a
look and provide his thoughts.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e45" id="d0e45"></a>The Harpist's
Response</h2>
</div>
<p>I notice that in setting the problem Francis asked that we focus
on helpful advice to the author. So here goes:</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e50" id="d0e50"></a>A Clear Statement
of Intent</h3>
</div>
<p>Before writing a single line of code you need to have a clear
idea about what you are trying to produce. In this case it seems
that the objective is to produce a file of values generated by some
form of generator. I am certain that the actual code does not do
what the programmer thinks because it is littered with quirky bits.
If it did actually generate the desired values it would be pure
chance.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e55" id="d0e55"></a>Understand Your
Tools</h3>
</div>
<p>Fundamentally there are two ways to create an output file. The
first way is to have the program create the required file. The
second way that is often forgotten is to simply capture the program
output into a file. What you do not do (or only very rarely) is to
capture the output from the screen and paste it into a file. It
seems that the student has been trying to use this last method.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e60" id="d0e60"></a>Write Portable
Code</h3>
</div>
<p>There are times when we have to fall back on implementation
specific features and library functionality but they are much less
common than most students believe.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e65" id="d0e65"></a>Never Do Things
Till You Have To</h3>
</div>
<p>That almost speaks for itself so I will just leave it as a
thought to put alongside 'Do things in time.'</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e70" id="d0e70"></a>Applying These
Principles</h3>
</div>
<p>Here is my rewritten code up to the student's first comment:</p>
<pre class="programlisting">
# include&lt;iomanip&gt;
# include&lt;iostream&gt;
int main() {
  static int sum[5000][5000];
  sum[1][1]=25000;
  sum[2][1]=35000;
</pre>
<p>Two of the header files go. We do not need <tt class=
"filename">conio.h</tt> because we are not going to use the screen
as some intermediary for getting the output where we want it.
Looking forward I realise that the programmer only needed
<tt class="filename">math.h</tt> to give him access to the
declaration of <tt class="function">pow()</tt>. Using that function
to compute successive powers of two is overkill. It is the kind of
overkill that inexperienced programmers are very prone to. They
think 'power of two' and forget that what they needed was 'next
power of two' which is simply two times the current one.</p>
<p>While I was about it I replaced the header files with the
equivalent Standard C++ headers.</p>
<p>Next I tidied up the declaration of <tt class=
"function">main()</tt> to return the required <tt class=
"function">int</tt>, and threw out the definitions of <tt class=
"varname">i</tt> etc. because this is far too early to be declaring
single letter variables (I have nothing against them but they
should always be declared in the context of their use.) Even C now
allows that. <tt class="function">clrscr()</tt> went because it
serves no useful purpose.</p>
<p>I think the student was getting away with an implicit <tt class=
"function">int</tt> in the declaration of <tt class=
"varname">Sum</tt>, which I have amended to <tt class=
"varname">sum</tt> because I cannot abide gratuitous use of upper
case. In case you are wondering, removing the <tt class=
"function">static</tt> storage class specifier would result in
undefined behaviour because the array would not have been
initialised. Of course there are other ways of ensuring that an
array is fully initialised.</p>
<p>In passing, I feel profoundly uncomfortable with that
requirement for storage for twenty-five million <tt class=
"function">int</tt>s. I am sure that a correct analysis of the
required computation will demonstrate that a much less memory
demanding approach is viable.</p>
<p>Now let me look at the computation section. This definitely can
do with some restructuring because, frankly, it is currently a
hacked together mess.</p>
<pre class="programlisting">
int i_limit = 4;
for(int j=2; j != 12; ++j, i_limit *=2) {
  sum[1][j] = sum[1][j-1] + 25000;
  sum[2][j] = sum[1][j-1] + 35000;
  for(int i=3; i&lt;= i_limit; i += 2) {
    sum[i][j] = sum[2][j-1] + 25000;
    sum[i+1][j] = sum[(i+1)/2][j-1] + 35000;
  }
}
</pre>
<p>Where has the <tt class="varname">r</tt> gone? Careful analysis
of the control flow of the original code showed that <tt class=
"varname">r</tt> was always 2 when used. I find that very
suspicious and think that it probably should have been equal to
<tt class="varname">i</tt>. However the point I would make to the
student is that by cleaning up the code we can see what is
happening. This will make it much easier to correct errors in the
code. That '2' where <tt class="varname">r</tt> was sticks out like
a sore thumb. Indeed I suspect that the correct code should be:</p>
<pre class="programlisting">
int i_limit = 4;
for(int j=2; j != 12; ++j, i_limit *=2) {
  for(int i=1; i&lt;= i_limit; i += 2) {
    sum[i][j] = sum[i][j-1] + 25000;
    sum[i+1][j] = sum[(i+1)/2][j-1] + 35000;
  }
}
</pre>
<p>Once we have it down to this level, we can see that the original
dimensions of <tt class="varname">sum</tt> are ridiculous. In fact
he has 10 sets of results, each set solely dependant on the
immediately prior set. Allowing indexing from 1 rather than 0 and
not even attempting to optimise storage we get:</p>
<pre class="programlisting">
static int sum[2049][12];
</pre>
<p>as being entirely sufficient. This reduces the storage
requirement to something reasonable on most hardware (around about
a hundred thousand bytes on a platform using 4-byte <tt class=
"function">int</tt>s.</p>
<p>Finally let me look at the output section. This also has its
oddities. Here is my rewritten version:</p>
<pre class="programlisting">
i_limit = 2; // reset to initial value
for(int j=1; j != 12; ++j, i_limit *= 2) {
  for(int i=1; i &lt;= i_limit ; ++i){
    std::cout &lt;&lt; i &lt;&lt; j &lt;&lt; std::setw(10)
              &lt;&lt; sum[i][j] &lt;&lt; '\n';
    std::cout &lt;&lt; i &lt;&lt; j &lt;&lt; std::setw(10)
              &lt;&lt; sum[i][j] &lt;&lt; '\n';
  }
}
</pre>
<p>Now why the student wants to output the values of <tt class=
"varname">i</tt> and <tt class="varname">j</tt> without an
intermediate space, and why he wants to output each result twice
will for ever remain a mystery but the process of cleaning up his
code makes it quite clear that that is exactly what he does. By the
way, for consistency I changed the output loop so that it will
display the initial data as well as the computed data.</p>
<p>Now I suspect that all the code mangling came about while the
student struggled to solve the problem of getting the output into a
text file. His mind was so focused on trying to cope with this that
everything else went up in flames. So how to get the data into a
file? Simply, invoke the program with:</p>
<pre class="programlisting">
program &gt; data.txt
</pre>
<p>Which I think makes it clear that the student actually needed a
very different answer from the one he was asking for.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e173" id="d0e173"></a>Student Code
Critique 24 from Roger Orr <tt class="email">&lt;<a href=
"mailto:rogero@howzatt.demon.co.uk">rogero@howzatt.demon.co.uk</a>&gt;</tt></h2>
</div>
<p>&quot;Hmm&quot;, said Bill, &quot;I wonder what this program does. Any ideas,
Jim?&quot;</p>
<p>Jim came over and stared at Bill's screen. &quot;Well&quot;, he said, &quot;all
the user wants is to be able to copy the output to an ASCII text
file. Does it matter what it does?&quot;</p>
<p>Bill thought a moment and then said, &quot;Yes, it does matter -
partly for professional pride but also to try and understand what
he means here where he writes 'my coding is not really that
efficient'&quot;.</p>
<p>Jim looked puzzled and tentatively suggested that it didn't
matter - surely the code was just a bit slow and so what it was
doing was irrelevant since you obviously don't need to understand
the purpose of code to make it faster.</p>
<p>&quot;No, I'm afraid you've missed the point of my remark- efficiency
is not necessarily anything to do with speed. In this case the user
is currently pasting data into notepad - the speed of the program
is a tiny part of the overall time. I suspect the user is actually
worried about either the inefficient use of memory or the amount of
effort it took turn the original formula into code. Look, I'll show
you what I mean.&quot;</p>
<p>Bill turned to the keyboard, compiled the sample code and ran
the program. There was a long pause.</p>
<p>&quot;You're wrong&quot;, said Jim, &quot;look how long it's taking to get
anywhere - what is the program doing?&quot; Bill simply pointed to the
CPU meter, which was showing almost zero, and said &quot;No, it's not
busy - what is it waiting for? &hellip;Ah of course, silly me.&quot;</p>
<p>With that he leaned on the space bar and almost immediately the
screen filled with numbers.</p>
<p>&quot;The problem is the mix of I/O since the output uses the C++
streams library - well, an old one anyway - which buffers up output
to write many characters at once for speed, but the input uses a
non-standard low-level C runtime call. It isn't a good idea to pair
up buffered output and unbuffered input. It looks like the user
really wanted to all the pending output to appear each time before
waiting for a keypress. Oh well, so much water under the bridge -
we want to write the entire output to an ASCII text file now so
there's no need to wait - I'll remove the <tt class=
"function">getch()</tt> call and the <tt class="filename">#include
of conio.h&quot;</tt>.</p>
<p>Bill applied himself to the keyboard, and made these two
changes. He then noticed that the '<tt class=
"function">clrscr()</tt>' function was not in fact needed, so
removed that line too. &quot;Just reversing entropy&quot;, he muttered to
himself, &quot;gets in everywhere doesn't it?&quot;</p>
<p>He then decided to bring the program into the world of the C++
standard. This meant making '<tt class="function">void main()</tt>'
become '<tt class="function">int main()</tt>' and then changing the
old includes '<tt class="filename">iostream.h</tt>' and '<tt class=
"filename">iomanip.h</tt>' to the new ones '<tt class=
"filename">iostream</tt>' and '<tt class="filename">iomanip</tt>'.
Of course, the standard C++ streams library is in the namespace
'<tt class="classname">std</tt>' so he had to added '<tt class=
"classname">std::</tt>' before '<tt class="classname">cout</tt>'
and '<tt class="classname">setw</tt>'.</p>
<p>&quot;Ok, let's try that&quot;, he said, &quot;Oh &hellip; our output doesn't
match what the user says he gets - odd. Perhaps I've broken
something&hellip;.no - look - the output loop starts with
<tt class="varname">m=2</tt> but the user's output starts with
'<tt class="constant">11</tt>'. Looks like the code he sent us
doesn't match what he's actually using. Not the first time, eh? Now
we really do need to know what the program does so we can decide
whether the program or the sample output is wrong - or both of
course! Ok, for now we'll change the second loop to start with
<tt class="varname">m=1</tt> and now the results do look like what
the user wants. Hey, look here - this variable '<tt class=
"varname">r</tt>'. The first time round the input loop it isn't
used, just set to 2. All the other times round the loop it is used,
then incremented, and then reset to 2. I wonder if that is really
right? For now I'll put a warning comment in the margin.&quot;</p>
<p>&quot;Right, now we're ready. Here goes&quot;. Bill opened a command
prompt and typed:</p>
<pre class="programlisting">
scc24 &gt; x.txt
</pre>
<p>&quot;That's got the output into a text file&quot;, he said.</p>
<p>&quot;Isn't that cheating - doesn't the user want to do that with
C++?&quot;, Jim objected.</p>
<p>&quot;He is using C++&quot;, said Bill, &quot;and we're simply using the
features of his chosen environment. KISS.&quot;</p>
<p>&quot;Pardon??&quot;</p>
<p>&quot;Keep It Simple, Stupid&quot;, explained Bill, &quot;Why write code when
you don't have to? Let the operating system solve that part of the
problem! Now let's send the user the tidied-up program and
instructions on how to run it.&quot;</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e267" id="d0e267"></a>The Winner of
SCC 24</h2>
</div>
<p>The editor's &quot;choice&quot; is:</p>
<p><span class="bold"><b>Roger Orr</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="d0e280" id="d0e280"></a>Student Code
Critique 25</h2>
</div>
<p>(Submissions to <tt class="email">&lt;<a href=
"mailto:francis@robinton.demon.co.uk">francis@robinton.demon.co.uk</a>&gt;</tt>
by Jan. 14th)</p>
<p>It is always worth sending in a late entry, depending on my
workload it may or may not be considered for the prize but it will
eventually get published.</p>
<p>This time I am presenting two short C programs. Please attempt
to critique either or both of them.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e292" id="d0e292"></a>Program 1</h3>
</div>
<p>I am little confused about return values of sizeof operator.
Here is a simple C program which is putting me in doubt:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
int main() {
  int a[10];
  int *p =(int *) malloc (10);
  printf(&quot;Size of a = %d \n&quot;,sizeof(a));
  printf(&quot;Size of p = %d \n&quot;,sizeof(p));
}
</pre>
<p>Output is :</p>
<pre class="screen">
Size of a = 40
Size of p = 4
</pre>
<p>My understanding says even array name is a pointer. If so why it
does not show <tt class="function">sizeof(a)</tt> as <tt class=
"constant">4</tt>? Or if <tt class="function">sizeof</tt> shows the
total allocated memory then why <tt class="function">sizeof(p)</tt>
does not show <tt class="constant">10</tt>?</p>
<p><span class="emphasis"><em>There are numerous errors in both the
code and the student's understanding. Please address these
comprehensively, perhaps including places where your explanation
would be different if this were a C++ program.</em></span></p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e323" id="d0e323"></a>Program 2</h3>
</div>
<p>I am getting an error linker error. Here is the code:</p>
<pre class="programlisting">
// Define Libraries
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
//Start Of Main Program
main(){
  double hypo, base, height;
/* Enter base and height */
  printf(&quot;Enter base:&quot;);
  scanf(&quot;%f&quot;, &amp;base);
  printf(&quot;Enter height:&quot;);
  scanf(&quot;%f&quot;, &amp;height);
  hypo = sqrt(pow(base, 2)+pow(height, 2));
  printf(&quot;hypotenuse is %f&quot;, &amp;hypotenuse);
}
</pre>
<p><span class="emphasis"><em>Ignore the question asked by the
student and address the serious problems with the code
itself.</em></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
