    <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 11</title>
        <link>https://members.accu.org/index.php/journals/1131</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


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

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

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

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

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

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c119/">134</a>
                    (6)
<br />

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

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

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

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

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




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Student Code Critique Competition 11</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 06 August 2001 13:15:47 +01:00 or Mon, 06 August 2001 13:15:47 +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><span class="bold"><b>Prizes provided by Blackwells
Bookshops</b></span></p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e23" id="d0e23"></a>Student Code
Competition 10 - C Vu Volume 13 No.3</h2>
</div>
<p class="c2"><span class="remark">Once again there was only a
single entry. It is becoming increasingly difficult to deliver
issues of C Vu with any sort of balanced content. When I suggest
that ACCU should carefully consider whether it should continue with
printed publication, I am greeted with howls of protest from those
who have a hundred reasons why they think we should go on. However,
when it comes down to it, if members do not contribute there will
not be any issues. Editors take a pride in their work, and any
editor worth his/her salt is not going to be happy with producing a
gutless C Vu (i.e. just reports and reviews).</span></p>
<p class="c2"><span class="remark">On to what this column is
supposed to be about.</span></p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e32" id="d0e32"></a>The Problem:</h3>
</div>
<p>OK let us try something slightly different this time. Go back to
my interpretation of the student's task (a class to manage the
subjects taken and marks attained by a single student) and write a
model answer. All types you need should be properly implemented
(note that subjects and marks are types) in an appropriate fashion.
Now explain clearly your reasons for the different design decisions
you made.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e37" id="d0e37"></a>Response to
Critique 10</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e40" id="d0e40"></a>Tim Pushman
<tt class="email">&lt;<a href=
"mailto:jalal@gnomedia.com">jalal@gnomedia.com</a>&gt;</tt></h3>
</div>
<p>Well, confusion indeed! The original contributor obviously had
his idea of what the specification was, the teacher had another
idea, and then FG had yet another idea! I've chosen to continue
with the original contributors idea of having a class that
encapsulated a 'set of students scores', so arguably a better name
for it would be <tt class="classname">StudentRecord</tt> or
<tt class="classname">StudentScores</tt>. However, I've continued
to call the class <tt class="classname">Student</tt>, in order to
maintain some continuity with what has gone before.</p>
<p>First, let me restate the problem specification (Francis's
version): &quot;Implement a class to record an individual student's
marks. The student may be taking up to 10 subjects. Subjects are
identified by a subject number. Write a short program to test the
class.&quot; Note that there is no indication of what context the
resulting class will be used in, something I will look at later on
as it will affect our implementation.</p>
<p>I will write some code based on the approach taken by the
original student (including old-style C++), then at the end I will
show how the specification can be implemented using the latest
style of C++ coding.</p>
<p>Let me start off with the test bed, often a good starting point,
because this clarifies what we require the class to do.</p>
<pre class="programlisting">
#include &quot;student.h&quot;
int main() {
  Student s1;
  Student s2(1, 32);
  s1.add(2, 22);
  s2.add(0, 0);
  s2.add(1, 56);
  s2.add(2, 22);
  s1.output();
  s2.output();
}
</pre>
<p>Here we create 2 students, one using the default constructor,
the second using the parameter constructor. Then we add some values
and then ask the objects to print themselves out. I have simplified
a bit here, as there would be some further tests that could be
run.</p>
<p>Here is a possible implementation of the <tt class=
"classname">Student</tt> class:</p>
<p>In file <tt class="filename">student.h</tt></p>
<pre class="programlisting">
#include &lt;iostream.h&gt;
const int MAX_ENTRIES = 10;
typedef int subjcode_t;
typedef int score_t;
class Cstudent {
public:
  CStudent():m_numGrades(0){}
  CStudent( subjcode_t g, score_t s );
  int add( subjcode_t g, score_t s );
  void output( ostream&amp; os );
private:
  subjcode_t m_subj[MAX_ENTRIES];
  score_t m_score[MAX_ENTRIES];
  int m_numGrades;
};
</pre>
<p>In file <tt class="filename">student.cpp</tt></p>
<pre class="programlisting">
#include &quot;student.h&quot;
CStudent::CStudent(subjcode_t g, score_t s):m_numGrades(0) {
  add(g, s);
}
int CStudent::add(subjcode_t g, score_t s){
  if( m_numGrades &gt; MAX_ENTRIES ) {
    return MAX_ENTRIES;
  }
  m_subj[m_numGrades] = g;
  m_score[m_numGrades] = s;
  return m_numGrades++;
}
void CStudent::output(std::ostream&amp; os){
  os&lt;&lt; &quot;Student: number entries: = &quot; &lt;&lt; m_numGrades &lt;&lt; std::endl;
  for( int i = 0; i &lt; m_numGrades; i++ ) {
    os &lt;&lt; &quot;Grade: &quot; &lt;&lt; m_subj[i] &lt;&lt; &quot; Score: &quot; &lt;&lt; m_score[i] &lt;&lt; std::endl;
  }
}
</pre>
<p>So, a few comments on the above.</p>
<p>I've used a <tt class="literal">typedef</tt> for the subject
code and for the <tt class="varname">grade</tt>. This is not really
necessary, but could be useful in the future if we needed to change
the type of either (to an <tt class="type">unsigned int</tt>, for
example).</p>
<p>[<i><span class="remark">OK, now if I were marking this as
student work I would mark you down because the question as set
specifically required that these would be types. I would expect, at
a minimum:</span></i></p>
<pre class="programlisting c3">
<span class="remark">struct subject {
  int code;
};</span>
</pre>
<p><i><span class="remark">FG</span></i>]</p>
<p>The <tt class="methodname">add(..)</tt> method returns an
<tt class="type">int</tt>. We have the choice of returning a
<tt class="type">void</tt>, a <tt class="type">bool</tt> or an
<tt class="type">int</tt>. Using a <tt class="type">void</tt>
return would be a waste of a return value, we could return a
<tt class="type">bool</tt> to indicate if the values were inserted
correctly. But returning the index of the inserted value gives the
caller an indication of how many grades have been inserted so far.
I have also simply ignored any insertions past the maximum number.
This may not be the best response to an out of bounds insertion,
see later for more on this.</p>
<p>The <tt class="methodname">output(...)</tt> method takes an
<tt class="classname">ostream</tt> parameter, this allows us to use
the same method and redirect the output wherever we want, to a file
or into a <tt class="classname">strstream</tt>. (<i><span class=
"remark">or even a standard stringstream FG</span></i>)</p>
<p>Using two arrays (<tt class="varname">m_subj</tt> and <tt class=
"varname">m_score</tt>) is probably unnecessary. It is quite likely
that given there is a fixed number of entries (10 in this case)
that there is fixed number of courses, and that we would only need
to keep track of the score for each course. In which case we only
need one array and use the index into the array as the subject
code. But I have stayed with using two arrays for this example.
Possibly the subject codes are not contiguous. (<i><span class=
"remark">even more likely that students are allowed to take up to
ten courses out of dozens or even hundreds FG</span></i>)</p>
<p>I have kept the test bed program simple for the purposes of this
article, but in a real test bed it would be important to test all
the 'boundary conditions' that a class could be expected to deal
with. One important condition here would be, what happens when we
add an eleventh grade to the student? We have an array of ten
elements, adding the eleventh takes us into that region of darkness
and despair known as &quot;undefined behaviour&quot;... I mentioned at the
start of the article that the class specification gives us no clue
as to what context it would be used in, and this is an important
factor in deciding how to handle boundary conditions such as adding
too many elements.</p>
<p>In this case, I can see five possible ways of handling the
situation:</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>Crash. Inelegant but simple.</p>
</li>
<li>
<p>Throw an exception.</p>
</li>
<li>
<p>Refuse to add an extra element.</p>
</li>
<li>
<p>Expand the array.</p>
</li>
<li>
<p>Remove the oldest entry and add the new one.</p>
</li>
</ol>
</div>
<p>Lets ignore the first... If this class were to be used in the
context of a library, or as part of a larger, more complex project,
then (2) may be the best choice. The last three depend on knowledge
of the problem domain and would make an excellent exercise for the
reader.</p>
<p>Other things to be dealt with are things like, can we accept a
negative score, does the course code need to be within a particular
range, how we deal with situations where these constraints are not
met?</p>
<div class="sect3" lang="en">
<div class="titlepage">
<h3><a name="d0e180" id="d0e180"></a>Standard
C++</h4>
</div>
<p>So far we've looked at using old style C++ coding, but there are
more elegant ways of implementing the class.</p>
<p>The Student class is basically a container of subject codes and
scores, so the simplest implementation of <tt class=
"classname">Student</tt> would be:</p>
<pre class="programlisting">
typedef std::vector&lt;std::pair&lt;subjcode_t, grade_t&gt; &gt; Student;
</pre>
<p>which could be used as:</p>
<pre class="programlisting">
Student s1;
s1.push_back( std::make_pair( 2, 12 ) );
</pre>
<p>Simple and efficient and no class needed, but it allows us no
control of the input, checking for valid subject codes and so on,
so an improvement would be to wrap the above into a <tt class=
"classname">Student</tt> class, using the same interface as for our
original design of student. That gives us:</p>
<p>File: <tt class="filename">newstudent.h</tt></p>
<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;utility&gt;
const int MAX_ENTRIES = 10;
typedef int subjcode_t;
typedef int score_t;
typedef std::vector&lt;std::pair&lt; subjcode_t, score_t&gt; &gt; subjectlist;
typedef std::vector&lt;std::pair&lt; subjcode_t, score_t&gt; &gt;::iterator subjectiter;
class Cstudent {
public:
  CStudent(){}
  CStudent( subjcode_t g, score_t s );
  int add( subjcode_t g, score_t s );
  void output( std::ostream&amp; os );
private:
  subjectlist subjects;
};
</pre>
<p>And file: <tt class="filename">newstudent.cpp</tt></p>
<pre class="programlisting">
#include &quot;newstudent.h&quot;
CStudent::CStudent(subjcode_t g, score_t s){
  add(g, s);
}
int CStudent::add( subjcode_t g, score_t s ){
  if( subjects.size() &gt;= MAX_ENTRIES ) {
    return MAX_ENTRIES;
  }
  subjects.push_back(std:: make_pair( g, s ));
  return subjects.size();
}
void CStudent::output( std::ostream&amp; os ){
  os &lt;&lt; &quot;Student: number entries: = &quot; 
    &lt;&lt; subjects.size() &lt;&lt; std::endl;
  subjectiter iter = subjects.begin();
  for( ; iter != subjects.end(); iter++ ) {
    os&lt;&lt;&quot;Grade: &quot; &lt;&lt;(*iter).first 
      &lt;&lt;&quot; Score: &quot; &lt;&lt; (*iter).second 
      &lt;&lt; std::endl;
  }
}
</pre>
<p>The first important thing to note is that our interface to the
outside world (in the .h file) has remained virtually unchanged,
which means that users of our original <tt class=
"classname">CStudent</tt> class can just plug in the new one
without changing any of their code. Indeed, the test bed program
runs just the same.</p>
<p>Secondly, we are now including the new C++ headers (<tt class=
"filename">&lt;vector&gt;</tt>, <tt class=
"filename">&lt;iostream&gt;</tt> etc) and therefore we need to use
the <tt class="literal">std::</tt> namespace when accessing the
containers and streams within them.</p>
<p>I have chosen <tt class="classname">vector</tt> in the above
code, but alternatives would be:</p>
<pre class="programlisting">
std::map&lt; subjcode_t, grade_t&gt;
</pre>
<p>or simply</p>
<pre class="programlisting">
std::vector&lt;grade_t&gt;
</pre>
<p>and use the index into the vector as the <tt class=
"varname">subjcode</tt>, as discussed in the first section of
code.</p>
<p>If the subject code must appear more than once, then the
<tt class="classname">map</tt> won't work (the key must be unique)
and therefore we would need a <tt class=
"classname">multi-map</tt>.</p>
<p>As I mentioned at the start, the context within which a class
will be used is an important factor in deciding how to implement it
and in how to handle boundary conditions. The design above is
flexible enough that in a real world situation, the implementation
could be changed without any disastrous effects on any users of the
class.</p>
<p class="c2"><span class="remark">Well you see how easy it is to
win a book. If Tim contacts me we can discuss which Addison-Wesley
book he wants.</span></p>
<p class="c2"><span class="remark">Of course contestants have to
submit themselves to the editors comments, but the idea of this
section of C Vu is a kind of Seminar. I would hope that many
readers will want to add their bit as well. It would be nice to see
some of you offer classes to handle subjects (including titles) and
marks (including grades). It isn't that hard, a few good clean
examples might help to raise standards. FG</span></p>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e261" id="d0e261"></a>Student Code
Critique Competition 11</h2>
</div>
<p>The following code is intended to use Newton's method of
approximations to find the roots of a function. It is a mess. The
direct question is that the program only works for some input
values. The code is C.</p>
<p>Reverse engineer the code, explaining what each function
actually evaluates. Then rewrite the code (in C). Extra credit for
dealing with the magic numbers, and expert credit for generalising
the program so it handles finding roots of a wider range
functions.</p>
<p>Given sufficient entries, there will be more than one prize.
Remember that the objective is to help a student improve his/her
understanding of programming and the process of writing simple
code.</p>
<pre class="programlisting">
#include &lt;stdio.h&gt;
#include &lt;math.h&gt;
double func(double x) {
  double val1, val2, val3, val4, vsqrt;
  vsqrt = sqrt(fabs(x));
  val1 = 25.0/7.0; val2 = log(3750.0 * vsqrt);
  val3 = 1.0/vsqrt;   val4 = 6.0;
  return (val1*val2 - val3 - val4);
}
double derivative(double x){
  double val1, val2, val3;
  val1 = 1.0/(2.0 * X); val2 = 25.0 / 7.0;
  val3 = 1.0/sqrt(fabs(X));
  return val1 * (val2 + val3);
}
double NewtonRough(double x0){
return(x0-( func(x0)/derivative(x0)));
} 
int main(){
  double x0, x1;
  puts(&quot;Enter an estimate of the root\n&gt;&quot;);
  scanf(&quot;%f&quot;, &amp;x0);
  printf(&quot;x0 = %f\n&quot;, x0);
  for(;;){ x1 = NewtonRough(x0);
    if(fabs(x1 - x0)&lt; pow(10.0, -6.0) break;
    x0 = x1;
  }
  printf(&quot;Estimation of root %f\n&quot;, X1);
  return 0;
}
</pre>
<p>Closing date: September 20th</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
