NZ Info For UK Visitors »

Someone else's homework

  by  , Friday 21 September 2018, Categories: Info

Here's another flashback. I used to follow comp.lang.c++ on Usenet & one of the ongoing annoyances was students who wanted the group to do their homework. One day I was feeling especially irritated so I deliberately wrote a C++ program that solved the problem but still should have got the student a fail. Explanation for why if should be a fail is at the bottom of this post.

His question:

How can you write a program in C++ by using loop to control the calculation without the use of library function pwr .For example 3 to the power of 4 (ie 3x3x3x3). Any help will be appreciated

To which I replied:

Try something like this. It uses a redundant loop and calculates X to the power of Y in approximately Y! steps.

/***************************************************************************
main.cpp - description
   -------------------
   begin : Thu Apr 15 19:35:27 NZDT 2004
   copyright : (C) 2004 by Julia Clement
   email : 

***************************************************************************/

/***************************************************************************
*
* This program is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any
* later version.
*
**********************************************************************/

#include  <iostream>

double power( double x, int y )
{
    double rslt = 1;
    for( int i = y; 0 < i--; )
        rslt = x * power( x, y - 1 );
    return rslt;
}


int main(int argc, char *argv[])
{
    std::cout << "Zap, Pow, Kapow ... 3^4 = " << power( 3.0, 4 ) <<
    std::endl;

    return 0;
}

So, why should this fail the assignment? Because the specification was supposed to be a loop solving the problem and I've supplied a loop, but it doesn't do anything, it simply discards the result of every iteration except the last. The actual calculation of the answer is recursive.

Other people picked up on the thread and produced even more inefficient and obscure calculations. It was fun reading them.

 

Revisiting it today, the only surprise to me was that I was still following UseNet as late as 2004. I thought it was pretty dead a few years earlier.

No feedback yet


Form is loading...

October 2018
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
 << <   > >>

Search

  XML Feeds

Website engine