    <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/1112</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 13, #2 - Apr 2001</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/c121/">132</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c183+121/">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 April 2001 13:15:45 +01:00 or Fri, 06 April 2001 13:15:45 +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="d0e18" id="d0e18"></a></h2>
</div>
<p>Prizes for this competition are provided by Blackwells Bookshops
in co-operation with Addison Wesley.</p>
<p>Note that the code being critiqued is on our website (if it
isn't let me know) As I am struggling to get this issue to print, I
am only publishing the winning entry. There were several other
excellent submissions, in particular, one from Colin Gloster and an
interesting one from Jon Krom. I really regret not being able to
include that one because Jon is a great advocate for functional
programming - how about doing a series on functional programming,
Jon.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e24" id="d0e24"></a>Student Code
Critique Competition No. 8</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e27" id="d0e27"></a>Solution from
Raymond Butler</h3>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e30" id="d0e30"></a>Reported and
Observed Behaviour</h4>
</div>
<p>It was reported that the program did not collect the second
number after the operator symbol had been entered. My own
observation was that it</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>prompted for and collected the first number,</p>
</li>
<li>
<p>prompted for, but did not collect, the operation symbol,</p>
</li>
<li>
<p>prompted for and collected the second number.</p>
</li>
</ul>
</div>
<p>I suggest that the original user was probably typing the
operation symbol in response to the &quot;second number&quot; prompt, not
having noticed that the &quot;operation&quot; input had been skipped. In that
case the observed behaviour would have seemed to be as
reported.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e47" id="d0e47"></a>Why it doesn't
work</h4>
</div>
<p>The first call to <tt class="function">printf</tt> prompts the
user to enter the first number. The user types in the number and
presses the &quot;Enter&quot; key, thereby placing a string of characters
into the input stream such as:</p>
<pre class="screen">
1 2 . 3 4 5 \n
</pre>
<p>The <tt class="function">scanf</tt> function reads the input
stream. The format specifier &quot;%e&quot; tells <tt class=
"function">scanf</tt> that it is looking for a floating-point
number, but does not specify the number of characters to be read.
<tt class="function">scanf</tt> therefore keeps reading characters
as long as they are plausibly part of a floating-point number. The
resulting value is assigned to <tt class="varname">num1</tt>. The
new-line character, <tt class="literal">\n</tt>, corresponding to
the <span><b class="keycap">Enter</b></span>-key, cannot be part of
a floating-point number and so is not consumed by <tt class=
"function">scanf</tt>. It is not discarded either; it stays in the
input stream waiting to be read. The next call to printf prompts
the user for the operation symbol. scanf again reads the input
stream. This time the format specifier is &quot;<tt class=
"literal">%c</tt>&quot;, which differs from other format specifiers in
these respects:-</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>White-space characters (including <tt class="literal">\n</tt>)
are not skipped over, but can be read and assigned to the variable
like any other sort of character;</p>
</li>
<li>
<p>There is a default field width of one.</p>
</li>
</ul>
</div>
<p>Now, there is already a <tt class="literal">\n</tt> character in
the input stream, left over from the input of <tt class=
"varname">num1</tt>. <tt class="function">scanf</tt> reads this
straight away and assigns it to operation. The user doesn't get a
chance to type in the actual operation symbol before...</p>
<p>The next call to <tt class="function">printf</tt> prompts the
user for the second number, <tt class="varname">num2</tt>. By now
the input stream is empty, so <tt class="function">scanf</tt> has
to wait for the user to type in a new string of characters, which
are read in and assigned to <tt class="varname">num2</tt> in the
same way as for <tt class="varname">num1</tt>.</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e121" id="d0e121"></a>How it can be
made to work</h4>
</div>
<p>The program can be made to work almost as expected by inserting
a call to <tt class="function">getchar</tt> immediately after the
first <tt class="function">scanf</tt>.</p>
<pre class="programlisting">
scanf(&quot;%le&quot;, &amp;num1);  getchar();
</pre>
<p>This <tt class="function">getchar</tt> &quot;swallows&quot; the <tt class=
"literal">\n</tt> at the end of the input stream, ensuring that the
second <tt class="function">scanf</tt> has to wait for the user to
type in an operation symbol. It does not matter that this character
will also be followed by <tt class="literal">\n</tt>, because the
third <tt class="function">scanf</tt>, under the control of format
specifier &quot;<tt class="literal">%e</tt>&quot;, will skip over any leading
whitespace characters, including <tt class="literal">\n</tt>.
Incidentally, my compiler (Borland Turbo C++ version 3.1 for
Windows) required the format specifier &quot;%le&quot; (that's a lowercase
'L') in order to assign correctly to a variable of type
<span class="type">double</span>.</p>
<p>Another correction needs to be made before the program will work
properly. As they stand, the two <tt class=
"literal">if</tt>-statements are rendered ineffective by the
semi-colon immediately following the test:</p>
<pre class="programlisting">
if (num2 == 0);
</pre>
<p>This causes the value of <tt class="varname">num2</tt> to be
compared with zero, but nothing in particular is done on the basis
of the result. The program continues with the next statement
regardless. Consequently, if the division operation is selected,
the program both prints the error message and attempts the
calculation, whether <tt class="varname">num2</tt> is zero or not.
This is easily rectified:</p>
<pre class="programlisting">
if (num2 == 0)
   printf(&quot;ERROR: DIVIDE BY ZERO!!\n&quot;);
else {
   total = num1/num2;
   printf(&quot;%e\n&quot;, total);
}
</pre></div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e177" id="d0e177"></a>Comments on the
style</h4>
</div>
<p>The program is written in a style which is only suitable for
very short, simple programs. After the input section, the
switch-statement sends the thread of execution down one of four
possible paths. These branches are quite short, between four and
eight statements long, so the overall structure of this program is
still quite easy to see. But suppose there were more branches, and
each was forty or more lines in length. It would be much more
difficult to see what was going on then.</p>
<p>As a result of adopting such a style, there has been some
unnecessary repetition. For example, each branch has at least one
printf statement for printing out the answer, but they are all
identical. The two <tt class="function">printf</tt> statements for
printing the error messages are also similar to one another. If it
became necessary to change the format of the output; all these
statements would have to be changed. They are all quite close
together here, so its not an onerous task. But again suppose that
the <tt class="literal">switch</tt> had more branches and they were
much longer; you could spend hours tracking down all the
occurrences of <tt class="function">printf</tt> and deciding which
ones had to be changed, (and you would still to miss one).</p>
</div>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e193" id="d0e193"></a>My solution</h4>
</div>
<p>First, I broke the problem down into a series of simpler steps,
each of which can be expressed as a function:-</p>
<pre class="programlisting">
input(&amp;num1, &amp;op, &amp;num2);
answer = evaluate(num1, op, num2);
output(answer);
</pre>
<p>I then considered the types of each of the variables involved.
It would be sensible for <tt class="varname">num1</tt> and
<tt class="varname">num2</tt> to be floating point numbers, i.e. of
type <span class="type">float</span> or <span class=
"type">double</span>, and for the operator <tt class=
"varname">op</tt> to be a <span class="type">char</span>. What
about the answer? If all went well it too would be a floating-point
number. But it could also be an error message, that is, a string of
characters. I therefore decided to define a data structure,
<span class="structname">Answer</span>, which could accommodate
both a <span class="type">double</span> value and a pointer to a
<span class="type">char</span>, but which could still be passed
around as a single object. Consequently, the &quot;top level&quot; of my
program looks like this:-</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
struct Answer {
   double num;
   char   *err;
};
int input(double *ptr_num1, char *ptr_op,
        double *ptr_num2);
struct Answer evaluate(double num1, char op,
                 double num2);
struct Answer divide(double num1,double num2);
void output(struct Answer answer);
int main(){
  double    num1, num2;
  char      op;
  struct Answer answer;
  input(&amp;num1, &amp;op, &amp;num2);
  answer = evaluate(num1, op, num2);
  output(answer);
  return 0;
}
</pre>
<p>In my <tt class="function">input</tt> function, rather than
making the user type in the two numbers and the operator on
separate lines, I have gone for a single <tt class=
"function">scanf</tt> statement, which allows a more natural
expression like &quot;<tt class="literal">2.78 + 4.65</tt>&quot; to be typed
in. I have used &quot;<tt class="literal">%1s</tt>&quot; (a one-character
string) instead of &quot;<tt class="literal">%c</tt>&quot; (a single
character) in the format specifier for the <tt class=
"varname">op</tt> variable. The difference may seem subtle, but the
advantage of &quot;<tt class="literal">%1s</tt>&quot; is that any spaces
preceding it will be ignored, and the first non-space character
will be assigned to <tt class="varname">op</tt>. This gives the
user the option of including spaces.</p>
<p>Note that the parameters to the input function, like those of
<tt class="function">scanf</tt>, are pointers, i.e. variables
containing the addresses of other objects. This allows the values
of the variables in the <tt class="function">main</tt> function, to
which they point, to be changed. Because these objects are
pointers, they do not need to be preceded by '<tt class=
"literal">&amp;</tt>' in the call to <tt class=
"function">scanf</tt>.</p>
<pre class="programlisting">
int input(double *ptr_num1, char *ptr_op,
      double *ptr_num2){
  printf(&quot;&gt; &quot;);
  scanf(&quot;%le %1s %le&quot;, ptr_num1, ptr_op,
           ptr_num2);
  return 0;
}
</pre>
<p>The <tt class="function">evaluate</tt> function starts off by
defining its own local <span class="structname">Answer</span>
structure. The numeric component, <i class=
"structfield"><tt>answer.num</tt></i>, is initialised to 0 and the
pointer component, <i class="structfield"><tt>answer.err</tt></i>,
is initialised to NULL (pointing at nothing). I have then used a
<tt class="literal">switch</tt> statement to handle the various
possible values of <tt class="varname">op</tt>. The add, subtract
and multiply cases assign new values to the <i class=
"structfield"><tt>num</tt></i> component of <span class=
"structname">answer</span>, leaving the <i class=
"structfield"><tt>err</tt></i> component as NULL. The default case
makes the <i class="structfield"><tt>err</tt></i> component point
to the start of a suitable error message, leaving the <i class=
"structfield"><tt>num</tt></i> component as zero. Because the
divide operation is non-trivial, I have hived it off to a function
of its own, which returns a complete <span class=
"structname">Answer</span> structure. Finally, the resulting answer
is passed back to the <tt class="function">main</tt> function.</p>
<pre class="programlisting">
struct Answer evaluate(double num1, char op,
                       double num2) {
  struct Answer answer = {0, NULL};
  switch(op) {
    case '+':
      answer.num = num1 + num2;
      break;
    case '-':
      answer.num = num1 - num2;
      break;
    case '*':
      answer.num = num1 * num2;
      break;
    case '/':
      answer = divide(num1, num2);
      break;
    default:
      answer.err = &quot;Unknown operator&quot;;
      break;
  }
  return answer;
}
</pre>
<p>The <tt class="function">divide</tt> function also defines its
own local <span class="structname">Answer</span> structure, its
components initialised to 0 and NULL. If <tt class=
"varname">num2</tt> is not zero, the result of the division
operation is assigned to the numeric component. Otherwise, the
pointer component is made to point to the start of a suitable error
message. The resulting answer is returned to the calling
function.</p>
<pre class="programlisting">
struct Answer divide(double num1, double num2) {
  struct Answer answer = {0, NULL};
  if (num2 != 0.0) answer.num = num1 / num2;
  else  answer.err = &quot;Division by zero&quot;;
  return answer;
}
</pre>
<p>The output function takes an <span class=
"structname">Answer</span> structure as its parameter. If the
<i class="structfield"><tt>err</tt></i> component is NULL, then the
computation must have succeeded without any errors, so the
<i class="structfield"><tt>num</tt></i> component is output.
Otherwise, the character string pointed to by <i class=
"structfield"><tt>err</tt></i> is output.</p>
<pre class="programlisting">
void output(struct Answer answer) {
  if (answer.err == NULL) printf(&quot;= %le\n&quot;, answer.num);
  else printf(&quot;ERROR: %s\n&quot;, answer.err);
  return;
}
</pre></div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e345" id="d0e345"></a>Student Code
Critique Competition 9</h2>
</div>
<p><span class="emphasis"><em>Set by Francis
Glassborow</em></span></p>
<p><span class="emphasis"><em>Something short and confused this
time, and in C++. By the way I am quite happy to ask for critiques
for code written in other widely used languages if any readers
would like to submit them. Indeed, I think we could stretch to a
prize for submitting code that gets published for critiquing (and
yes, you can submit your own code if you are a student
member)</em></span></p>
<p><span class="emphasis"><em>Your first problem with the following
piece of code is to write what you think was the spec to which the
student was responding. The second is to note that I have not
messed around with the layout (except to add comment marks where
comments have wrapped round), so that you can comment on it. Once
again extra credit will be given for innovative
presentations.</em></span></p>
<pre class="programlisting">
class Student //specify an object
   {
   private:
       int subjcode[10];//subject codes array
       int mark[10];//marks for each subject //code array
       int num_marks;//number of subjects //taken
   public:
       Student(){}//default constructor,no //args,does nothing
       Student(int grd, int cd) //constructor(two args)
     {  subjcode= cd;
               mark = grd;
     }
       void showstudent()//display data
       {
     cout&lt;&lt;&quot;\nYour Subject Code is:&quot; &lt;&lt;subjcode&quot;;
     cout&lt;&lt;&quot;\nYour mark is:&quot;&lt;&lt;mark;
       }
     };
 void main()
 {
   int count=2;//count controls for loop
   class Student[count];//array for 2 students
       for (int n=0; n&lt;2; n++)
         {
         student[n].showstudent();//prints //array
         }
   Student[0]();//no marks so use default //constructor(no arguments)
   //First element of array is subject code, //2nd element is grade
   Student[1](0,87);
   Student[0](0,78);
   Student[0](1,83);
   Student[1](2,66);
   Student[1](3,92);
}
</pre></div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
