    <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/1224</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, #3 - Jun 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/c108/">153</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+108/">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 June 2003 13:15:58 +01:00 or Fri, 06 June 2003 13:15:58 +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="d0e13" id="d0e13"></a></h2>
</div>
<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="d0e21" id="d0e21"></a>Student Code
Critique 21</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e24" id="d0e24"></a>The problem</h3>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>I'm creating a program that inputs three integers, and returns
the sum, product, average, largest and smallest. Very simple, but
I'm getting a bad return on one of my variables. Except for my
&quot;largest&quot; variable, the others are returning the correct numbers.
I'm hoping that someone can tell me where I'm going wrong.</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
int main(){
  int num1, num2, num3, sum, average
  int product, smallest, largest;
  puts(&quot;Input three different integers: &quot;);
  scanf(&quot;%d, %d, %d&quot;,&amp;num1,&amp;num2,&amp;num3);
        // read three integers
  sum = num1 + num2 + num3;
  average = ((num1 + num2 + num3)/ 3 );
  product = num1 * num2 * num3;
  if(num1 &lt; num2 ) smallest = num1;
  if(num2 &lt; num1 ) smallest = num2;
  if(num3 &lt; smallest ) smallest = num3;
  if(num1 &gt; num2 ) largest = num1;
  if(num2 &gt; num1 ) largest = num2;
  if(num3 &gt; largest ) largest = num3;
  printf(&quot;\nSum is %d&quot;,sum);
  printf(&quot;\nAverage is %d&quot;,average);
  printf(&quot;\nProduct is %d&quot;,product);
  printf(&quot;\nSmallest is %d&quot;,smallest);
  printf(&quot;\nLargest is %d\n&quot;,largest);
  return 0;
}
</pre></blockquote>
</div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e32" id="d0e32"></a>Critiques</h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e35" id="d0e35"></a>From The
Harpist</h4>
</div>
<p>Please note that I am only doing this as a favour to Francis and
not as a competition entry.</p>
<p>I am going to assume that this student has just started and is
attempting one of those ridiculous exercises that thoughtless
authors and instructors set. I assume that the student has not yet
learnt about arrays.</p>
<p>Clearly the student has been taught that the structure of a
program is:</p>
<div class="literallayout">
<p>Input<br>
Compute<br>
Output</p>
</div>
<p>This is the kind of brain deadening guideline that results in
bad code. For example, it is because of this that the program
declares three similar variables whose only difference is the order
in which they acquire values from input. In fact almost all the
student's problems are directly attributable to this 'design'
decision. Experience teaches me that the instructor will probably
be entirely happy with this aspect of the program and waste time on
the implementation faults that arise because of it.</p>
<p>Yes, the student should have used the largest available integer
type for input (assuming that the question specified input). The
student should have considered that an average would generally be
of a floating-point type. There is also the issue that when
computing the product, we might get overflow. I am going to ignore
these issues because it is likely that the student simply does not
have the tools to cope with such issues. For example how do you
detect overflow when dealing with integer multiplication? Note that
actually overflowing an integer type results in undefined
behaviour. (The best solution I can come up with is to do all the
computation in a long double, check that the result is within the
range of a <span class="type">long int</span> - expressed as a
<span class="type">long double</span> - and finally convert the
result to a <span class="type">long int</span> - assuming that an
integer result is required. Such programming techniques are way
beyond what we should expect from a student who does not yet know
about arrays and loops.)</p>
<p>Anyway here is my solution with commentary:</p>
<pre class="programlisting">
int main() {
  long int number = 0;
  long int largest = LONG_MIN;
  long int smallest = LONG_MAX;
// The above is an idiom for use when you are
// going to compute a largest/smallest value,
// initialise to the smallest/largest possible
  long int sum = 0;
  long int product = 1;
  puts(&quot;WARNING: If you give inappropriate \n&quot;
       &quot;values to this program you\n&quot;
       &quot;will get silly results\n&quot;);
// Note the use of puts to supply pure text
// output and the use of quotes to deal with a
// multiline text statement.
  puts(&quot;Type in a whole number: &quot;);
  scanf(&quot;%d&quot;, &amp;number);
// scanf is a poor function for general use
// but with the Student's likely state of
// knowledge it is appropriate. However
// warnings should be given that this is not
// a desirable long term mechanism.
  if(number &gt; largest) largest = number;
  if(number &lt; smallest) smallest = number;
  sum += number;
  product *= number;
// The above give an opportunity to discuss
// C's compound assignments and the need to
// use initilaised variables
// The following is simply a copy and paste of
// the above input and processing code
  puts(&quot;Type in a whole number: &quot;);
  scanf(&quot;%d&quot;, &amp;number);
  if(number &gt; largest) largest = number;
  if(number &lt; smallest) smallest = number;
  sum += number;
  product *= number;
  puts(&quot;Type in a whole number: &quot;);
  scanf(&quot;%d&quot;, &amp;number);
  if(number &gt; largest) largest = number;
  if(number &lt; smallest) smallest = number;
  sum += number;
  product *= number;
// Now output the results:
  printf(&quot;\nThe sum is %d&quot;,sum);
  printf(&quot;\nThe mean is is %d&quot;,sum/3);
  printf(&quot;\nThe product is %d&quot;,product);
  printf(&quot;\nThe smallest is %d&quot;,smallest);
  printf(&quot;\nThe largest is %d\n&quot;,largest);
  return 0;
}
</pre>
<p>Please notice that this code is a very good way to introduce the
concept of a for-loop as a way to avoid repetitious source code.
Once the code has been rewritten with a for-loop it can be
developed to handle more input, both by hardcoding the number of
items and by obtaining the number of items interactively.</p>
<p>Unless we are going to re-use the input (for example by sorting
it) there is no need for the student to know about arrays. Indeed I
would contend that using an array for a question such as this one
is overkill, not least because it requires the introduction of
dynamic memory management if the question is generalised to user
determined amounts of input.</p>
<p>However, were I mentoring students in C++ I would give any
student who submitted such a pure C solution a very low grade. Why?
Well I believe that students who head off in this direction are
actually making their C++ progress much harder by being
pre-occupied with low-level detail (such as the use of the
address-of operator with scanf()). Yes, it is important that a
student who presented the original code should be helped to
understand why the code fails to work as expected. But the most
important lesson is that bad design leads to logic errors. In this
case there is no inherent difference between the three inputs and
yet the submitted program handles them as if they were somehow
different.</p>
<p>What saddens me is the frequency with which such opportunities
to develop a student's design insights are ignored by tutors. It
should not be four times more difficult to write a program that
handles four numbers rather than three, and yet that, basically, is
the consequence of the original design. Even without knowing about
a for-loop, my design can be extended with a single copy/paste
operation. That is not to encourage such, but to demonstrate that
the solution of the problem for three inputs should generalise to
the solution for n inputs. If it does not, it is a poor
solution.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e71" id="d0e71"></a>Critique by
Catriona O'Connell <tt class="email">&lt;<a href=
"mailto:catriona38@hotmail.com">catriona38@hotmail.com</a>&gt;</tt></h4>
</div>
<p>The problem domain is not well-defined. The mathematical meaning
of integer and the C language definition of integer are different.
Problems of overflow can be minimised by using the largest possible
representation (<span class="type">long</span>) instead of
<span class="type">int</span>. However the GNU C compiler defines
<tt class="literal">INT_MAX</tt> and <tt class=
"literal">LONG_MAX</tt> to be the same value (2147483647), so this
doesn't necessarily help. The likelihood of problems might be
further reduced by using compiler extensions. For example the GNU C
compiler supports &quot;<span class="type">long long int</span>&quot; with a
maximum value of 9223372036854775807. The only way to avoid
problems would be to read the input as a string. It would then need
to be converted and processed using multiple-precision (MP)
arithmetic routines. This is not likely to be within the student's
ability. Without using MP routines there is no portable way to
determine if arithmetic overflow or underflow occurs. If this
happens then the results are undefined.</p>
<p>The user is asked to enter three different integers, but no
check is made for uniqueness. This is important for the comparisons
that are made to determine the largest and smallest numbers. If
<tt class="literal">num1==num2</tt> then smallest/largest will have
initial value (0), so depending on the sign of <tt class=
"varname">num3</tt>, the returned value could be wrong.</p>
<p>In the <tt class="function">scanf()</tt> format string it is
probably a mistake to include the commas. This forces the user to
separate the input integers with commas. Since <tt class=
"function">scanf()</tt> is already smart enough to bypass
whitespace it would be sufficient to specify that the numbers be
space-separated. If commas are required, then the user should be
told of this.</p>
<p>The only reason I can see to read in all three numbers at the
same time is that it avoids the problem of excess characters being
left in the input buffer. This would cause problems if <tt class=
"function">scanf()</tt> were called multiple times. The student
would either have to program in assignment to a string for the
remainder of the buffer or be introduced to the delights of
nonassigning <tt class="function">scanf()</tt> calls such as</p>
<pre class="programlisting">
scanf(&quot;%*[^\n]&quot;); // skip to end of line.
scanf(&quot;%*1[\n]&quot;); // skip one newline character.
</pre>
<p>to clear the input buffer.</p>
<p>The student does not check the return code from <tt class=
"function">scanf()</tt> to ensure that three integers have been
assigned before using what he/she thinks is valid input. This is a
major error. It is almost impossible to recover gracefully from bad
input using <tt class="function">scanf()</tt> but it is even worse
to plough on regardless.</p>
<p><tt class="function">scanf()</tt> should not really be used for
interactive user input. If you are going to use it then it should
be restricted to reading well-defined structure input - preferably
computer-generated output. When you have enough experience to know
how to use <tt class="function">scanf()</tt> safely, then you
probably know enough to avoid using it. There are very few cases
where <tt class="function">fgets()</tt>/<tt class=
"function">sscanf()</tt> cannot replace <tt class=
"function">scanf()</tt>.</p>
<p>A better solution avoids the use of <tt class=
"function">scanf()</tt> and instead uses a combination of
<tt class="function">fgets()</tt> to read a buffer of input and
<tt class="function">sscanf()</tt> to parse that buffer. <tt class=
"function">fgets()</tt> has the advantage of <tt class=
"function">gets()</tt> in that the buffer will not overflow, but
input may be truncated if it is longer than the buffer. <tt class=
"function">sscanf()</tt> works like <tt class=
"function">scanf()</tt> except that it reads formatted data from a
string instead of <tt class="literal">stdin</tt>.</p>
<p>The student's method for finding the largest and smallest values
does not scale well. The sum, product, largest and smallest values
can be calculated as running values, avoiding the need to have all
three integers entered at the same time. The average is calculated
as the sum divided by the number of integers entered. There is no
need to recompute the sum for this calculation. The problem domain
does not define if an integer average is acceptable or whether a
<span class="type">double</span>/<span class="type">float</span>
would be more appropriate. The variable average could be defined as
<span class="type">double</span> and the average calculated as
<tt class="literal">sum/3.0</tt>.</p>
<p>The accompanying code is my attempt at a re-write using
<tt class="function">fgets()</tt>/<tt class=
"function">sscanf()</tt> with return code checking.</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;limits.h&gt;
#define LOOP_COUNT 3
#define BUF_SIZE 80

int main() {
  long num, sum, average;
  long product, smallest, largest;
  char buffer[BUF_SIZE];
  int i;
  int gotint;
  sum = 0;
  product = 1;
  average = 0;
  largest = LONG_MIN;
  smallest = LONG_MAX;

  for(i=0; i&lt;LOOP_COUNT; ++i) {
    gotint = 0;
    while(!gotint) {
      printf(&quot;Input integer %d :&quot;, i+1);
      if(fgets(buffer, BUF_SIZE, stdin) != NULL) {
        if(sscanf(buffer, &quot;%ld&quot;, &amp;num) == 1) {
          gotint = 1;
        }
        else {
          printf(&quot;Error in sscanf()\n&quot;);
        }
      }
      else {
        printf(&quot;Error in fgets()\n&quot;);
      }
    }
    sum += num;
    product *= num;
    if(num &lt; smallest) smallest = num;
    if(num &gt; largest) largest = num;
  }
  average = sum/LOOP_COUNT;
  printf(&quot;\nSum: %ld&quot;, sum);
  printf(&quot;\nPrd: %ld&quot;, product);
  printf(&quot;\nAvg: %ld&quot;, average);
  printf(&quot;\nSml: %ld&quot;, smallest);
  printf(&quot;\nLge: %ld&quot;, largest);
  return 0;
}
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e195" id="d0e195"></a>By Anon</h4>
</div>
<p>The first thing I noticed was the amount of code duplication. If
the number of integers was changed from three then a comparatively
large amount of change would be required to update the code.</p>
<p>The student appears to have split the code into distinct parts,
one for input, a second for processing and a third for output,
which is laudable. To keep this structure means all the inputs must
be held until the input is complete; the obvious choice would be to
replace the individual <tt class="varname">num1</tt>, <tt class=
"varname">num2</tt>, <tt class="varname">num3</tt> variables with
an array, but we have been told that arrays are not
appropriate.</p>
<p>This suggests that the design should be changed to combine the
input and processing stages so that each input is consumed and
discarded in a loop, with the variables being reused each iteration
and the results generated incrementally.</p>
<p>As for the results being wrong I initially thought of overflow
in the addition and multiplication but we are told these are
correct, it is in fact the largest value that is wrong. Looking
again at the three lines calculating the largest value it appears
it could go wrong if <tt class="literal">num1==num2</tt>, in which
case neither of the first two lines will fire and largest will be
uninitialised, the result of the comparison with num3 is therefore
random. The student may have covered this by prompting the user for
different integers but this is a very weak check. The same fault
should be true of the calculation of the smallest value as the code
is very similar, but we are told this is ok. A possible explanation
is that the test numbers are likely to be small, and that the
random values in uninitialised variables are unlikely to be zero in
all the most significant bytes.</p>
<p>I wonder if the programmer is used to <tt class=
"literal">else</tt> clauses in the statements. Rather than reverse
the operands as in the first two lines of the smallest and largest
calculations, they could instead write:</p>
<pre class="programlisting">
if(num1&gt;num2);
largest=num2;
else
largest=num2;
</pre>
<p>This would also overcome the problem with not coping with the
<tt class="literal">num1==num2</tt> case.</p>
<p>[<i><span class="remark">Look again, this has another bug, and
one that will not always be detectable by the compiler.
Francis</span></i>]</p>
<p>As I have already decided this should be compressed into a loop,
there will only be a single condition updated each loop.</p>
<pre class="programlisting">
if(newvalue&gt;largest)
  largest=newvalue;
</pre>
<p>This presents the problem of how to ensure the first input is
always assigned to <tt class="varname">largest</tt>. Here are two
possible suggestions, either add special case code for the first
loop:</p>
<pre class="programlisting">
if(loop count == 0)
  largest=newvalue;
else {
  if(newvalue&gt;largest)
    largest=newvalue;
}
</pre>
<p>Alternatively, and my preference, is to initialise largest with
<tt class="literal">INT_MIN</tt> from <tt class=
"filename">&lt;limits.h&gt;</tt> This is guaranteed to be small as
the smallest input so the condition will work as expected.
<tt class="literal">INT_MAX</tt> can be used for smallest.</p>
<p>Similarly the sum can be initialised to zero and product to one
and both updated on each loop.</p>
<p>Finally there is the input method, which dictates how the
program is used. Currently the input is separate from the command
line so the user types:</p>
<pre class="screen">
name of executable (return)
3 2 1 (return) (or some other 3 numbers).
</pre>
<p>Is this is what is desired? Or should it run</p>
<pre class="screen">
name of executable 3 2 1 (return)
</pre>
<p>in which case the numbers should be extracted from <i class=
"parameter"><tt>argc</tt></i> and <i class=
"parameter"><tt>argv</tt></i> rather than a <tt class=
"function">scanf</tt>. The numbers could even be input one per
line:</p>
<pre class="screen">
name of executable (return)
3 (return)
2 (return)
1 (return)
</pre>
<p>This obviously depends on the user requirements. Seeing as this
is a student assignment the exact method is probably less important
than understanding the alternatives - so I will leave it as it
is.</p>
<p>Not having programmed in C for a few years I vaguely remember
something about preferring <tt class="function">atoi</tt> over
<tt class="function">scanf</tt> for <span class="type">int</span>s,
but I cannot remember the rationale for this so I will stick with
<tt class="function">scanf</tt>.</p>
<p>The code definitely does need some input validation, the code
expects three inputs but there is no check that <tt class=
"function">scanf</tt> received them. The concept of never trusting
user input is fundamental. At a minimum the <tt class=
"function">scanf</tt> return should be checked, this will be equal
to the number of variables successfully assigned.</p>
<p>Putting all these changes together with a few smaller items such
as separating the constant 3, we get</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;limits.h&gt;
#define NUM_INPUTS 3

int main(void) {
  int product = 1;
  int smallest = INT_MAX;
  int largest = INT_MIN;
  int sum =0;
  int count;
  printf( &quot;Input %d integers&quot;, NUM_INPUTS );
  for(count = 0; count&lt;NUM_INPUTS; ++count) {
    int num;
    if(scanf(&quot;%d&quot;, &amp;num) != 1) {
      puts(&quot;error reading input&quot;);
      return 1;
    }
    product *= num;
    sum += num;
    if(num &lt; smallest) smallest = num;
    if(num &gt; largest) largest = num;
  }
  printf(&quot;\nSum is %d&quot;, sum);
  printf(&quot;\nProduct is %d&quot;, product);
  printf(&quot;\nSmallest is %d&quot;, smallest);
  printf(&quot;\nLargest is %d&quot;, largest);
  printf(&quot;\nAverage is %d\n&quot;, sum/NUM_INPUTS);
  return 0;
}
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e308" id="d0e308"></a>From Walter
Milner <tt class="email">&lt;<a href=
"mailto:w.w.milner@bham.ac.uk">w.w.milner@bham.ac.uk</a>&gt;</tt></h4>
</div>
<p>This is a good attempt at a solution for which you deserve
credit. However there are several details of your code which
require comment, and the overall design could be improved.</p>
<p>Firstly the details. Your declaration:</p>
<pre class="programlisting">
int num1, num2, num3, sum, average
</pre>
<p>omits a trailing semi-colon, but since you are implying your
code compiles, I assume it was there and has somehow got lost.</p>
<p>There are several issues raised by</p>
<pre class="programlisting">
puts(&quot;Input 3 different integers: &quot;);
scanf(&quot;%d, %d, %d&quot;, &amp;num1, &amp;num2, &amp;num3);
</pre>
<p>If you remember, we discussed in class the limitations of scanf
for input in real code. The first point is that the commas in the
format string &quot;<tt class="literal">%d, %d, %d</tt>&quot; will need to
match up with commas separating data values in what the user types
in - in other words we are hoping the user enters something
like:</p>
<pre class="screen">
1, 2, 3 &lt;return&gt;
</pre>
<p>If they omit the commas you get a result like:</p>
<pre class="screen">
Input 3 different integers:
1 2 3
Sum is -1717986919
Average is -572662306
Product is 687194768
Smallest is -858993460
Largest is 1
</pre>
<p>The use of a comma is made worse by the possibility that the
user may separate thousand by using a comma, such as</p>
<pre class="screen">
1,000 2,000 3,000 &lt;return&gt;
</pre>
<p>These problems would be partly solved by changing the prompt to
something like 'Enter three different integers separated by
commas'. However users do not always obey instructions, and good
code should cope with this. In other words, data input should be
<span class="emphasis"><em>validated</em></span>. For example
suppose the user enters just 2 numbers, or non-integers, or numbers
which are equal? Real code would check this, for example by
inputting the data as a string, and then parsing it to check that
it did consist of three different integers. We will look at this in
detail in a later class.</p>
<p>The line</p>
<pre class="programlisting">
average=((num1+num2+num3)/3);
</pre>
<p>also contains several points. Firstly, the outermost pair of
brackets is superfluous. Secondly you have just calculated</p>
<pre class="programlisting">
num1 + num2 + num3
</pre>
<p>so why do it again - in other words say</p>
<pre class="programlisting">
average = sum/3;
</pre>
<p>Thirdly we have a major point about <span class=
"emphasis"><em>data type</em></span>. Suppose the user entered 1, 2
and 5. The average of these is 2.6667, which is not an integer. In
other words average needs to be a floating point type, single or
double. But even this is not enough, since</p>
<pre class="programlisting">
double average;
...
average=sum/3;
...
printf(&quot;\nAverage is %lf&quot;, average);
</pre>
<p>still gives 2.0000 for input of 1, 2 and 5. The problem is that
<tt class="literal">sum/3;</tt> is the division of an integer by
another integer, and the compiler uses integer division, which is
'guzinter', as in 5 guzinter 21 4 times remainder 1. If we want the
compiler to generate code for floating point division, one way to
do this is <tt class="literal">average = sum/3.0;</tt></p>
<p>If we divide by 3.0 (a floating point constant) rather than 3
(integer) the compiler converts sum to floating point, then uses
floating point division as we want. The difference between 3 and
3.0 is a small point (as it were) but an important one.</p>
<p>Another issue is the question of overflow. For example:</p>
<pre class="screen">
Input 3 different integers:
2000, 2001, 2002
Sum is 6003
Average is 2001.000000
Product is -577930592
Smallest is 2000
Largest is 2002
</pre>
<p>because on a system with 32 bit <span class="type">int</span>s
the product is larger than the largest integer which can be
represented. This cannot be fixed by say using <span class=
"type">long</span> instead of <span class="type">int</span> - we
could still input a value that was too large. We will see in a
later class that <tt class="filename">&lt;limits.h&gt;</tt>
contains a value for <tt class="literal">INT_MAX</tt> that we can
use to deal with this.</p>
<p>Then we turn to the overall design - which in this case is not
related to language-specific details. The overall plan of your code
is</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>input the 3 values</p>
</li>
<li>
<p>process them to calculate the required values</p>
</li>
<li>
<p>output the results</p>
</li>
</ol>
</div>
<p>The key question is about the storage of the input values - do
we need to store all three values <span class="emphasis"><em>at the
same time</em></span>? Or could we deal with them <span class=
"emphasis"><em>one at a time</em></span>, using this kind of
plan:</p>
<pre class="programlisting">
for each value
  input it
  process it
</pre>
<p>Now some kinds of process require all values to be available.
For example if we needed to find the standard deviation of some
numbers, we need to calculate how far each is from the mean, so we
need to first find the mean, then calculate the distance from the
mean. Unless we input them all twice, this requires us to hold all
values in memory at the same time. Similarly sorting them requires
all values to be available at the same time.</p>
<p>But in this case by using an idea like 'the biggest one so far'
we can do all the processing with only one value in memory at any
one time. For example -</p>
<pre class="programlisting">
input first value
biggest so far = first value
  for the rest
    if new value &gt; biggest so far
      biggest so far = new value
</pre>
<p>We can do the equivalent for the smallest, the product, the
total, and hence the average. Why bother? Because with this new
design</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>It is trivially extensible beyond three values to any number</p>
</li>
<li>
<p>The storage requirement is small (one integer) and constant,
independent of the number of values.</p>
</li>
</ol>
</div>
<p>The first of these is probably the most important. Finding the
largest of 3 values with the original approach required 3 ifs.
Finding the largest of 4 requires a re-writing of the logic of the
program. With the re-design, finding the maximum of 4, or 4000, is
a trivial change.</p>
<p>A coding with this design follows. We change how many numbers to
deal with by changing <tt class="constant">howmany</tt>, which
could be done at run-time:</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;

int main() {
  int num;
  const int howmany = 3;
  double average;
  int product, smallest, largest, sum;
  int index;
  printf(&quot;Enter first number: &quot;);
  scanf(&quot;%d&quot;,&amp;num);
  smallest = largest = sum = product = num;
  for(index = 1; index &lt; howmany; index++) {
    printf(&quot;Enter next number: &quot;);
    scanf(&quot;%d&quot;,&amp;num);
    if(num&gt;largest)
      largest = num;
    if(num&lt;smallest)
      smallest = num;
    sum += num;
    product *= num;
  }
  average = sum/(double)howmany;
  printf(&quot;\nSum is %d&quot;,sum);
  printf(&quot;\nAverage is %lf&quot;, average);
  printf(&quot;\nProduct is %d&quot;, product);
  printf(&quot;\nSmallest is %d&quot;, smallest);
  printf(&quot;\nLargest is %d\n&quot;,largest);
  return 0;
}
</pre></div>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e440" id="d0e440"></a>The Winner of
SCC 21</h3>
</div>
<p>The editor's choice is: Catriona O'Connell. 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>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e448" id="d0e448"></a>Student Code
Critique 22</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 July 6th)</p>
<p>When critiquing this code please do not restrict yourself to
explaining the writer's perceived problem but deal with all aspects
of the code. There are some nasty problems as well as issues of
good coding practice.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e458" id="d0e458"></a>The Code</h3>
</div>
<div class="blockquote">
<blockquote class="blockquote">
<p>Please look at the following code that is just playing with
container of objects.</p>
<pre class="programlisting">
#include&lt;iostream&gt;
#include&lt;fstream&gt;
#include&lt;vector&gt;
using namespace std;

class A {
public:
  A(int p1= 0) : x(p1) {
    cout&lt;&lt;&quot;CTOR&quot;&lt;&lt;endl;
  }
  A(const A&amp; a) {
    x = a.x;
    cout&lt;&lt;&quot;COPY CTOR&quot;&lt;&lt;endl;
  }
  ~A() {
    cout &lt;&lt; &quot;DTOR: address = &quot; &lt;&lt; (long)this &lt;&lt;endl;
  }
  friend ostream&amp;
  operator&lt;&lt;(ostream&amp; out, const A&amp; obj);
private:
  int x;
};

ostream&amp; operator&lt;&lt; (ostream&amp; out, const A&amp; obj) {
  out &lt;&lt; &quot;x = &quot;&lt;&lt;(obj.x)&lt;&lt;endl;
  return out;
}

int main() {
  vector&lt;A&gt; v;
// Be inefficient, not production code
  for(int i=0; i&lt;3; i++)
    v.push_back(A(i));
// Lo behold, container of objects
  copy(v.begin(), v.end(),
       ostream_iterator&lt;A&gt;(cout, &quot;&quot;));
  cout &lt;&lt; endl;
  A * pa = &amp;(v.back());
// pa points to address of reference
// to the last element
  cout &lt;&lt; (*pa);                         // info
  cout &lt;&lt; &quot;pa = &quot;
       &lt;&lt; (long)pa &lt;&lt; endl;              // address
  cout &lt;&lt; &quot;call pop_back()&quot; &lt;&lt;endl;
  v.pop_back();                          // Line A
// destructor WILL destroy last element
// Now pa points to deleted memory, should crash
  cout &lt;&lt; (*pa);                         // Line B
  cout &lt;&lt; &quot;pa = &quot; &lt;&lt; (long)pa &lt;&lt; endl;   // address
  delete pa;                             // Line C
  return 0;
}
</pre></blockquote>
</div>
<p>Lines A and C delete the same memory, which shouldn't be
allowed. But program runs fine allowing dereferencing at line B.
Why?</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
