    <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  :: Challenge 4 Report &amp; Outlining Challenge 5</title>
        <link>https://members.accu.org/index.php/articles/2551</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">Programming Topics + CVu Journal Vol 30, #4 - September 2018</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/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</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/c390/">304</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+390/">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;Challenge 4 Report &amp; Outlining Challenge 5</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 02 September 2018 18:16:03 +01:00 or Sun, 02 September 2018 18:16:03 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Francis Glassborow presents the responses to the challenge from last time and outlines the next one.</p>
<p><strong>Body:</strong>&nbsp;<p>The challenge from the last <em>C Vu</em> was to write a program that outputs the numbers from 1 to 100 without using <code>if</code>, <code>for</code>, <code>switch</code>, or <code>while</code>. I forgot to exclude the ternary operator. However, considerable ingenuity was exhibited by all. To save space and repetition, I have omitted solutions using the ternary operator unless they have some other ingenuity.</p>

<p>Before I get on with the submissions, here is an idea for a C++ solution which has not been used in any of the (often very ingenious) solutions.</p>

<p>Use a class constructor:</p>

<pre class="programlisting">
  struct challenge4 {
   static int counter =0;
   static int incr;
   challenge4(){
     cout &lt;&lt; counter &lt;&lt; \n;
     counter += incr;
  };</pre>
  
<p>Now you can set the counter to the start value and create a vector of <code>(end-start -1)</code> to output the numbers from start to end. The value passed to <code>incr</code> can be calculated with:</p>

<pre class="programlisting">
  Challenge4::incr =(end-start)/abs(end-start);</pre>
  
<p>Or using <code>signbit()</code>:</p>

<pre class="programlisting">
  int direction[] = {-1, 1}
  challenge4::incr = direction[signbit(start-end)]</pre>
  
<p>Now executing something like</p>

<pre class="programlisting">
  vector&lt;Challenge4&gt; c4(abs(end-start -1);</pre>
  
<p>I leave it as an exercise for the reader to take those ideas into a working program. You will need to ensure you understand how exactly how C++ initialises containers to get this right as I have deliberately written buggy code snippets. For some of you, the faults will stand out immediately; but some of you may not be quite so familiar with the finer details and have to think or even look up details in your reference sources.</p>

<p>Now to the readers efforts.</p>

<h2>From Silas S. Brown</h2>

<p class="EditorIntro">Francis: Sometimes the path from a first cut to the final solution is instructive.</p>

<p>I was sorry to read about the lack of response to Challenge 3.</p>

<p>I knew those things were called â€˜quinesâ€™ and thought plenty of members would look up how to make them, but itâ€™s easy to forget that not everyone knows such things.</p>

<p>For challenge 4 (outputting numbers <code>first</code> to <code>last</code> without using <code>if</code>, <code>for</code>, <code>switch</code> or <code>while</code>), a very dirty way in C is simply to use <code>goto</code> and the <code>?:</code> operator:</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  enum { first=1, last=100 };
  int main() {
    int c = first;
  loop:
    printf(&quot;%d\n&quot;, c);
    (c==last) ? exit(0) : 0;
    c += (last &gt;= first) ? 1 : -1;
    goto loop;
  }</pre>
  
<p>The fact that <code>exit()</code>, a function with side effects, can be included in a <code>?:</code> expression means we can terminate without an <code>if</code>. Of course, this wonâ€™t do if we additionally say that the function is to be included in a larger program and should therefore return to its caller rather than calling <code>exit()</code>. But thereâ€™s another standard function (thankfully little used) which can transfer control back to the caller: <code>longjmp</code>. Hereâ€™s the <code>longjmp</code> version (and for variety letâ€™s do it via recursion rather than a <code>goto</code>) :</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;setjmp.h&gt;
  enum { first=1, last=100 };
  int loop(int c, jmp_buf e) {
    printf(&quot;%d\n&quot;, c);
    (c==last) ? longjmp(e,1) : 0;
    loop (c + ((last &gt;= first) ? 1 : -1), e);
  }
  int main() {
    jmp_buf e;
    setjmp(e) ? 0 : loop(first, e);
  }</pre>
  
<p>What if we additionally ban the <code>?:</code> operator? In that case we can rewrite our loop function like this:</p>

<pre class="programlisting">
  int finished(jmp_buf e) {
    longjmp(e,1);
  }
  int loop(int c, jmp_buf e) {
    printf(&quot;%d\n&quot;, c);
    c==last &amp;&amp; finished(e);
    loop (c + (last &gt;= first) - (last &lt; first), e);
  }</pre>
  
<p>Itâ€™s necessary to put the <code>longjmp</code> in a different function because it returns <code>void</code>, so the compiler wonâ€™t allow us just to say <code>c==last &amp;&amp; longjmp(e,1);</code> and the same goes for <code>exit()</code>.</p>

<p>And if we also ban the use of <code>longjmp</code>, we can instead write it like this:</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  enum { first=1, last=100 };
  int loop(int c) {
    printf(&quot;%d\n&quot;, c);
    c != last &amp;&amp; loop (c + (last &gt; c) - 
      (last &lt; c));
  }
  int main() { loop(first); }</pre>
  
<p>which, come to think of it, is probably what I should have written to begin with.</p>

<p class="EditorIntro">Francis: But the scenic tour is illuminating.</p>

<h2>From James Holland</h2>

<p class="EditorIntro">Francis: This one explores various C++ solutions showing considerable ingenuity but misses the â€˜ahaâ€™ of populating a container using a type with suitable constructors.</p>

<p>Francisâ€™s challenge deprives us of most flow control constructs. There are, however, one or two left that could still be used. As Francis implies, the challenge is probably easier to solve using C++ rather than C. My first attempt employs the conditional expression (<code>?:</code>) and recursion as shown below.</p>

<pre class="programlisting">
  #include &lt;iostream&gt;
  void increment(int amount, int value, int last)
  {
    std::cout &lt;&lt; value &lt;&lt; ' ';
    value - last ? increment(amount, 
      value + amount, last) : static_cast&lt;void&gt;(0);
  }

  int main(int argc, const char * argv[])
  {
    const int first = std::stoi(argv[1]);
    const int last = std::stoi(argv[2]);
    increment(first &gt; last ? -1 : 1, first, last);
    std::cout &lt;&lt; '\n';
  }</pre>
  
<p>This solution prints the number in the correct order (beginning with <code>first</code>) and copes with negative values of <code>first</code> and <code>last</code>. It would be better, however, not to use a conditional expression if possible. Another feature of C++ that controls program flow is exceptions. If exceptions are to be used, something needs to be found that generates an exception when supplied with a value that signifies the task of printing the numbers is complete. It would be helpful if such an object was part of the standard library. There are probably several such objects. The one I have chosen is <code>std::bitset</code> as it has a member function that throws an exception when the value of its parameter is not an index of one of its bits. I have used this feature in the code below.</p>

<pre class="programlisting">
  #include &lt;bitset&gt;
  #include &lt;iostream&gt;
  void increment(int amount, int value, int last)
  {
    std::cout &lt;&lt; value &lt;&lt; ' ';
    std::bitset&lt;1&gt; bs;
    try
    {
      bs.reset(value - last);
    }
    catch (...)
    {
      increment(amount, value + amount, last);
    }
  }

  int main(int argc, const char * argv[])
  {
    const int first = std::stoi(argv[1]);
    const int last = std::stoi(argv[2]);
    const int amount = 1 - 2 * (first &gt; last);
    increment(amount, first, last);
    std::cout &lt;&lt; '\n';
  }</pre>
  
<p>The <code>std::bitset</code> object <code>bs </code>contains just one bit and, therefore, has an index of zero. While the sequence is being written, <code>value - last</code> will not be a valid index and so <code>bs</code> will throw an exception. The exception is immediately caught causing <code>increment()</code> to be called recursively. Just after the last number is printed, <code>value - last</code> will equal 0. This is a valid index of <code>bs</code>. No exception is thrown and <code>increment()</code> recursively returns to <code>main()</code> where, after a final line-feed, the program terminates.</p>

<p>Also in the above program, instead of using the conditional expression to determine the value (1 or -1) by which the sequence should increment, I have constructed a little formula to do the job. Firstly, <code>(first &gt; last)</code> is implicitly converted to 1 if <code>first</code> is greater than <code>last</code>, 0 otherwise. Multiplying this value by -2 gives -2 and 0 for the two conditions. Finally, adding 1 gives 1 or -1 as required.</p>

<p>The <code>std::bitset</code> technique can also be used to iterate instead of recurse as shown below.</p>

<pre class="programlisting">
  #include &lt;bitset&gt;
  #include &lt;iostream&gt;

  int main(int argc, const char * argv[])
  {
    const int first = std::stoi(argv[1]);
    const int last = std::stoi(argv[2]);
    const int amount = 1 - 2 * (first &gt; last);
    int i = first;
  loop:
    std::cout &lt;&lt; i &lt;&lt; ' ';
    try
    {
      std::bitset&lt;1&gt; bs;
      bs.reset(i == last);
      i += amount;
      goto loop;
    }
    catch (...)
    {
      std::cout &lt;&lt; '\n';
    }
  }</pre>
  
<p>The program uses a <code>goto</code> statement that may be frowned upon. Is there a way of meeting the challenge without using iteration or recursion thus getting rid of explicit flow control altogether? Well, I think there is. The main feature of the program shown below is its use of <code>std::iota()</code>.</p>

<pre class="programlisting">
  #include &lt;algorithm&gt;
  #include &lt;iostream&gt;
  #include &lt;iterator&gt;
  #include &lt;numeric&gt;
  #include &lt;vector&gt;

  int main(int argc, const char * argv[])
  {
    const int first = std::stoi(argv[1]);
    const int last = std::stoi(argv[2]);
    const int length = std::abs(first - last) + 1;
    std::vector&lt;int&gt; numbers(length);
    std::iota(numbers.begin(), numbers.end(), 0);
    const int m = 1 - 2 * (first &gt; last);
    const auto f = [m, first](int x) {
      return m * x + first;};
    const std::ostream_iterator&lt;int&gt;
      output(std::cout, &quot; &quot;);
    std::transform(numbers.cbegin(),
      numbers.cend(), output, f);
    std::cout &lt;&lt; '\n';
  }</pre>
  
<p>An <code>std::vector</code> is created that contains a sequence of values from zero to one less that the number of values to be printed. The coefficients of the formula designed to map the values in the vector to the required output sequence is then calculated. This is based on the equation <em>y</em> = <em>mx</em> + <em>c</em>, where <em>y</em> is the desired printed value and <em>m</em> is the value of the corresponding element in the vector. Within the program, <em>c</em> has the value of <code>last</code>. The function <code>std::transform()</code> is used to successively convert to the required value each element of the vector and then print it.</p>

<p>As can be seen from the above discussion, C++ provides sufficient flexibility to provide various solutions to the challenge. The C language is not quite so accommodating.</p>

<p>Using the conditional operator, a C language solution is not too difficult. A recursive version is shown below.</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  void increment(int amount, int value, int last)
  {
    printf(&quot;%d &quot;, value);
    value != last ? increment(amount, 
      value + amount, last) : (void)0;
  }
  int main(int argc, const char * argv[])
  {
    const int first = atol(argv[1]);
    const int last = atol(argv[2]);
    increment(first &gt; last ? -1 : 1, first, last);
    putchar('\n');
  }</pre>
  
<p>Alternatively, an iterative version can be provided.</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;

  int main(int argc, const char * argv[])
  {
    const int first = atol(argv[1]);
    const int last = atol(argv[2]);
    const int amount = 1 - 2 * (first &gt; last);
    int i = first;
  loop:
    printf(&quot;%d &quot;, i);
    (i == last) ? exit(0) : (void)0;
    i += amount;
    goto loop;
  }</pre>
  
<p>Providing a C language solution that does not use a conditional expression is a little more difficult. The best I can manage is shown below.</p>

<pre class="programlisting">
  #include &lt;assert.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;

  int main(int argc, const char * argv[])
  {
    const int first = atol(argv[1]);
    const int last = atol(argv[2]);
    const int amount = 1 - 2 * (first &gt; last);
    int i = first;
  loop:
    printf(&quot;%d &quot;, i);
    assert(i != last);
    i += amount;
    goto loop;
  }</pre>
  
<p>The program certainly prints the numbers from <code>first</code> to <code>last</code> but other unwanted text is also printed due to the <code>assert</code> statement. I am not familiar with the later C standards and better solutions may be possible.</p>

<h2>From Paul Davies</h2>

<p>I have these entries for Francis. He didnâ€™t give an email so no wonder he didnâ€™t get many responses</p>

<p class="EditorIntro">Francis: Excellent point, please send submissions to francis.glassborow@gmail.com</p>

<p>The following is a c-quine which is â€˜portableâ€™. I based it on a C++ one I wrote in 2006 and just changed the <code>cout</code>s into <code>printf</code>.</p>

<pre class="programlisting">
  #include&lt;stdio.h&gt;
  char p[]=&quot;\&quot;;int main(){
    printf(\&quot;#include&lt;stdio.h&gt;\\nchar p[]=\\\&quot;\&quot;);
    for (char* q=p;*q;++q){
      if(*q=='\\\\'||*q=='\&quot;')printf(\&quot;\\\\\&quot;);
      printf(\&quot;%c\&quot;,*q);}
    printf(\&quot;%s\\n\&quot;,p);
    return 0;}&quot;;
    int main(){
      printf(&quot;#include&lt;stdio.h&gt;\nchar p[]=\&quot;&quot;);
      for (char* q=p;*q;++q){
        if(*q=='\\'||*q=='&quot;')printf(&quot;\\&quot;);
        printf(&quot;%c&quot;,*q);}
      printf(&quot;%s\n&quot;,p);return 0;}</pre>
	  
<p>At least, itâ€™s â€˜portableâ€™ if you save it in the same encoding you will go on to run it in!</p>

<p class="EditorIntro">Francis: Thanks, I think that is as much as we could expect. A quine that could be compiled for one character encoding and then work with a different one seems to me to be a step too far (unless you, the reader, knows better).</p>

<p>The key is to put most of the program in the data string, and then print it twice, once quoted and once not quoted. Francisâ€™s example did this easily; mine uses a <code>for</code> loop to go through and deliberately quote the awkward characters.</p>

<p><span class="filename">accu.cpp</span> generates the numbers <code>first</code> to <code>last</code> without <code>if</code>, <code>for</code>, <code>switch</code> or <code>while</code>. Ok, I cheated: I used the ternary operator.</p>

<p class="EditorIntro">Francis: Not really, but I have omitted it because this column is already about to take over this issue of <em>CVu</em>.</p>

<p>This does it without the ternary operator.</p>

<p>(This code was done in my own time and is not connected with my employer.)</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int f(int, int);
  int g(int, int) { return 0; }
  int (*which[2])(int,int) = { f, g };
  
  int f(int first, int last) {
    printf(&quot;%d\n&quot;,first);
    int next = first - 1 + 2*(last &gt; first);
    return (*(which[first == last]))(next,last);
  }

  int main(int argc, char** argv){
    f(atoi(argv[1]), atoi(argv[2]));
  }</pre>
  
<p class="EditorIntro">Francis: Great idea and results in a really simple program.</p>

<h2>And a Java solution from Pete Disdale</h2>

<p>Please find attached my solution â€“ it is written in Java on the grounds that â€œ<em>anything not expressly forbidden is allowed</em>â€. I could probably write something similar in C using linked lists but that is an exercise for a rainy day and printing the output would be a challenge.</p>

<p>You will need Java 7 or above to compile and run this code, although with some tweaking it should be OK with Java 5 or 6. As you can see, it uses recursion to build up the numbers to print (incrementing or decrementing) controlled by a ternary operator. The <code>System.out</code> in <code>main()</code> and the two <code>ret</code> methods are just fluff in order to use it.</p>

<p>No doubt it could be factored into something simpler but it appears to work as is on all the number ranges I tried.</p>

<pre class="programlisting">
  import java.util.ArrayList;
  import java.util.List;
  
  public class AccuChallenge {

    public static void main(String[] args) {
      try {
        new AccuChallenge(args[0], args[1]);}
      catch (IndexOutOfBoundsException ex) {
        System.err.println(&quot;Insufficient arguments: 2 integers required.&quot;);}
    }
    private AccuChallenge(String arg1, String arg2)
    {
      int a, b;
      try {
        a = Integer.parseInt(arg1);
        b = Integer.parseInt(arg2);
        System.out.print((a &lt;= b) 
          ? new Incrementing(a, b).ret() 
          : new Decrementing(a, b).ret());
      } catch (NumberFormatException nfe) {
        System.err.println(&quot;One or both arguments are not parsable as integers.&quot;);
      }
    }
    private class Incrementing {
      private final List&lt;Integer&gt; result 
        = new ArrayList&lt;&gt;();
      private final int b;
      private int a;
      public Incrementing(int a, int b) {
        this.a = a;
        this.b = b;
        addInt();
      }
      private boolean addInt() {
        return a &lt;= b ? keepGoing() 
          : printResult();
      }
      private boolean keepGoing() {
        result.add(a++);
        addInt();
        return true;
      }
      private boolean printResult() {
        System.out.println(result);
        return true;
      }
      public String ret() {
        return &quot;&quot;;
      }
    }
    private class Decrementing {
      private final List&lt;Integer&gt; result 
        = new ArrayList&lt;&gt;();
      private final int b;
      private int a;
      public Decrementing(int a, int b) {
        this.a = a;
        this.b = b;
        addInt();
      }
      private boolean addInt() {
        return a &gt;= b ? keepGoing() 
          : printResult();
      }
      private boolean keepGoing() {
        result.add(a--);
        addInt();
        return true;
      }
      private boolean printResult() {
        System.out.println(result);
        return true;
      }
      public String ret() {
        return &quot;&quot;;
      }
    }
  }</pre>
  
<p class="EditorIntro">Francis: I note that this is about the longest solution submitted. I wonder if that is inherent in the choice of language.</p>

<h2>From Richard Brookfield</h2>

<p>I managed it in C, originally by using the ternary operator, but that felt like a bit of a cheat (though you didnâ€™t prohibit it), so I refactored it out â€“ hence the two attached versions.</p>

<p class="EditorIntro">Francis: I have omitted the first because of space constraints.</p>

<pre class="programlisting">
#include &lt;stdio.h&gt;
typedef enum tagBOOL
{
  FALSE  = 0,
  TRUE  = 1
} BOOL;
static BOOL ShowNumber(int n)
{
  printf(&quot;%d &quot;,n);
  return TRUE;
}
static BOOL ShowRangeBase(int start, int end,
  BOOL ascending)
{
  int halfwayish  = (start+end)/2;
  return
    // Gone too far
    ascending &amp;&amp; start&gt;end || 
    !ascending &amp;&amp; start&lt;end ||
    // Something to do
    ShowNumber(start) &amp;&amp;
    // Maximum recursion O(log2(n))
    ascending &amp;&amp;
    ShowRangeBase(start+1,halfwayish,ascending) &amp;&amp;
    ShowRangeBase(halfwayish+1,end,ascending)||
    !ascending &amp;&amp;
    ShowRangeBase(start-1,halfwayish,ascending) &amp;&amp;
    ShowRangeBase(halfwayish-1,end,ascending);
}
static void ShowRange(int start, int end)
{
  printf(&quot;Showing range from %d to %d\n&quot;,
    start,end);
  ShowRangeBase(start,end,start&lt;end);
  printf(&quot;\n&quot;);
}
int main(int argc, char *argv[])
{
  // Various examples and edge cases
  int i;
  for (i=-2; i&lt;12; ++i)
  {
    ShowRange(1, i);
  }
  ShowRange(2, 1);
  ShowRange(3, 1);
  ShowRange(5, 1);

  ShowRange(-1, 2);
  ShowRange(2, -1);

  ShowRange(0, 2);
  ShowRange(2, 0);

  // Enough to show the recursion isn't deep
  ShowRange(1, 200);
  return 0;
}</pre>

<p class="EditorIntro">Francis: Whilst this is a fairly long solution, it does a good deal of checking as well as testing edge cases and being adequately commented.</p>

<h2>From Robin Williams</h2>

<p class="EditorIntro">Francis: Though Robin has used the ternary operator, his solution is novel.</p>

<p>I thought of two ways to avoid control statements in C: operator <code>?:</code> and short-circuit logic. Both rely on expression evaluation, which means you need functions to return something, even if the result will be ignored (apart from generating compiler warnings).</p>

<p>The attached uses operator <code>?:</code> for the core logic: the short-circuit version would be more verbose. I use short-circuit logic for error-checking, in a common scripting language idiom.</p>

<p>Itâ€™s possible to do the iteration by simple stepping rather than bisection. However, without tail-call optimization, stepping can cause the program to fail for large ranges.</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int rangeprint(int i1, int i2)
  {
    int im = (i1+i2)/2;
    // If range has one element
    return im == i1 || im == i2 ? 
    printf(&quot;%d\n&quot;,i1) :  // Print that

    // Else split
    rangeprint(i1,im) &amp;&amp; rangeprint(im,i2);
  }
  int usage(char* s, int i)
  {
    printf(&quot;Usage: %s &lt;n1&gt; &lt;n2&gt;\n&quot;,s);
    exit(i);
    return 1;
  }
  int main(int argc, char*argv[])
  {
    int i1, i2;
    argc == 3 || usage(argv[0],1);
    sscanf(argv[1],&quot;%d\n&quot;,&amp;i1) == 1 
      || usage(argv[0],1);
    sscanf(argv[2],&quot;%d\n&quot;,&amp;i2) == 1 
      || usage(argv[0],1);
    i1 == i2 || rangeprint(i1,i2);
    printf(&quot;%d\n&quot;,i2);
  }</pre>

<p class="EditorIntro">Francis: Robin also sent in a system-independent quine.</p>

<pre class="programlisting">
#include &lt;stdio.h&gt;
int main()
{
 char s[]=&quot;#include &lt;stdio.h&gt;\n&quot;
&quot;int main()\n&quot;
&quot;{\n&quot;
&quot; char s[]=$;\n&quot;
&quot; for(char*t=s;*t;++t){\n&quot;
&quot;  if(*t=='$' &amp;&amp; *(t+1)==';'){\n&quot;
&quot;   putchar('\&quot;');\n&quot;
&quot;   for(char*u=s;*u;++u){\n&quot;
&quot;    if(*u=='\\n')printf(\&quot;\\\\n\\\&quot;\\n\\\&quot;\&quot;);\n&quot;
&quot;    else if(*u=='\&quot;')printf(\&quot;\\\\\\\&quot;\&quot;);\n&quot;
&quot;    else if(*u=='\\\\')printf(\&quot;\\\\\\\\\&quot;);\n&quot;
&quot;    else putchar(*u);}\n&quot;
&quot;   putchar('\&quot;');}\n&quot;
&quot;  else putchar(*t);\n&quot;
&quot; }\n&quot;
&quot;}\n&quot;
&quot;&quot;;
 for(char*t=s;*t;++t){
  if(*t=='$' &amp;&amp; *(t+1)==';'){
   putchar('&quot;');
   for(char*u=s;*u;++u){
    if(*u=='\n')printf(&quot;\\n\&quot;\n\&quot;&quot;);
    else if(*u=='&quot;')printf(&quot;\\\&quot;&quot;);
    else if(*u=='\\')printf(&quot;\\\\&quot;);
    else putchar(*u);}
   putchar('&quot;');}
  else putchar(*t);
 }
}</pre>

<h2>A conversation piece from Steven Singer</h2>

<p class="EditorIntro">Francis: I really enjoy this way of presenting a solution. I find them so much more fun than just cold code.</p>

<p>S: Letâ€™s see, you want me to write a program that takes two integer inputs (first and last), to output the integers from the first to the last and you donâ€™t want me to use if, for, switch or while.</p>

<p>F: Yes, and first may be higher than last.</p>

<p>S: There are a couple of ways of interpreting that last condition, Iâ€™ll assume you mean that if <code>first</code> is higher than <code>last</code> you want me to count down. The alternative would be to count from the lower of <code>first</code> and <code>last</code> up to the higher.</p>

<p>F: Thatâ€™s a reasonable interpretation of the problem.</p>

<p>S: OK, letâ€™s recurse and use the ternary operator. Although the ternary operator doesnâ€™t allow us to embed statements, like <code>return</code>, we can embed function calls and thatâ€™s all we need for recursion:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;

  void count(int first, int last, int step)
  {
    printf(&quot;%d\n&quot;, first);
    first != last ? count(first + step, last, step)
    : (void) 0;
  }
  int main(int argc, char *argv[])
  {
    int first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    int last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    int step = first &lt; last ? 1 : -1;
    count(first, last, step);
    return 0;
  }</pre>
  
<p>F: Whatâ€™s the <code>(void) 0</code> for?</p>

<p>S: A ternary operator always has two value expressions but I only need one. I need to specify something in the unwanted path. The two value expressions for the ternary operator must have compatible types. Since <code>count()</code> naturally has no return value, I need the third expression also to have no return value but I canâ€™t leave it blank. Personally, I like using <code>(void) 0</code> as it makes it clear to the reader and the compiler that I really, really want to do nothing. Itâ€™s very Zen.</p>

<p>F: Well, I suppose that works but arenâ€™t you worried about the stack usage of the recursion?</p>

<p>S: A little, but modern compilers are pretty good at tail call optimisations. For example, gcc 5.4.0 at optimisation level 2 produces the following on my Linux box (Iâ€™ll remove some non-essential lines, like call frame information directives, alignment directives, unused labels and so on for clarity):</p>

<pre class="programlisting">
  count:
    pushq %r12
    movl  %edx, %r12d
    pushq %rbp
    movl  %esi, %ebp
    pushq %rbx
    movl  %edi, %ebx
    jmp   .L3
  .L6:
    addl  %r12d, %ebx
  .L3:
    xorl  %eax, %eax
    movl  %ebx, %edx
    movl  $.LC0, %esi
    movl  $1, %edi
    call  __printf_chk
    cmpl  %ebp, %ebx
    jne   .L6
    popq  %rbx
    popq  %rbp
    popq  %r12
    ret</pre>
	
<p>S: You can see the call to <code>printf()</code> but the recursive call to count has become the conditional jump to label <code>.L6</code>.</p>

<p>F: That looks good but what if someone feels that using a ternary operator is perhaps a little too much like an <code>if</code>-<code>else</code>, particularly as there are redundant expressions.</p>

<p>S: No problem, I can remove the ternary operators:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  void count(int first, int last, int step)
  {
    printf(&quot;%d\n&quot;, first);
    (void) (first != last &amp;&amp; (count(first + step,
      last, step), 0));
  }
  int main(int argc, char *argv[])
  {
    int first = 1, last = 100, step = 1;
    (void) (argc &gt;= 2 &amp;&amp; (first = atoi(argv[1])));
    (void) (argc &gt;= 3 &amp;&amp; (last = atoi(argv[2])));
    (void) (first &gt; last &amp;&amp; (step = -1));
    count(first, last, step);
    return 0;
  }</pre>
  
<p>S: There you go, not a ternary operator in sight. The logical operators short-circuit paths that arenâ€™t taken so the recursion terminates properly.</p>

<p>F: I notice youâ€™re using a comma operator.</p>

<p>S: Yes, when using short circuit operators, the terms on either side canâ€™t be void expressions. Since Iâ€™ve declared <code>count()</code> as not having a return value, I need something to keep the compiler happy. I could have avoided the comma operator by declaring <code>count()</code> as returning <code>int</code> but thatâ€™s a little unnatural as thereâ€™s nothing meaningful for <code>count</code> to return.</p>

<p>F: OK, I see what you did there but if weâ€™re avoiding ternary operators then the short-circuit logical operators are still a bit too much like an <code>if</code>.</p>

<p>S: OK, fine, no short-circuiting logical or ternary operators:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  int opt_default(int dflt, char *argv[], int arg)
  {
    return dflt;
  }
  int opt_parse(int dflt, char *argv[], int arg)
  {
    return atoi(argv[arg]);
  }
  int (*opt_select[])(int, char *[], int) = {
    opt_default, opt_parse };
  void nop(int first, int last, int step)
  {
  }
  void count(int, int, int);/* Forward reference */

  void (*funcs[])(int, int, int) = { nop, count };
  void count(int first, int last, int step)
  {
    printf(&quot;%d\n&quot;, first);
    funcs[first != last](first + step, last, step);
  }
  int main(int argc, char *argv[])
  {
    int first = opt_select[argc &gt;= 2](1, argv, 1);
    int last = opt_select[argc &gt;= 3](100, argv, 2);
    int step = (first &lt; last) * 2 - 1;
    count(first, last, step);
    return 0;
  }</pre>
  
<p>S: This time, there are no <code>if</code>-like operators at all. Iâ€™ve used two-element arrays of function pointers and then indexed them with boolean expressions. Element zero gets called when the expression is false and element one gets called when the expression is true.</p>

<p>F: Isnâ€™t that a bit obscure?</p>

<p>S: Actually, no. Many real systems defer complex decisions to state machines and the core of a state machine is logically a two-dimensional array of function pointers indexed by the current state and the event received. Usually thereâ€™s some compression of the data structures as not all events can be received in all states. Think of the code I just gave as a state machine compressed to deal with having just one state in which it can receive events (printing a number) and two events (continue and stop).</p>

<p>F: I suppose thatâ€™s fair.</p>

<p>S: Did you know that even though weâ€™re using function pointers, GCC has still performed the tail call optimisation so we wonâ€™t overflow the stack:</p>

<pre class="programlisting">
  count:
    pushq %r12
    pushq %rbp
    movl  %edx, %r12d
    pushq %rbx
    movl  %esi, %ebp
    movl  %edi, %ebx
    movl  %edi, %edx
    movl  $.LC3, %esi
    movl  $1, %edi
    xorl  %eax, %eax
    call  __printf_chk
    xorl  %eax, %eax
    cmpl  %ebp, %ebx
    leal  (%rbx,%r12), %edi
    setne %al
    movl  %r12d, %edx
    movl  %ebp, %esi
    popq  %rbx
    popq  %rbp
    popq  %r12
    movq  funcs(,%rax,8), %rax
    jmp   *%rax</pre>
	
<p>S: The <code>jmp *%rax</code> is a tail call to the function pointer. You can see the three <code>popq</code>s a few lines earlier that unwind this stack frame.</p>

<p>F: Hmm, not all compilers are that good at tail call optimisation and it may depend on which processor is being targeted. Can you avoid recursion completely?</p>

<p>S: Sure, but do you mind if I go back to using ternary operators for the simple <code>if</code> conditions? Iâ€™ve got a choice of several options but ternary operators will make it easier to see the new code.</p>

<p>F: Itâ€™s the least I can do.</p>

<p>S: OK, here goes, but be warned that since youâ€™ve taken away <code>for</code>, <code>while</code> and recursion, I can think of only one way to make the loop I need:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  int main(int argc, char *argv[])
  {
    int first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    int last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    int step = first &lt; last ? 1 : -1;
  loop:
    printf(&quot;%d\n&quot;, first);
    first == last ? exit(0) : (void) 0;
    first += step;
    goto loop;
  }</pre>
  
<p>S: We couldnâ€™t use this trick for <code>return</code> as itâ€™s a statement but <code>exit()</code> is a function. C is a small language, a lot of functionality is provided by functions in libraries.</p>

<p>F: Exiting the entire program is a bit brute force; you canâ€™t use this trick in a function embedded in a program.</p>

<p>S: The rules donâ€™t say this has to be a function.</p>

<p>F: I suppose they donâ€™t but itâ€™d be a better example if it were.</p>

<p>S: OK, how about this:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;setjmp.h&gt;
  void count_internal(int first, int last, 
    int step, jmp_buf env)
  {
  loop:
    printf(&quot;%d\n&quot;, first);
    first == last ? longjmp(env, 1) : (void) 0;
    first += step;
    goto loop;
  }
  void count(int first, int last, int step)
  {
    jmp_buf env;
    
    setjmp(env) ? (void) 0 
      : count_internal(first, last, step, env);
  }
  int main(int argc, char *argv[])
  {
    int first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    int last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    int step = first &lt; last ? 1 : -1;
    count(first, last, step);
    return 0;
  }</pre>
  
<p>S: There you go, no premature exit.</p>

<p>F: Oh good grief. That is not a better example.</p>

<p>S: Thatâ€™s the first time Iâ€™ve used <code>setjmp</code>/<code>longjmp</code>.</p>

<p>F: Iâ€™m glad to hear it.</p>

<p>S: It kept me entertained.</p>

<p>F: Thatâ€™s what concerns me.</p>

<p>S: I can do worse.</p>

<p>F: Oh dear.</p>

<p>S: How about this:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  int main(int argc, char *argv[])
  {
    int first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    int last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    int reverse = first &gt; last;
    char buffer[256];
    sprintf(buffer, &quot;perl -e 'print map { \&quot;$_\\n\&quot;
      } %s (%d..%d)'&quot;, reverse ? &quot;reverse&quot; : &quot;&quot;,
      reverse ? last : first,
      reverse ? first : last);
    (void) system(buffer);
    return 0;
  }</pre>
  
<p>F: How can you justify that?</p>

<p>S: Like the function pointers code being an example of a more sophisticated technique (state machines) which is valid for more complex problems, sometimes itâ€™s important to realise youâ€™re using the wrong language to solve a problem. Why write a thousand lines of hard-to-debug C when it might only take a couple of lines in Perl.</p>

<p>F: A couple of lines of hard-to-debug Perl. You could use Python.</p>

<p>S: OK, a dozen lines of hard-to-debug Python. Itâ€™s the programmer that makes code hard-to-debug, not the language.</p>

<p>F: Letâ€™s not start a flame war.</p>

<p>S: Spoilsport. But even if you donâ€™t go to another language, you should look at the libraries for the language youâ€™re using. In the Perl example, the loops and the iteration are implicit. Many languages have similar higher-level constructs. C has a smaller set, but there are some useful routines there (not to mention a wide variety of third party libraries). For example, if you wanted to sort an array in C you wouldnâ€™t write your own sort routine without having a story as to why the library <code>qsort()</code> routine wasnâ€™t suitable. Writing sort routines from scratch is error prone; itâ€™s better to avoid it if possible. Less well-known are functions for searching flat arrays either linearly or using binary search. There are even functions for managing binary trees and hash tables. For example, we can solve the problem with this program, which you could imagine as a learning exercise to investigate the order in which <code>lfind()</code> visits a linear array just with the output slightly manipulated to give the numbers we want:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;search.h&gt;
  struct params {
    int first;
    int step;
    char *base;
  };
  int compar(const void *key, const void *velem)
  {
    const struct params *pp = key;
    const char *elem = velem;
    int index = (int) (elem - pp-&gt;base);
    printf(&quot;%d\n&quot;, index * pp-&gt;step + pp-&gt;first);
    return 1; /* Keep going */

  }
  int main(int argc, char *argv[])
  {
    struct params p;
    int last;
    size_t num;
    p.first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    p.step = p.first &lt; last ? 1 : -1;
    num = (last - p.first) * p.step + 1;
    p.base = malloc(num);
    (void) lfind(&amp;p, p.base, &amp;num, 1, compar);
    return 0;
  }</pre>
  
<p>F: I notice you didnâ€™t initialise the array you allocate.</p>

<p>S: Thereâ€™s no need as I never actually dereference the values. I just print out the order in which the array indexes are visited.</p>

<p>F: I guess thatâ€™s technically correct, even if itâ€™s a little ugly. You are using a lot of memory for no benefit.</p>

<p>S: I wanted to keep it legal so I needed to ensure the pointers <code>p.base</code> and <code>elem</code> pointed to the same object otherwise the subtraction wouldnâ€™t be defined in the C specification. Some equivalent techniques in other languages might suffer the same problem; for example, building the entire output in memory before writing it out consumes memory. Sometimes this is a problem and using iterator functions or objects can help. Other times, the problem youâ€™re solving requires having all the data in memory so you have to pay that cost anyway. However, overall, I agree for this problem itâ€™s ugly and overkill. I donâ€™t even test whether the allocation succeeded.</p>

<p>F: It could be worse, at least you didnâ€™t abuse the C pre-processor.</p>

<p>S: Did someone say â€œ<em>abuse the C pre-processor</em>â€:</p>

<pre class="programlisting">
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #define PASTE(a, b) b ## a
  #define until(x) PASTE(ile, wh) (!(x))
  int main(int argc, char *argv[])
  {
    int first = argc &gt;= 2 ? atoi(argv[1]) : 1;
    int last = argc &gt;= 3 ? atoi(argv[2]) : 100;
    int step = first &lt; last ? 1 : -1;
    do {
      printf(&quot;%d\n&quot;, first);
      first += step;
    } until(first == last + step);
    return 0;
  }</pre>
  
<p>F: I should have kept my mouth shut.</p>

<p>S: Hey, it obeys the rules, it doesnâ€™t contain the word â€˜whileâ€™, it doesnâ€™t even include the letters w, h, i, l and e in that order.</p>

<p>F: Can we stop now?</p>

<p>S: Nope. A coding competition isnâ€™t over until someone abuses the rules.</p>

<p>F: And that last example didnâ€™t already abuse the rules?</p>

<p>S: Letâ€™s pretend itâ€™s an important real-world lesson about requirements. What did the rules say the program had to output?</p>

<p>F: â€œ<em>the integers from the first to the last</em>â€.</p>

<p>S: Thanks for the quotation marks:</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  int main(void)
  {
    printf(&quot;the integers from the first to the last\n&quot;);
    return 0;
  }</pre>
  
<p>S: Does it help if I pretend itâ€™s an important lesson about escaping strings to avoid SQL injection attacks and similar.</p>

<p>F: Not really. Please can we stop now?</p>

<p>S: Alright. Iâ€™ve had my fun.</p>

<p>F: Yes, you seemed to be enjoying this all too much.</p>

<h2>From Stephen Baynes</h2>

<p class="EditorIntro">Francis: Here is an interesting collection of (short) solutions.</p>

<p>The problem is not how to do it at all, C provides short circuit operators that combined with recursion easily do the job (1, 2, 3) but how many other ways it can be done. One can terminate a <code>goto</code> loop by terminating the program with assert (4), division by zero [undefined behaviour so will depend on implementation] (5) or by the process killing itself using some clever arithmetic using booleans as integers to calculate signal number that does or does not stop execution [requires POSIX] (6). Using booleans as integers can be used to select a function to call from a table that recurses or not to end the loop (7). It should be possible to recursively use the error callback of <code>memset_s</code> to provide a controlled recursive loop (8) but I was unable to find a compiler that implements this optional feature so this code is untested.</p>

<p>One could do all sorts of non-portable implementations using system but that is outside the spirit of doing it in C.</p>

<p>I wondered about printing consecutive numbers from the comparison function passed to <code>qsort</code>. <code>qsort</code> on an array of size <em>n</em> would give you at least <em>n</em>-1 comparisons but could give more though a finite amount. The printing would terminate, but it would be very difficult to ensure it terminated at the right time and when it terminated would not be portable.</p>

<p>Having to read in the <code>first</code> and <code>last</code> values means one cannot use recursive pre-processor macros to solve the challenge.</p>

<p class="EditorIntro">Francis: Which is just as well because this column is already heading for record-breaking size.</p>

<p><strong>1)</strong></p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  static int from, to;
  int pri( int n ){
    printf( &quot;%d\n&quot;, n );
    n &lt; to &amp;&amp; pri( n + 1 );
    return n;
  }
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    pri( from );
    return 0;
  }</pre>
  
<p><strong>2)</strong></p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  static int from, to;
  int pri( int n ){
    printf( &quot;%d\n&quot;, n );
    n &gt;= to || pri( n + 1 );
    return n;
  }
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    pri( from );
    return 0;
  }</pre>
  
<p><strong>3)</strong></p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  static int from, to;
  int pri( int n ){
    printf( &quot;%d\n&quot;, n );
    n &lt; to ? pri( n + 1 ) : 0;
    return n;
  }
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    pri( from );
    return 0;
  }</pre>
  
<p><strong>4)</strong></p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;assert.h&gt;
  static int from, to;
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    int n = from;
  LOOP:
    printf( &quot;%d\n&quot;, n );
    assert( n &lt; to );
    ++n;
    goto LOOP;
    return 0;
  }</pre>
  
<p><strong>5)</strong></p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  static int from, to;
  static int j = 0;
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    int n = from;
  LOOP:
    printf( &quot;%d\n&quot;, n );
    j =  1 / ( to -n );
  // This might depend on your compiler
    ++n;
    goto LOOP;
    return 0;
  }</pre>
  
<p><strong>6)</strong></p>

<pre class="programlisting">
  #include &lt;sys/types.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  static int from, to;
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    int n = from;
    pid_t pid = getpid();
  LOOP:
    printf( &quot;%d\n&quot;, n );
    int j = (int)( n &gt;= to );
    kill( pid, j * SIGTERM ) ; 
      // Signal 0 does not signal.
    ++n;
    goto LOOP;
    return 0;
  }</pre>
  
<p><strong>7)</strong></p>

<pre class="programlisting">
  #include &lt;sys/types.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  static int from, to;
  typedef void action( int );
  action *jump_table[2];
  static void action_end( int n ) { }
  static void action_next( int n ) {
    printf( &quot;%d\n&quot;, n );
    int j = (int)( n &gt;= to );
    jump_table[ j ]( n + 1 );
  }
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
  
    jump_table[ 0 ] = action_next;
    jump_table[ 1 ] = action_end;
    action_next( from );
    return 0;
  }</pre>
  
<p><strong>8)</strong></p>

<pre class="programlisting">
  // This code is not tested as my compiler 
  // does not support memset_s
  #define __STDC_WANT_LIB_EXT1__ 1
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  static int from, to;
  static int n;
  void pri( void ){
    printf( &quot;%d\n&quot;, 1 + from - n );
    --n;
    char c;
    memset_s( &amp;c, 1, 0, n );
  }
  void ch(
    const char *restrict msg,
    void *restrict ptr,
    errno_t error
  ){
    pri()
  }
  int main(){
    scanf( &quot;%d %d&quot;, &amp;from, &amp;to );
    n = 1 +  from - to;
    set_constraint_handler_s( ch )
    pri( );
    return 0;
  }</pre>

<h2>From Tim Kent</h2>

<p>My first thought was how to control program flow without loops and <code>if</code> statements and it didnâ€™t take a moment to recall a code base that I inherited which uses exceptions for normal code flow. I ignored the use of the ternary (<code>?:</code>) operator thinking that this was not in the spirit of the challenge. So how could I use exceptions to control a loop? The first thing that came to mind was divide by zero. This led me to the following solution:</p>

<pre class="programlisting">
  #include &lt;iostream&gt;
  int main()
  {
    /*Here is an initial idea using divide by zero,
      to solve Challenge 4 in CVU Vol 30 Issue 3,
      July 2018 */
    int first = 1;
    int last = 100;
    /*check that first is less than last otherwise
      fault on divide by zero to terminate program.
      TRUE - TRUE = 0*/
    volatile int terminating_calc1 = 
      1/ ((first &gt; last) - true);
  loop:
    std::cout &lt;&lt; first++ &lt;&lt; '\n';
    volatile int terminating_calc2 =
      1/(last-first+1);
      /* fault terminate with divide by zero after
         we reached the last number */
    goto loop;
    return 0;
  }</pre>
  
<p>The only problem is that this signals and terminates [<em>well, you hope it does that rather than rewrite your hard-drive</em> &#9786;] the program meaning this could not be used in a larger program. Sure, it would be possible to handle the signal and not terminate but that would be platform dependent code. How to conditionally throw an exception? I almost have this condition in the program above. <code>True - True == 0</code>, <code>True - False == ?</code>. If I could force <code>True - False == 1</code> then I could use a two-element array of functions to throw or not throw based on the index. I ended up just dividing by true to achieve this. The only other question in my mind was what to throw. I arbitrarily chose a <code>void</code> pointer so as not to interfere with any other code that might be used with this solution (not that I am recommending using this solution anywhere!), which leads to the following solution:</p>

<pre class="programlisting">
  void throw_if_true(bool condition)
  {
    typedef void fntype();
    static fntype* fn_lut[2] = { []{
      throw static_cast&lt;void*&gt;(0);}, []{}};
    int index = (true - condition)/true;
    fn_lut[index]();
  }

  int main()
  {
  /*Using an exception for flow control, to solve
    Challenge 4 in CVU Vol 30 Issue 3, July 2018 */
    int first = 1;
    int last = 100;
    try{
      throw_if_true(first &gt; last);
      loop:
      std::cout &lt;&lt; first++ &lt;&lt; '\n';
      throw_if_true(first &gt; last);
      goto loop;
    }catch(...) {}
    return 0;
  }</pre>

<p>Now that this works, can I go a step further and avoid signals and exceptions altogether? Building on what I have so far, I thought about replacing the lambda that throws with a lambda that recurses, and this led eventually to the following solution.</p>

<pre class="programlisting">
  #include &lt;iostream&gt;
  typedef void fntype(int,int);
  void count_inner(const int first,
    const int last);
  static fntype* fn_lut[2] = {
    [](const int first, const int last){},
    [](const int first, const int last)
    {count_inner(first+1, last);} };
  void count_inner(const int first, const int last)
  {
    int index = (true - (first &gt; last))/true;
    std::cout &lt;&lt; first &lt;&lt; '\n';
    fn_lut[index](first, last);
  }
  void count(const int first, const int last)
  {
    int index = (true - (first &gt; last))/true;
    fn_lut[index](first-1, last-1);
  }
  int main()
  {
  // Using recursion  for flow control, to solve
  // Challenge 4 in CVU Vol 30 Issue 3, July 2018
    int first = 1;
    int last = 100;
    count(first, last);
    return 0;
  }</pre>

<h2>From Colin Hersom</h2>

<p>In <em>CVu</em> 30.3, you challenged us to devise a program to output a sequence of numbers without using <code>for</code>, <code>if</code>, <code>switch</code> and <code>while</code>. You also made an implicit challenge to do it in C (by stating that you could not) as well as C++. Now, I know that you are a very clever man and know the intricacies of C in far more detail than most, so I was surprised at the statement that you could not do it in C. If this was meant as a provocation, it worked!</p>

<p class="EditorIntro">Francis: Hmmâ€¦ I am getting old and forgetful. For example I forgot to exclude the ternary operator. &#9786;</p>

<p>I agree that recursion (or indeed anything) cannot know when to stop without a condition (unless you cause the program to crash!), but you have not excluded conditions, only those keywords. There is still the conditional operator, and I have used this in my solution [<span class="EditorIntro">omitted to save space</span>]. The problem with this is that the recursion will take up a lot of stack space and if you ask for a very large range, the system may run out of space and cause an error. With my system, it crashes when asked to produce a sequence of around 261,850 numbers, but varies from run to run. [<span class="EditorIntro">You need a better compiler that spots tail recursion. </span> &#9786;]</p>

<p>So to C++. My first solution was to create a vector with all the numbers in and then output the vector. This is OK, but also uses stack space, although not so much. However, the vector is being created and then written, without any other use, so it seemed sensible to remove the vector completely and replace it with an iterator that produced the correct sequence, outputting that directly.</p>

<p class="EditorIntro">Francis: Both of Colinâ€™s C++ solutions use the ternary operator in the set-up in <code>main</code> but the actual method for creating the desired output do not. I have provided them because they have interesting mechanisms.</p>

<pre class="programlisting">
  class sequence_interator :
    public   iterator&lt;forward_iterator_tag, int&gt;
  {
  public:
    sequence_interator(int start, int end)
      : current(start)
      , last(end)
      , inc(start &lt; end ? 1 : -1)
    {  }
    sequence_interator &amp;begin()
    {
      return *this;
    }
    sequence_interator &amp;end()
    {
      return *this;
    }
    // The compared interator is always 'this' so
    // no need to examine it
    // Just using to test for the last one
    bool operator !=(const sequence_interator&amp;)
    {
      return last != current - inc;
    }
    sequence_interator &amp;operator++()
    {
      current += inc;
      return *this;
    }
    int operator *() const
    {
      return current;
    }
  private:
    int current;
    int last;
    int inc;
  };
  int main(int av, char **ac)
  {
    int start = av &gt;1 ? atoi(ac[1]) : 0;
    int end = av &gt;2 ? atoi(ac[2]) : 100;
    int inc = start &lt; end ? 1 : -1;
    sequence_interator seq(start, end);
    copy(seq.begin(), seq.end(),
      ostream_iterator&lt;int&gt;(cout, &quot; &quot;));
    cout &lt;&lt; endl;
    return 0;
  }</pre>

<h2>From Burkhard Kloss</h2>

<p>Spurred on by Francisâ€™s challenge, I dusted off the C compiler and wrote my first C program in ... over a decade at least? Turns out I can still do it, although I wouldnâ€™t say Iâ€™m particularly proud of this one. It does work, though, and matches the spec as far as I can tell. For the simple case, this should do the trick.</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int quitter()
  {
    exit(0);
    return -1;
  }
  int main()
  {
    int i = 1;
  start:
    printf(&quot;%d\n&quot;, i);
    i = i &lt; 100 ? i + 1 : quitter();
    goto start;
  }</pre>
  
<p class="EditorIntro">Francis: Yes, but I forgot to exclude the ternary operator. Your solution can be amended to avoid use of the ternary operator by replacing that statement with:</p>

<pre class="programlisting">
  i &lt; 100 || quitter(); ++i;</pre>
  
<p class="EditorIntro">I notice that the ternary operator can almost invariably be replaced by lazy evaluation. For example, usually this:</p>

<pre class="programlisting">
  expr1 ? expr2 : expr3</pre>
  
<p class="EditorIntro">can be transformed into:</p>

<pre class="programlisting">
  (expr1 &amp;&amp; expr2) ||| expr3;</pre>
  
<p>Using the same approach for the extended problem with inputs of <code>first</code> and <code>last</code> on the command line â€“ even including rudimentary input checking:</p>

<pre class="programlisting">
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int quitter()
  {
    exit(0);
    return -1;
  }
  int sign(int x)
  {
    return x &gt; 0 ? 1 : -1;
  }
  int noisy_quit(char const * msg)
  {
    puts(msg);
    exit(1);
    return -1;
  }
  void check_args(int argc)
  {
    argc == 3 ? 0 : noisy_quit
      (&quot;first_to_last start stop&quot;);
  }
  int main(int argc, char * argv[])
  {
    check_args(argc);
    int start = atoi(argv[1]);
    int stop = atoi(argv[2]);
    int step = sign(stop - start);
    int i = start;
  loop:
    printf(&quot;%d\n&quot;, i);
    i = i != stop ? i + step : quitter();
    goto loop; 
  }</pre>
  
<p>Not the worldâ€™s most elegant code, but it seems to handle all possible conditions, and has no sign of <code>if</code>, <code>for</code>, <code>while</code>, or <code>switch</code>.</p>

<h2>And the winner isâ€¦</h2>

<p>Well, none of the above. I have asked Steve to turn the winning submission (from Andreas Gieriet) into a free-standing article, which you will find on page 6.</p>

<p>Thanks to all of you who have put in so much thought and ingenuity. It is eye-opening to see how many completely different solutions you collectively managed to find.</p>

<h2>Challenge 5</h2>

<p>Many years ago someone â€“ I have forgotten who â€“ ran a competition for writing a (natural) language that only had seven words. The trap was to assume that each word had to have a single meaning. To deal with such a paucity of words requires making good use of combinations. Start with two words meaning one and zero then using binary you have an unlimited supply of numbers. Now make a third word mean â€˜select meaning <em>n</em> from the next wordâ€™ and you have an unlimited supply of meanings available to you (and only using four words â€¦ and yes, I know that I could do the same with only three words).</p>

<p>However, I am going to test your ingenuity by asking you to select seven operators with their normal meanings. No grotesque multi-purpose operators. So if <code>+</code> is one of your operators, <code>a+b</code> will mean add â€˜a to bâ€™)</p>

<p>Having chosen your seven operators, show how you would obtain as many other operators from C++ as you can. To get you started: Suppose that one of your seven operators is <code>-</code> then you could write:</p>

<pre class="programlisting">
  template&lt;typename T&gt; T operator+(T t1, T t2)
    { return t1 - (0 - t2)};</pre>

<p>I am pretty sure you cannot find a subset of seven operators that spans the set of C++ operators but I wonder how far you can get.</p>

<p>Submissions to francis.glassborow@gmail.com</p>

<p class="bio"><span class="author"><b>Francis Glassborow</b></span>  Since retiring from teaching, Francis has edited <em>C Vu</em>, founded the ACCU conference and represented BSI at the C and C++ ISO committees. He is the author of two books: <em>You Can Do It!</em> and <em>You Can Program in C++</em>.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
