The Elephant of Surprise


I am continuing to teach C++, which I am now convinced is a specialized language whose main feature is unchecked array access. However, my students discovered a cool application of said feature. I asked students to write some code to turn this elephant


into this grid of 4 elephants:


They have a primitive bitmap library, which reads a 256 pixel square grayscale bitmap into a 256-by-256 array of unsigned chars (bytes). Here is an attempted solution that several students stumbled upon:

#include "bmplib.h"

int main() {
  unsigned char src[256][256];
  unsigned char dest[256][256];
  readGSBMP("elephant.bmp", src);
  for (int i=0; i<256; i++) // row
    for (int j=0; j<256; j++) // column
      dest[i][j] = src[2*i][2*j];

To their surprise and mine, it generated the following picture, which was way cooler than the desired one:


The questions for the reader are:

  • why does the result look like this?
  • what needs to change to get the 4-elephant grid originally desired?

2 Responses to “The Elephant of Surprise”

  1. 1 Sara

    Lovely 🙂

  2. I would have expected src and dest to be ordered differently in memory, but this is pretty sweet! I guess to fix that you need a % 256 (or & 255) during indexing, but since the indexes are 8-bit I would go with a left rotate 1. I like to use all of my elephants…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: