Monday, November 2

Getting back into C++

...with my stepdad. We come up with problems to solve for fun, then try to independently code them and compare our solutions. We're just using a console rather than use the Windows GUI APIs (MFCs, all that stuff), just to get to the core of the programs for now. Maybe we'll do more object-oriented and GUI stuff in the future (he knows a lot more than I do), but for now my brain needs to warm back up.

Our first problem was to ask the user how many prime numbers he/she would like, then to find and output that many. We both (eventually) got it to work. Here was my code:

// "Primes" (2009) - J. Sias 

#include "stdafx.h"
#include "iostream.h" // for cin and cout
#include "math.h"     // for sqrt function
using namespace std;

bool isPrime(int);    // returns true if prime, false if not

int main(void)
{
int  primesWanted,
     primesFound = 0,
     nextInt = 2;
char toEnd;

// ask how many primes wanted
cout << "How many primes do you want? (minimum 1): ";
cin >> primesWanted;

// find and display that many primes
do {
  if(isPrime(nextInt))
  {
    cout << nextInt << " ";
    primesFound++;
  }
  nextInt++;
  } while (primesFound < primesWanted);

// pause so user can see output
cout << "\n" << "There you go! Enter a character to continue... ";
cin >> toEnd;

return(0);
}

bool isPrime(int num)
{
// 2 is prime by definition
if(num == 2)
return true;

// test for factors
for(int i = 2; i <= (int) sqrt((float) num); i++)
  if(num % i == 0)
  return false;

// if no factors, it's prime
return true;  
}

His code was a lot different, but both worked just as well, which goes to show there are as many solutions to a given problem as there are programmers!

Now that I've got Visual Studio set up and (sort of) figured out the actual IDE itself, which is a bit cumbersome, I hope the next program will go more smoothly. Fun!

4 comments:

Katbili said...

Looks like Greek to me, but sounds fun ;)

Metamatician said...

Greek, good one :)

billybytedoc said...

It is Greek, how did you know? er... maybe it's geek.

Metamatician said...

Haha, Geek for sure! But I think Kat likes Geek and Greek, since she's a biologist and born and raised in Greece. :-)

Archived Posts

Search The Meta-Plane