C++

Home / projects / code / C++

Some simple C++ code.

Greatest Common Divisor

Find the greatest common divisor of two numbers in the least recursive calls.


/* 
Author: [Me] 
Date: 14 July 11 
Purpose: Program to find the greatest common divisor of two 
numbers selected by the user.
*/

#include 

using namespace std;

int gcd(int, int); // function prototype for gcd function

int main()
{
  int x, y, greatestCommon; 

  cout << "Enter a number for x: ";
  cin >> x;

  cout << "Enter a number for y: ";
  cin >> y;

  greatestCommon = gcd(x, y);

  cout << "The greatest common divisor is " << greatestCommon << endl;

  return 0;
}

int gcd(int x, int y)
{
  if (x % y == 0) {
    return y;
  }
  else {
    gcd(y, x % y); // recursive call
  }
}

// or gc could be written this way, but there will be one more recursion
//
// int gcd(int x, int y) {
//   if (y == 0) {
//     return x;
//   }
//   else {
//     gcd(y, x % y);
//   }
// }

Number Guessing Game

Game program which selects a random number and has the user make guesses as to what the number is by giving feedback on whether the users number was higher or lower.


/* 
Author: [Me] 
Date: 14 July 11 
Purpose: Game program which selects a random number and has the user make guesses as to what the number is by giving feedback on whether the users number was higher or lower.
*/

#include <iostream>
#include <cstdlib> 

using namespace std;

int main()
{
  int randomNumber;
  unsigned int userGuess; // set userGuess unsigned to eliminate any negative user input
  int guessCount=0;

  srand(time(0)); // introduce a random seed based on the system time
  randomNumber = (1 + rand() % 1000); // generate a random number between 1 and 1000

  // loop until the user guesses the correct number
  while (userGuess != randomNumber) 
  {
    cout << "Pick a number between 1 and 1000: ";
    cin >> userGuess;

    if (userGuess < randomNumber) {
      cout << "Too Low! Try Again!\n";
      guessCount++; // increment guessCount to track guess attempts
    }
    else if (userGuess > randomNumber) {
      cout << "Too High! Try Again!";
      guessCount++;
    }
    else {
      cout << "You Guessed It!\n";
    }
  }


  // provide user feedback based on number of guesses needed to guess correctly
  if (guessCount < 10) {
    cout << "You either know the secret or you got lucky!";
  }
  else if (guessCount == 10) {
    cout << "Ahah! You know the secret!";
  }
  else {
    cout << "You can do better!";
  }

  return 0;
}

Tortoise VS Hare Simulation

Do a tortoise VS hare simulation.


/*
Author: [Me]
Date: 22 June 11
Purpose: Write a Tortoise VS Hare race simulation. 
*/ 

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

void Delay(float);
void displayPositions(int, int);
void movePositions(int *, int *);

int main() {

  int harePosition = 1;
  int tortoisePosition = 1;

  cout << "\nBANG !!!!";
  Delay(1);
  cout << "\nAND THEY'RE OFF !!!!\n";

  while (harePosition != 70 && tortoisePosition != 70) {
    movePositions(&harePosition, &tortoisePosition);
    displayPositions(harePosition, tortoisePosition);
    Delay(1);
  }

  if (harePosition == 70 && tortoisePosition == 70) {
    cout << "It's a tie.";
  }
  else if (tortoisePosition == 70 && harePosition < 70) {
    cout << "TORTOISE WINS!!! YAY!!!";
  }
  else {
    cout << "Hare wins. Yuch.";
  }

  return 0;
}

void Delay(const float seconds) {
  clock_t delay = clock_t(seconds * CLOCKS_PER_SEC);
  clock_t start = clock();
  while (clock() - start < delay);
}

void displayPositions(int harePosition, int tortoisePosition) {
  for (int pathCounter = 1; pathCounter <= 70; pathCounter++) {
    if (harePosition == pathCounter && tortoisePosition == pathCounter) {
      cout << "OUCH!";
    }
    else if (harePosition == pathCounter) {
      cout << "H";
    }
    else if (tortoisePosition == pathCounter) {
      cout << "T";
    }
    else {
      cout << "-";
    }
  }
  cout << endl;
}

void movePositions(int *harePositionPtr, int *tortoisePositionPtr) {
  int randomNumber; 

  srand(time(0)); // introduce a random seed based on the system time
  randomNumber = (1 + rand() % 10); // generate a random number between 1 and 10
  cout << randomNumber << endl;
  if (randomNumber <= 3) {
    *tortoisePositionPtr = *tortoisePositionPtr + 3;
    *harePositionPtr = *harePositionPtr + 1;
  }
  else if (randomNumber > 3 && randomNumber <= 5) {
    *tortoisePositionPtr = *tortoisePositionPtr + 3;
    *harePositionPtr = *harePositionPtr + 9;
  } 
  else if (randomNumber > 5 && randomNumber <= 7) {
    *tortoisePositionPtr = *tortoisePositionPtr - 6;
    *harePositionPtr = *harePositionPtr - 2;
  } 
  else if (randomNumber > 7 && randomNumber <= 9) {
    *tortoisePositionPtr = *tortoisePositionPtr + 1;
  } 
  else {
    *tortoisePositionPtr = *tortoisePositionPtr + 1;
    *harePositionPtr = *harePositionPtr - 12;
  } 

  if (*harePositionPtr <= 1) {
    *harePositionPtr = 1;
  }

  if (*tortoisePositionPtr <= 1) {
    *tortoisePositionPtr = 1;
  }

  if (*harePositionPtr >= 70) {
    *harePositionPtr = 70;
  }

  if (*tortoisePositionPtr >= 70) {
    *tortoisePositionPtr = 70;
  }
}

Decks of Cards

Initialize a deck of cards and then deal all of them.

decks.cpp

/* 
Author: [Me] 
Date: 14 July 11 
File name: decks.cpp 
Purpose: Create a Card class and a DeckOfCards Class
*/ 

#include <iostream>
#include "Card.h"
#include "DeckOfCards.h"

using namespace std;

int main()
{
	DeckOfCards myDeckOfCards;

	cout << "This program will initialize a deck of cards and then deal all 52 cards." << endl;

	myDeckOfCards.shuffleCards();

	while (myDeckOfCards.moreCards()) {
		myDeckOfCards.dealCards();
	}

	return 0;
}

Comment comming.

Card.h

/* 
Author: [Me] 
Date: 14 July 11 
File name: Card.h 
Purpose: Card class definition
*/

// prevent multiple inclusions of the header file
#ifndef CARD_H
#define CARD_H

// Card class definition
class Card
{
	public:
		Card(int, int);
		void toString();
	private:
		int cardFace;
		int cardSuit;
};

#endif

Comment Comming.

Card.cpp

/* 
Author: [Me]
Date: 14 July 11 
File name: Card.cpp 
Purpose: Card class member function definitions
*/
#include <iostream>
#include <iomanip>
#include <string>
#include "Card.h"

using namespace std;

static char * suitName[4] = {"Hearts","Diamonds","Clubs","Spades"};
static char * faceName[14] = {"Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"};

Card::Card(int face, int suit)
{
	cardFace = face;
	cardSuit = suit;
}

void Card::toString()
{
	cout << faceName[cardFace] << " of " << suitName[cardSuit] << endl;
}

Comments comming.

DeckOfCards.h

/* 
Author: [Me] 
Date: 14 July 11 
File name: DeckOfCards.h 
Purpose: DeckOfCards class definition
*/

// prevent multiple inclusions of the header file
#ifndef DECKOFCARDS_H
#define DECKOFCARDS_H

// DeckOfCards class definition
class DeckOfCards
{
	public:
		DeckOfCards();
		void shuffleCards();
		void dealCards();
		bool moreCards();
	private:
		int currentCard;
};

#endif

Comments comming.

DeckOfCards.cpp

/* 
Author: [Me]
Date: 14 July 11 
File name: DeckOfCards.cpp 
Purpose: DeckOfCards class member function definitions
*/

#include <iostream>
#include <iomanip>
#include <vector>
#include <ctime>
#include "DeckOfCards.h"
#include "Card.h"

using namespace std;

vector <Card*> deck;

DeckOfCards::DeckOfCards()
{
	currentCard = 0;

	for (int suit = 0; suit < 4; suit++) {
		for (int face = 0; face < 13; face++) {
			Card *currentCardToStore = new Card(face, suit);
			deck.push_back (*currentCardToStore);			
		}
	}
}

void DeckOfCards::shuffleCards()
{
  int randomNumber; 

  srand(time(0)); // introduce a random seed based on the system time
  randomNumber = (1 + rand() % 52); // generate a random number between 1 and 52

  for (int currentCardToSwap = 0; currentCardToSwap < 52; currentCardToSwap++) {
	  swap (deck[currentCardToSwap], deck[randomNumber]);
  }

}

void DeckOfCards::dealCards()
{
	deck[currentCard].toString();
	currentCard++;
}

bool DeckOfCards::moreCards()
{
	if (currentCard < 52) {
		return true;
	}
	else {
		return false;
	}
}