Saturday, December 12, 2009

C++ Solution for Hoppity problem

Here's a C++ language solution for the Hoppity problem. This is part of the Code Snippet series.

To run this:
Make a simple Make file and a script to run the resulting executable, or else run it in your favorite C IDE. I used Netbeans to build this one. The only argument to the exe is the path to the file that contains the number as described by Hoppity.

The code:

#include <stdlib.h>
#include <iostream>
#include <fstream>

using namespace std;

bool isModN(int num, int mod){
if ((num % mod) == 0){
return true;
}
return false;
}

int main(int argc, char** argv) {

if (argc < 2){
cout << "Must have 1 argument, the file name" << endl;
exit(1);
}

ifstream inFile;

inFile.open(argv[1]);
if (!inFile) {
cout << "Unable to open file" << endl;
exit(1); // terminate with error
}

int theNum;
while (inFile >> theNum) {
// assume it's good -- don't do this when coding for 'real'!
}

inFile.close();

for (int kount = 1; kount < (theNum + 1); kount++){
if (isModN(kount, 3) && isModN(kount, 5)){
cout << "hop" << endl;
continue;
}
if (isModN(kount, 3)){
cout << "Hoppity" << endl;
continue;
}
if (isModN(kount, 5)){
cout << "Hophop" << endl;
continue;
}
}

return (EXIT_SUCCESS);
}

No comments: