#include <conio.h>
#include <stdio.h>
int main()
{
int a[10];
for(int x=0; x<10; x++)
{
scanf("%d",&a[x]);
}
printf("\n\nODD EVEN\n");
for( int i = 0; i < 10; i++ )
{
if(a[i]%2==0)
{
printf("\t%d\n",a[i]);
}
if(a[i]%2==1)
{
printf("%d",a[i]);
}
}
getch();
}
Binary Tree data structure.
//******************************************************************//
// Demonstration of simple binary tree implementation
//******************************************************************//
#include <iostream>
#include <cstdlib> // For exit()
#include <vector> // For storing characters
#include <iomanip> // For setw(), setfill()
#include <string>
using namespace std;
//******************************************************************//
// Tree class. //
//******************************************************************//
class Tree
{
public:
Tree()
{ root = NULL; }
~Tree()
{ destroySubTree(root); }
void insertNode(char);
bool searchNode(char);
void remove(char);
void displayInOrder() const
{ displayInOrder(root); }
void displayPreOrder() const
{ displayPreOrder(root); }
void displayPostOrder() const
{ displayPostOrder(root); }
void FindExitNode(char item)
{ FindExitNode(root, item); }
void TracePath();
private:
struct TreeNode
{
char item;
TreeNode *left;
TreeNode *right;
};
TreeNode *root;
static int tries;
vector<char> itemPlaceholder;
void insert(TreeNode *&, TreeNode *&);
void destroySubTree(TreeNode *);
void deleteNode(char, TreeNode *&);
void makeDeletion(TreeNode *&);
void displayInOrder(TreeNode *) const;
void displayPreOrder(TreeNode *) const;
void displayPostOrder(TreeNode *) const;
void FindExitNode(TreeNode *, char);
};
// Holds the number of attempts in finding the target character.
int Tree::tries = 0;
//******************************************************************//
// insertNode creates a new node to hold item as its value, and //
// passes it to the insert function. //
//******************************************************************//
void Tree::insertNode(char item)
{
TreeNode *newNode;
newNode = new TreeNode;
newNode->item = item;
newNode->left = newNode->right = NULL;
insert(root, newNode);
}
//******************************************************************//
// insert accepts a TreeNode pointer and a pointer to a node. The //
// function inserts the node into the tree pointed to by the //
// TreeNode pointer. This function is called recursively. //
//******************************************************************//
void Tree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if(nodePtr == NULL)
nodePtr = newNode;
else if(newNode->item < nodePtr->item)
insert(nodePtr->left, newNode);
else
insert(nodePtr->right, newNode);
}
//******************************************************************//
// destroySubTree is called by the destructor. It deletes all nodes //
// in the tree. //
//******************************************************************//
void Tree::destroySubTree(TreeNode *nodePtr)
{
if(nodePtr)
{
if(nodePtr->left)
destroySubTree(nodePtr->left);
if(nodePtr->right)
destroySubTree(nodePtr->right);
delete nodePtr;
}
}
//******************************************************************//
// The displayInOrder member function display the values in the //
// subtree pointed to by nodePtr, via inorder traversal. //
//******************************************************************//
void Tree::displayInOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
displayInOrder(nodePtr->left);
cout << nodePtr->item << endl;
displayInOrder(nodePtr->right);
}
}
//******************************************************************//
// The displayPreOrder member function displays the values in the //
// subtree pointed to by nodePtr, via preorder traversal. //
//******************************************************************//
void Tree::displayPreOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
cout << nodePtr->item << endl;
displayPreOrder(nodePtr->left);
displayPreOrder(nodePtr->right);
}
}
//******************************************************************//
// The displayPostOrder member function displays the values in the //
// subtree pointed to by nodePtr, via postorder traversal. //
//******************************************************************//
void Tree::displayPostOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
displayPostOrder(nodePtr->left);
displayPostOrder(nodePtr->right);
cout << nodePtr->item << endl;
}
}
//******************************************************************//
// searchNode determines whether a value is present in the tree. //
// If so, the function returns true. Otherwise, it returns false. //
//******************************************************************//
bool Tree::searchNode(char item)
{
TreeNode *nodePtr = root;
while(nodePtr)
{
if(nodePtr->item == item)
return true;
else if(item < nodePtr->item)
nodePtr = nodePtr->left;
else
nodePtr = nodePtr->right;
}
return false;
}
//******************************************************************//
// remove calls deleteNode to delete the node whose item member is //
// the same as item. //
//******************************************************************//
void Tree::remove(char item)
{
deleteNode(item, root);
}
//******************************************************************//
// deleteNode deletes the node whose value member is the same as //
// item. //
//******************************************************************//
void Tree::deleteNode(char item, TreeNode *&nodePtr)
{
if(item < nodePtr->item)
deleteNode(item, nodePtr->left);
else if(item > nodePtr->item)
deleteNode(item, nodePtr->right);
else
makeDeletion(nodePtr);
}
//******************************************************************//
// makeDeletion takes a reference to a pointer to the node that is //
// to be deleted. The node is removed and the branches of the tree //
// below the node are reattached. //
//******************************************************************//
void Tree::makeDeletion(TreeNode *&nodePtr)
{
TreeNode *tempNodePtr;
if(nodePtr == NULL)
cout << "Cannot delete an empty node.\n";
else if(nodePtr->right == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->left;
delete tempNodePtr;
}
else if(nodePtr->left == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->right;
delete tempNodePtr;
}
else
{
tempNodePtr = nodePtr->right;
while(tempNodePtr->left)
tempNodePtr = tempNodePtr->left;
tempNodePtr->left = nodePtr->left;
tempNodePtr = nodePtr;
nodePtr = nodePtr->right;
delete tempNodePtr;
}
}
//******************************************************************//
// Function: Traverses the tree based on user selected direction. //
// Compare the current node with the current item. //
// Pre-condition: A valid character item must be in the tree. //
// Post-condition: A printout is sent to the output stream. //
//******************************************************************//
void Tree::FindExitNode(TreeNode *nodePtr, char item)
{
if(nodePtr)
{
itemPlaceholder.push_back(nodePtr->item);
if(nodePtr->item == item)
{
itemPlaceholder.push_back(nodePtr->item);
cout << endl << "Tracing your path..." << endl << endl;
TracePath();
cout << endl << "Congratulations! " << "After " << ++tries;
(tries > 1) ? cout << " tries, " : cout << " try, ";
cout << "you have found the exit to the maze!" << endl;
itemPlaceholder.clear();
exit(EXIT_SUCCESS);
}
cout << "Select turn (left/right): ";
string answer;
getline(cin, answer);
if(answer == "left" || answer == "LEFT" || answer == "l" || answer == "L")
{
itemPlaceholder.push_back('/');
FindExitNode(nodePtr->left, item);
}
else if(answer == "right" || answer == "RIGHT" || answer == "r" || answer == "R")
{
itemPlaceholder.push_back('\\');
FindExitNode(nodePtr->right, item);
}
else
{
cout << endl << "Invalid direction." << endl;
cout << "Going back to the beginning of maze..." << endl << endl;
while(!itemPlaceholder.empty())
itemPlaceholder.pop_back();
}
}
else
{
cout << endl << "Tracing your path..." << endl << endl;
TracePath();
cout << endl << "You've reached a dead end." << endl;
cout << "Going back to the beginning of maze..." << endl << endl;
tries++;
}
}
//******************************************************************//
// Function: Traces the path the player has visited. //
// Post-condition: The visited path is sent to the output stream. //
//******************************************************************//
void Tree::TracePath()
{
int x, currentPosition;
x = currentPosition = 15;
for(unsigned int i=0; i<itemPlaceholder.size()-1; i++)
{
if(itemPlaceholder[i] == '/')
{
currentPosition -= 1;
for(int j=0; j<currentPosition; j++)
cout << " ";
cout << "/" << endl;
x=currentPosition-1;
}
else if(itemPlaceholder[i] == '\\')
{
currentPosition += 1;
for(int j=0; j<currentPosition; j++)
cout << " ";
cout << "\\" << endl;
x=currentPosition+1;
}
else // letter
{
for(int j=0; j<x; j++)
cout << " ";
cout << itemPlaceholder[i] << endl;
currentPosition = x;
}
}
itemPlaceholder.clear();
}
//******************************************************************//
// Show introduction to game. //
//******************************************************************//
void ShowBanner()
{
cout << left << setfill('-') << setw(79) << "-" << endl;
cout << left << setfill(' ') << setw(20) << " ";
cout << "WELCOME TO THE BINARY TREE MAZE GAME!" << endl;
cout << left << setfill('-') << setw(79) << "-" << endl << endl;
}
//******************************************************************//
// Main function //
//******************************************************************//
int main()
{
Tree *tree = new Tree();
// Create the tree structure
tree->insertNode('O');
tree->insertNode('K');
tree->insertNode('W');
tree->insertNode('B');
tree->insertNode('M');
tree->insertNode('S');
tree->insertNode('X');
tree->insertNode('Q');
tree->insertNode('U');
tree->insertNode('Z');
tree->insertNode('R');
tree->insertNode('T');
tree->insertNode('V');
ShowBanner();
// Begin the game
while(true)
{
// Look for character 'R'
tree->FindExitNode('R');
}
return 0;
}
// Demonstration of simple binary tree implementation
//******************************************************************//
#include <iostream>
#include <cstdlib> // For exit()
#include <vector> // For storing characters
#include <iomanip> // For setw(), setfill()
#include <string>
using namespace std;
//******************************************************************//
// Tree class. //
//******************************************************************//
class Tree
{
public:
Tree()
{ root = NULL; }
~Tree()
{ destroySubTree(root); }
void insertNode(char);
bool searchNode(char);
void remove(char);
void displayInOrder() const
{ displayInOrder(root); }
void displayPreOrder() const
{ displayPreOrder(root); }
void displayPostOrder() const
{ displayPostOrder(root); }
void FindExitNode(char item)
{ FindExitNode(root, item); }
void TracePath();
private:
struct TreeNode
{
char item;
TreeNode *left;
TreeNode *right;
};
TreeNode *root;
static int tries;
vector<char> itemPlaceholder;
void insert(TreeNode *&, TreeNode *&);
void destroySubTree(TreeNode *);
void deleteNode(char, TreeNode *&);
void makeDeletion(TreeNode *&);
void displayInOrder(TreeNode *) const;
void displayPreOrder(TreeNode *) const;
void displayPostOrder(TreeNode *) const;
void FindExitNode(TreeNode *, char);
};
// Holds the number of attempts in finding the target character.
int Tree::tries = 0;
//******************************************************************//
// insertNode creates a new node to hold item as its value, and //
// passes it to the insert function. //
//******************************************************************//
void Tree::insertNode(char item)
{
TreeNode *newNode;
newNode = new TreeNode;
newNode->item = item;
newNode->left = newNode->right = NULL;
insert(root, newNode);
}
//******************************************************************//
// insert accepts a TreeNode pointer and a pointer to a node. The //
// function inserts the node into the tree pointed to by the //
// TreeNode pointer. This function is called recursively. //
//******************************************************************//
void Tree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if(nodePtr == NULL)
nodePtr = newNode;
else if(newNode->item < nodePtr->item)
insert(nodePtr->left, newNode);
else
insert(nodePtr->right, newNode);
}
//******************************************************************//
// destroySubTree is called by the destructor. It deletes all nodes //
// in the tree. //
//******************************************************************//
void Tree::destroySubTree(TreeNode *nodePtr)
{
if(nodePtr)
{
if(nodePtr->left)
destroySubTree(nodePtr->left);
if(nodePtr->right)
destroySubTree(nodePtr->right);
delete nodePtr;
}
}
//******************************************************************//
// The displayInOrder member function display the values in the //
// subtree pointed to by nodePtr, via inorder traversal. //
//******************************************************************//
void Tree::displayInOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
displayInOrder(nodePtr->left);
cout << nodePtr->item << endl;
displayInOrder(nodePtr->right);
}
}
//******************************************************************//
// The displayPreOrder member function displays the values in the //
// subtree pointed to by nodePtr, via preorder traversal. //
//******************************************************************//
void Tree::displayPreOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
cout << nodePtr->item << endl;
displayPreOrder(nodePtr->left);
displayPreOrder(nodePtr->right);
}
}
//******************************************************************//
// The displayPostOrder member function displays the values in the //
// subtree pointed to by nodePtr, via postorder traversal. //
//******************************************************************//
void Tree::displayPostOrder(TreeNode *nodePtr) const
{
if(nodePtr)
{
displayPostOrder(nodePtr->left);
displayPostOrder(nodePtr->right);
cout << nodePtr->item << endl;
}
}
//******************************************************************//
// searchNode determines whether a value is present in the tree. //
// If so, the function returns true. Otherwise, it returns false. //
//******************************************************************//
bool Tree::searchNode(char item)
{
TreeNode *nodePtr = root;
while(nodePtr)
{
if(nodePtr->item == item)
return true;
else if(item < nodePtr->item)
nodePtr = nodePtr->left;
else
nodePtr = nodePtr->right;
}
return false;
}
//******************************************************************//
// remove calls deleteNode to delete the node whose item member is //
// the same as item. //
//******************************************************************//
void Tree::remove(char item)
{
deleteNode(item, root);
}
//******************************************************************//
// deleteNode deletes the node whose value member is the same as //
// item. //
//******************************************************************//
void Tree::deleteNode(char item, TreeNode *&nodePtr)
{
if(item < nodePtr->item)
deleteNode(item, nodePtr->left);
else if(item > nodePtr->item)
deleteNode(item, nodePtr->right);
else
makeDeletion(nodePtr);
}
//******************************************************************//
// makeDeletion takes a reference to a pointer to the node that is //
// to be deleted. The node is removed and the branches of the tree //
// below the node are reattached. //
//******************************************************************//
void Tree::makeDeletion(TreeNode *&nodePtr)
{
TreeNode *tempNodePtr;
if(nodePtr == NULL)
cout << "Cannot delete an empty node.\n";
else if(nodePtr->right == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->left;
delete tempNodePtr;
}
else if(nodePtr->left == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->right;
delete tempNodePtr;
}
else
{
tempNodePtr = nodePtr->right;
while(tempNodePtr->left)
tempNodePtr = tempNodePtr->left;
tempNodePtr->left = nodePtr->left;
tempNodePtr = nodePtr;
nodePtr = nodePtr->right;
delete tempNodePtr;
}
}
//******************************************************************//
// Function: Traverses the tree based on user selected direction. //
// Compare the current node with the current item. //
// Pre-condition: A valid character item must be in the tree. //
// Post-condition: A printout is sent to the output stream. //
//******************************************************************//
void Tree::FindExitNode(TreeNode *nodePtr, char item)
{
if(nodePtr)
{
itemPlaceholder.push_back(nodePtr->item);
if(nodePtr->item == item)
{
itemPlaceholder.push_back(nodePtr->item);
cout << endl << "Tracing your path..." << endl << endl;
TracePath();
cout << endl << "Congratulations! " << "After " << ++tries;
(tries > 1) ? cout << " tries, " : cout << " try, ";
cout << "you have found the exit to the maze!" << endl;
itemPlaceholder.clear();
exit(EXIT_SUCCESS);
}
cout << "Select turn (left/right): ";
string answer;
getline(cin, answer);
if(answer == "left" || answer == "LEFT" || answer == "l" || answer == "L")
{
itemPlaceholder.push_back('/');
FindExitNode(nodePtr->left, item);
}
else if(answer == "right" || answer == "RIGHT" || answer == "r" || answer == "R")
{
itemPlaceholder.push_back('\\');
FindExitNode(nodePtr->right, item);
}
else
{
cout << endl << "Invalid direction." << endl;
cout << "Going back to the beginning of maze..." << endl << endl;
while(!itemPlaceholder.empty())
itemPlaceholder.pop_back();
}
}
else
{
cout << endl << "Tracing your path..." << endl << endl;
TracePath();
cout << endl << "You've reached a dead end." << endl;
cout << "Going back to the beginning of maze..." << endl << endl;
tries++;
}
}
//******************************************************************//
// Function: Traces the path the player has visited. //
// Post-condition: The visited path is sent to the output stream. //
//******************************************************************//
void Tree::TracePath()
{
int x, currentPosition;
x = currentPosition = 15;
for(unsigned int i=0; i<itemPlaceholder.size()-1; i++)
{
if(itemPlaceholder[i] == '/')
{
currentPosition -= 1;
for(int j=0; j<currentPosition; j++)
cout << " ";
cout << "/" << endl;
x=currentPosition-1;
}
else if(itemPlaceholder[i] == '\\')
{
currentPosition += 1;
for(int j=0; j<currentPosition; j++)
cout << " ";
cout << "\\" << endl;
x=currentPosition+1;
}
else // letter
{
for(int j=0; j<x; j++)
cout << " ";
cout << itemPlaceholder[i] << endl;
currentPosition = x;
}
}
itemPlaceholder.clear();
}
//******************************************************************//
// Show introduction to game. //
//******************************************************************//
void ShowBanner()
{
cout << left << setfill('-') << setw(79) << "-" << endl;
cout << left << setfill(' ') << setw(20) << " ";
cout << "WELCOME TO THE BINARY TREE MAZE GAME!" << endl;
cout << left << setfill('-') << setw(79) << "-" << endl << endl;
}
//******************************************************************//
// Main function //
//******************************************************************//
int main()
{
Tree *tree = new Tree();
// Create the tree structure
tree->insertNode('O');
tree->insertNode('K');
tree->insertNode('W');
tree->insertNode('B');
tree->insertNode('M');
tree->insertNode('S');
tree->insertNode('X');
tree->insertNode('Q');
tree->insertNode('U');
tree->insertNode('Z');
tree->insertNode('R');
tree->insertNode('T');
tree->insertNode('V');
ShowBanner();
// Begin the game
while(true)
{
// Look for character 'R'
tree->FindExitNode('R');
}
return 0;
}
PASCAL'S TRIANGLE
#include <iostream>
using namespace std;
//functions
int myTriangle();
int tryAgain();
//end of functions
//global variables
int pascalH = 0;
//end of global variables
int main()
{
cout << "\t***Please do not enter very large number***\n\n";
cout << "\t Enter the desired height of triangle: ";
cin >> pascalH;
fflush(stdin);
myTriangle();
tryAgain();
cout << endl;
return 0;
}
int myTriangle()
{
int space = pascalH - 1;
cout << "\n\n\n";
for (int ctr = 0; ctr < pascalH; ctr++)
{
int topH = 1;
for (int z = 0; z <= space; z++)
{
cout << " ";
}
space--;
//cout.width(pascalH - ctr); //another method for space
for(int a = 0; a <=ctr; a++)
{
cout << topH << " ";
topH = topH * ( ctr - a) / ( a + 1);
}
cout << "\n";
}
cout << "\n";
return 0;
}
int tryAgain()
{
string answer[4] = {"Y", "y", "N", "n"};
string decision;
cout << "\n\nTry Again? [y/n]:";
cin >> decision;
fflush(stdin);
if (decision == answer[0] || decision == answer[1])
{
system("CLS");
main();
}
if (decision == answer[2] || decision == answer[3])
{
//window close
}
return 0;
}
using namespace std;
//functions
int myTriangle();
int tryAgain();
//end of functions
//global variables
int pascalH = 0;
//end of global variables
int main()
{
cout << "\t***Please do not enter very large number***\n\n";
cout << "\t Enter the desired height of triangle: ";
cin >> pascalH;
fflush(stdin);
myTriangle();
tryAgain();
cout << endl;
return 0;
}
int myTriangle()
{
int space = pascalH - 1;
cout << "\n\n\n";
for (int ctr = 0; ctr < pascalH; ctr++)
{
int topH = 1;
for (int z = 0; z <= space; z++)
{
cout << " ";
}
space--;
//cout.width(pascalH - ctr); //another method for space
for(int a = 0; a <=ctr; a++)
{
cout << topH << " ";
topH = topH * ( ctr - a) / ( a + 1);
}
cout << "\n";
}
cout << "\n";
return 0;
}
int tryAgain()
{
string answer[4] = {"Y", "y", "N", "n"};
string decision;
cout << "\n\nTry Again? [y/n]:";
cin >> decision;
fflush(stdin);
if (decision == answer[0] || decision == answer[1])
{
system("CLS");
main();
}
if (decision == answer[2] || decision == answer[3])
{
//window close
}
return 0;
}
SIMPLE HANGMAC [C++]
#include <iostream>
#include <string>
using namespace std;
void printHangMac(int);
void main()
{
string toBeGuessed, guess;
int i, numErrors = 0;
cout << "\n\nEnter the string to be guessed: ";
fflush(stdin); //used to clear the buffer
getline(cin, toBeGuessed);
system("cls");
string asterisks(toBeGuessed.length(), '*'); //replace all characters with asterisks
for(i = 0 ; i < toBeGuessed.length() ; i++)
{
if(toBeGuessed.at(i)==' ')
{
asterisks.replace(i, 1, " "); //replace spaces
}
}
do
{
cout << endl << asterisks;
cout << "\n\nGive me a letter: ";
fflush(stdin);
getline(cin, guess);
for(i = 0 ; i < toBeGuessed.length() ; i++)
{
if(toBeGuessed.at(i)==guess.at(0))
{
asterisks.replace(i, 1, guess); //if found
}
}
if( toBeGuessed.find(guess, 0)==-1 )
{
numErrors++;
printHangMac(numErrors);
}
} while(numErrors < 6 && (asterisks.find("*",0) != -1) );
if(numErrors == 6)
{
cout << "\n\nLoser. Moron. Game ovah.";
}
else
{
cout << "\n\nWinnder. Not a moron.";
}
cout << endl << endl;
}
void printHangMac(int errors)
{
string mac[6];
mac[0] = " O\n";
mac[1] = " /";
mac[2] = "|";
mac[3] = "\\\n";
mac[4] = " /";
mac[5] = " \\\n";
for(int j = 0 ; j < errors ; j++ )
{
cout << mac[j];
}
cout << endl;
}
#include <string>
using namespace std;
void printHangMac(int);
void main()
{
string toBeGuessed, guess;
int i, numErrors = 0;
cout << "\n\nEnter the string to be guessed: ";
fflush(stdin); //used to clear the buffer
getline(cin, toBeGuessed);
system("cls");
string asterisks(toBeGuessed.length(), '*'); //replace all characters with asterisks
for(i = 0 ; i < toBeGuessed.length() ; i++)
{
if(toBeGuessed.at(i)==' ')
{
asterisks.replace(i, 1, " "); //replace spaces
}
}
do
{
cout << endl << asterisks;
cout << "\n\nGive me a letter: ";
fflush(stdin);
getline(cin, guess);
for(i = 0 ; i < toBeGuessed.length() ; i++)
{
if(toBeGuessed.at(i)==guess.at(0))
{
asterisks.replace(i, 1, guess); //if found
}
}
if( toBeGuessed.find(guess, 0)==-1 )
{
numErrors++;
printHangMac(numErrors);
}
} while(numErrors < 6 && (asterisks.find("*",0) != -1) );
if(numErrors == 6)
{
cout << "\n\nLoser. Moron. Game ovah.";
}
else
{
cout << "\n\nWinnder. Not a moron.";
}
cout << endl << endl;
}
void printHangMac(int errors)
{
string mac[6];
mac[0] = " O\n";
mac[1] = " /";
mac[2] = "|";
mac[3] = "\\\n";
mac[4] = " /";
mac[5] = " \\\n";
for(int j = 0 ; j < errors ; j++ )
{
cout << mac[j];
}
cout << endl;
}
BlackJack Game
/////////////////////////////////////////////////////////////////////////////
// This is a simple Blackjack (21) game simulator. //
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
const unsigned int MAX_HAND_CARDS = 10;
const unsigned int MAX_DECK_CARDS = 52;
/////////////////////////////////////////////////////////////////////////////
// This is the Card Class which represents each card in the game. //
/////////////////////////////////////////////////////////////////////////////
class Card {
public:
enum rank { ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING };
// ASCII code of each card
enum suit { HEARTS = 3, DIAMONDS, CLUBS, SPADES };
friend ostream& operator<< (ostream& os, const Card aCard);
Card(rank r = ACE, suit s = SPADES, bool cardfaceup = true);
~Card();
unsigned int GetCardValue() const;
void FlipCard();
bool GetFace();
private:
rank cardRank;
suit cardSuit;
bool cardIsFaceUp;
};
// Card class constructor
Card::Card(rank r, suit s, bool cardFaceUp): cardRank(r), cardSuit(s), cardIsFaceUp(cardFaceUp)
{}
Card::~Card()
{}
// Returns the real value of card if greater than 10
unsigned int Card::GetCardValue() const
{
int cardValue = 0;
if (cardIsFaceUp)
{
cardValue = cardRank;
if (cardValue > 10)
cardValue = 10;
}
return cardValue;
}
// For hiding the the first card of dealer
void Card::FlipCard()
{
cardIsFaceUp = !cardIsFaceUp;
}
// Check if the card is facing up
bool Card::GetFace()
{
return cardIsFaceUp;
}
/////////////////////////////////////////////////////////////////////////////
// This is the Deck Class which represents a deck of cards. //
// Each deck in the game can have up to 52 cards maximum. //
/////////////////////////////////////////////////////////////////////////////
class Deck {
public:
Deck(unsigned int dPos = 0);
~Deck();
void ClearDeck();
void PopulateDeck();
void ShuffleDeck();
bool DeckIsEmpty();
void AddCardToDeck(Card pCard);
unsigned int CurrentPosition();
Card GiveCardToPlayer();
private:
unsigned int deckCurrentPos;
Card deckCards[MAX_DECK_CARDS];
};
// Deck class constructor
Deck::Deck(unsigned int dPos) : deckCurrentPos(dPos)
{
ClearDeck();
PopulateDeck();
ShuffleDeck();
}
// Empty destructor
Deck::~Deck()
{}
// Current position in the array
unsigned int Deck::CurrentPosition()
{
return deckCurrentPos;
}
// Reset position of array
void Deck::ClearDeck()
{
deckCurrentPos = 0;
}
// Create an array of Card objects
void Deck::PopulateDeck()
{
for (int s = Card::HEARTS; s <= Card::SPADES; s++)
{
for (int r = Card::ACE; r <= Card::KING; r++)
{
AddCardToDeck(Card(static_cast<Card::rank>(r),
static_cast<Card::suit>(s)));
}
}
}
// Shuffle the array of cards
void Deck::ShuffleDeck()
{
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < (MAX_DECK_CARDS - 1); i++)
{
int r = i + (rand() % (MAX_DECK_CARDS - i));
Card tempCard = deckCards[i];
deckCards[i] = deckCards[r];
deckCards[r] = tempCard;
}
}
// Check if we have an empty deck
bool Deck::DeckIsEmpty()
{
return (deckCurrentPos <= 0);
}
// Helper function to PopulateDeck()
void Deck::AddCardToDeck(Card pCard)
{
deckCards[deckCurrentPos++] = pCard;
}
// Start dealing cards from the last index
Card Deck::GiveCardToPlayer()
{
if (!DeckIsEmpty())
return deckCards[--deckCurrentPos];
else
{
// If cards ran out, we simply
// re-shuffle the deck
deckCurrentPos = MAX_DECK_CARDS;
ShuffleDeck();
return deckCards[--deckCurrentPos];
}
}
/////////////////////////////////////////////////////////////////////////////
// This is the Hand Class which represents a hand of cards. //
// Each hand in the game can have up to 10 cards maximum. //
/////////////////////////////////////////////////////////////////////////////
class Hand {
public:
Hand(unsigned int hPos = 0, unsigned int pPos = 0);
~Hand();
void ClearHand();
void FlipFirstCard();
bool HandIsEmpty();
bool HandIsFull();
Card RetrieveCard();
void AddCardToHand(Card handCard);
unsigned int GetHandTotal() const;
unsigned int GetHandLastPosition() const;
private:
unsigned int handCurrentPos;
unsigned int playerCardPos;
Card handCards[MAX_HAND_CARDS];
};
// Hand class constructor
Hand::Hand(unsigned int hPos, unsigned int pPos) : handCurrentPos(hPos), playerCardPos(pPos)
{ }
// Empty Hand class destructor
Hand::~Hand()
{}
// Reset hand
void Hand::ClearHand()
{
playerCardPos = handCurrentPos = 0;
}
// Flip dealer's first card
void Hand::FlipFirstCard()
{
handCards[0].FlipCard();
}
// Check if we have an empty hand
bool Hand::HandIsEmpty()
{
return (handCurrentPos < 0);
}
// Check if we have a full hand
bool Hand::HandIsFull()
{
return (handCurrentPos >= MAX_HAND_CARDS);
}
// Retrieve a card from hand
Card Hand::RetrieveCard()
{
return handCards[playerCardPos++];
}
// Add a card from deck to hand
void Hand::AddCardToHand(Card handCard)
{
if (!HandIsFull())
{
handCards[handCurrentPos++] = handCard;
}
}
// Get hand total value
unsigned int Hand::GetHandTotal() const
{
if (handCards[0].GetCardValue() == 0)
return 0;
int total = 0;
// Start from top most card
for (int i = GetHandLastPosition(); i >= 0; i--)
{
total += handCards[i].GetCardValue();
}
// Check if we have an Ace
bool cardHasAce = false;
for (int i = GetHandLastPosition(); i >= 0; i--)
{
if (handCards[i].GetCardValue() == Card::ACE)
cardHasAce = true;
}
// If we have an ace and our total is <= 11
// then we make the ace equal to 11
if (cardHasAce && total <= 11)
total += 10;
return total;
}
// Get the hand's last position
unsigned int Hand::GetHandLastPosition() const
{
return handCurrentPos - 1;
}
/////////////////////////////////////////////////////////////////////////////
// This is the Player Class which represents a player of the game. //
/////////////////////////////////////////////////////////////////////////////
class Player {
public:
friend ostream& operator<< (ostream& os, const Player aPlayer);
Player(const string playerName);
Player();
~Player();
void Clear();
string GetPlayerName() const;
void SetPlayerName(string name);
bool IsEmpty();
bool IsHitting() const;
void FlipDealerFirstCard();
void ReceiveCard(Card playerCard);
bool IsBusted() const;
unsigned int GetCardTotal() const;
unsigned int GetPosition() const;
private:
string playerName;
Card playerCard;
Hand playerHand;
};
// Player class constructor
Player::Player(const string pName) : playerName(pName)
{}
// Set default name for player
Player::Player()
{
playerName = "Dealer";
}
// Empty Player class destructor
Player::~Player()
{}
// Get player's name
// Can be used in multi-player game
string Player::GetPlayerName() const
{
return playerName;
}
// Set player's name
void Player::SetPlayerName(string name)
{
playerName = name;
}
// Check if player's hand has no card
bool Player::IsEmpty()
{
return playerHand.HandIsEmpty();
}
// Reset player's hand
void Player::Clear()
{
playerHand.ClearHand();
}
// Check if the player or dealer is still
// asking for additional cards
// In the dealer's case, if the card value
// is <= 16 then we continue giving additional
// cards
bool Player::IsHitting() const
{
if (playerName != "Dealer")
{
cout << endl << playerName << ", do you want to hit? (y/n): ";
char response;
cin >> response;
return (response == 'y' || response == 'Y');
}
else
{
return (playerHand.GetHandTotal() <= 16);
}
}
// Flip dealer's first card
void Player::FlipDealerFirstCard()
{
if (!(playerHand.HandIsEmpty()))
playerHand.FlipFirstCard();
}
// Add a new card to player's hand
void Player::ReceiveCard(Card playerCard)
{
playerHand.AddCardToHand(playerCard);
}
// Check if player or dealer is busted
bool Player::IsBusted() const
{
return (playerHand.GetHandTotal() > 21);
}
// Get hand total
unsigned int Player::GetCardTotal() const
{
return playerHand.GetHandTotal();
}
// Get the player's hand's last position
unsigned int Player::GetPosition() const
{
return playerHand.GetHandLastPosition();
}
/////////////////////////////////////////////////////////////////////////////
// This is the Game Class which represents the game itself. //
/////////////////////////////////////////////////////////////////////////////
class Game {
public:
Game(string s);
~Game();
void Play();
void ShowTable();
void AnnounceWinner();
void IfDeckIsEmpty();
void ClearGame();
private:
string name;
Deck *gameDeck;
Player dealer;
Player player1;
};
// Game class constructor
// string can be set up as an array of string
// for use with multiple players
Game::Game(string s) : name(s)
{
gameDeck = new Deck(0);
player1.SetPlayerName(name);
}
// Game destructor
Game::~Game()
{
delete gameDeck;
}
// The blackjack game logic
void Game::Play()
{
// Always check if we have an empty deck
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
else
{
// Deal 2 cards initially
for (int i = 0; i < 2; i++)
{
player1.ReceiveCard(gameDeck->GiveCardToPlayer());
dealer.ReceiveCard(gameDeck->GiveCardToPlayer());
}
// Hide dealer's first card
dealer.FlipDealerFirstCard();
// Display everyone's cards
ShowTable();
}
// Get more cards from deck
while (!player1.IsBusted() && player1.IsHitting())
{
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
else
{
player1.ReceiveCard(gameDeck->GiveCardToPlayer());
ShowTable();
}
}
// Show dealer's first card
dealer.FlipDealerFirstCard();
// Dealer's turn to hit
while (!dealer.IsBusted() && dealer.IsHitting())
{
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
dealer.ReceiveCard(gameDeck->GiveCardToPlayer());
}
// Show the cards and announce the winner
if (!gameDeck->DeckIsEmpty())
{
ShowTable();
AnnounceWinner();
ClearGame();
}
}
// Show the players and cards
void Game::ShowTable()
{
cout << string(50, '\n');
cout << "\tWelcome to Simple Casino's BlackJack Game!" << endl << endl;
cout << left << setw(10) << dealer.GetPlayerName() << dealer << endl;
cout << left << setw(10) << player1.GetPlayerName() << player1 << endl;
}
// Who won the game?
void Game::AnnounceWinner()
{
cout << endl;
if (player1.GetCardTotal() > 21)
cout << player1.GetPlayerName() << " busts, Dealer Wins." << endl;
else if (dealer.GetCardTotal() > 21)
cout << dealer.GetPlayerName() << " busts, " << player1.GetPlayerName() << " Wins!" << endl;
else if (player1.GetCardTotal() == 21)
cout << player1.GetPlayerName() << " hit a BlackJack, " << player1.GetPlayerName() << " Wins!" << endl;
else if (dealer.GetCardTotal() == 21)
cout << dealer.GetPlayerName() << " hit a BlackJack, " << player1.GetPlayerName() << " lose." << endl;
else if (player1.GetCardTotal() > dealer.GetCardTotal())
cout << player1.GetPlayerName() << " Wins!" << endl;
else if (dealer.GetCardTotal() > player1.GetCardTotal())
cout << dealer.GetPlayerName() << " Wins." << endl;
else
cout << "It's a tie!" << endl;
}
// This is what we do if we have an empty deck
// Just create a new deck object
void Game::IfDeckIsEmpty()
{
delete gameDeck;
gameDeck = new Deck(0);
}
// Reset the game
void Game::ClearGame()
{
dealer.Clear();
player1.Clear();
}
/////////////////////////////////////////////////////////////////////////////
// Client Program //
/////////////////////////////////////////////////////////////////////////////
// Set the function prototype for the overloaded << operator
ostream& operator<< (ostream& os, const Card aCard);
ostream& operator<< (ostream& os, const Player aPlayer);
int main()
{
string name;
char ans = 'y';
cout << "Enter your name: ";
cin >> name;
Game *aGame = new Game(name);
while (ans == 'y' || ans == 'Y')
{
aGame->Play();
cout << "\nPlay Again? (y/n): ";
cin >> ans;
}
delete aGame;
return 0;
}
// Overloaded << operator for use with the Card object
ostream& operator<< (ostream& os, const Card aCard)
{
const string RANKS[] = {"0", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K"};
if (aCard.cardIsFaceUp)
{
os << RANKS[aCard.cardRank] << (char) aCard.cardSuit << "\t";
}
else
{
// Hide card
os << "XX" << "\t";
}
return os;
}
// Overloaded << operator for use with the Player object
ostream& operator<< (ostream& os, Player aPlayer)
{
if (!aPlayer.IsEmpty())
{
for (int i = aPlayer.playerHand.GetHandLastPosition(); i >= 0; i--)
os << aPlayer.playerHand.RetrieveCard();
if (aPlayer.GetCardTotal() != 0)
cout << "[" << aPlayer.GetCardTotal() << "]";
}
else
{
os << "Error: Empty Hand";
}
return os;
}
// This is a simple Blackjack (21) game simulator. //
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
const unsigned int MAX_HAND_CARDS = 10;
const unsigned int MAX_DECK_CARDS = 52;
/////////////////////////////////////////////////////////////////////////////
// This is the Card Class which represents each card in the game. //
/////////////////////////////////////////////////////////////////////////////
class Card {
public:
enum rank { ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING };
// ASCII code of each card
enum suit { HEARTS = 3, DIAMONDS, CLUBS, SPADES };
friend ostream& operator<< (ostream& os, const Card aCard);
Card(rank r = ACE, suit s = SPADES, bool cardfaceup = true);
~Card();
unsigned int GetCardValue() const;
void FlipCard();
bool GetFace();
private:
rank cardRank;
suit cardSuit;
bool cardIsFaceUp;
};
// Card class constructor
Card::Card(rank r, suit s, bool cardFaceUp): cardRank(r), cardSuit(s), cardIsFaceUp(cardFaceUp)
{}
Card::~Card()
{}
// Returns the real value of card if greater than 10
unsigned int Card::GetCardValue() const
{
int cardValue = 0;
if (cardIsFaceUp)
{
cardValue = cardRank;
if (cardValue > 10)
cardValue = 10;
}
return cardValue;
}
// For hiding the the first card of dealer
void Card::FlipCard()
{
cardIsFaceUp = !cardIsFaceUp;
}
// Check if the card is facing up
bool Card::GetFace()
{
return cardIsFaceUp;
}
/////////////////////////////////////////////////////////////////////////////
// This is the Deck Class which represents a deck of cards. //
// Each deck in the game can have up to 52 cards maximum. //
/////////////////////////////////////////////////////////////////////////////
class Deck {
public:
Deck(unsigned int dPos = 0);
~Deck();
void ClearDeck();
void PopulateDeck();
void ShuffleDeck();
bool DeckIsEmpty();
void AddCardToDeck(Card pCard);
unsigned int CurrentPosition();
Card GiveCardToPlayer();
private:
unsigned int deckCurrentPos;
Card deckCards[MAX_DECK_CARDS];
};
// Deck class constructor
Deck::Deck(unsigned int dPos) : deckCurrentPos(dPos)
{
ClearDeck();
PopulateDeck();
ShuffleDeck();
}
// Empty destructor
Deck::~Deck()
{}
// Current position in the array
unsigned int Deck::CurrentPosition()
{
return deckCurrentPos;
}
// Reset position of array
void Deck::ClearDeck()
{
deckCurrentPos = 0;
}
// Create an array of Card objects
void Deck::PopulateDeck()
{
for (int s = Card::HEARTS; s <= Card::SPADES; s++)
{
for (int r = Card::ACE; r <= Card::KING; r++)
{
AddCardToDeck(Card(static_cast<Card::rank>(r),
static_cast<Card::suit>(s)));
}
}
}
// Shuffle the array of cards
void Deck::ShuffleDeck()
{
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < (MAX_DECK_CARDS - 1); i++)
{
int r = i + (rand() % (MAX_DECK_CARDS - i));
Card tempCard = deckCards[i];
deckCards[i] = deckCards[r];
deckCards[r] = tempCard;
}
}
// Check if we have an empty deck
bool Deck::DeckIsEmpty()
{
return (deckCurrentPos <= 0);
}
// Helper function to PopulateDeck()
void Deck::AddCardToDeck(Card pCard)
{
deckCards[deckCurrentPos++] = pCard;
}
// Start dealing cards from the last index
Card Deck::GiveCardToPlayer()
{
if (!DeckIsEmpty())
return deckCards[--deckCurrentPos];
else
{
// If cards ran out, we simply
// re-shuffle the deck
deckCurrentPos = MAX_DECK_CARDS;
ShuffleDeck();
return deckCards[--deckCurrentPos];
}
}
/////////////////////////////////////////////////////////////////////////////
// This is the Hand Class which represents a hand of cards. //
// Each hand in the game can have up to 10 cards maximum. //
/////////////////////////////////////////////////////////////////////////////
class Hand {
public:
Hand(unsigned int hPos = 0, unsigned int pPos = 0);
~Hand();
void ClearHand();
void FlipFirstCard();
bool HandIsEmpty();
bool HandIsFull();
Card RetrieveCard();
void AddCardToHand(Card handCard);
unsigned int GetHandTotal() const;
unsigned int GetHandLastPosition() const;
private:
unsigned int handCurrentPos;
unsigned int playerCardPos;
Card handCards[MAX_HAND_CARDS];
};
// Hand class constructor
Hand::Hand(unsigned int hPos, unsigned int pPos) : handCurrentPos(hPos), playerCardPos(pPos)
{ }
// Empty Hand class destructor
Hand::~Hand()
{}
// Reset hand
void Hand::ClearHand()
{
playerCardPos = handCurrentPos = 0;
}
// Flip dealer's first card
void Hand::FlipFirstCard()
{
handCards[0].FlipCard();
}
// Check if we have an empty hand
bool Hand::HandIsEmpty()
{
return (handCurrentPos < 0);
}
// Check if we have a full hand
bool Hand::HandIsFull()
{
return (handCurrentPos >= MAX_HAND_CARDS);
}
// Retrieve a card from hand
Card Hand::RetrieveCard()
{
return handCards[playerCardPos++];
}
// Add a card from deck to hand
void Hand::AddCardToHand(Card handCard)
{
if (!HandIsFull())
{
handCards[handCurrentPos++] = handCard;
}
}
// Get hand total value
unsigned int Hand::GetHandTotal() const
{
if (handCards[0].GetCardValue() == 0)
return 0;
int total = 0;
// Start from top most card
for (int i = GetHandLastPosition(); i >= 0; i--)
{
total += handCards[i].GetCardValue();
}
// Check if we have an Ace
bool cardHasAce = false;
for (int i = GetHandLastPosition(); i >= 0; i--)
{
if (handCards[i].GetCardValue() == Card::ACE)
cardHasAce = true;
}
// If we have an ace and our total is <= 11
// then we make the ace equal to 11
if (cardHasAce && total <= 11)
total += 10;
return total;
}
// Get the hand's last position
unsigned int Hand::GetHandLastPosition() const
{
return handCurrentPos - 1;
}
/////////////////////////////////////////////////////////////////////////////
// This is the Player Class which represents a player of the game. //
/////////////////////////////////////////////////////////////////////////////
class Player {
public:
friend ostream& operator<< (ostream& os, const Player aPlayer);
Player(const string playerName);
Player();
~Player();
void Clear();
string GetPlayerName() const;
void SetPlayerName(string name);
bool IsEmpty();
bool IsHitting() const;
void FlipDealerFirstCard();
void ReceiveCard(Card playerCard);
bool IsBusted() const;
unsigned int GetCardTotal() const;
unsigned int GetPosition() const;
private:
string playerName;
Card playerCard;
Hand playerHand;
};
// Player class constructor
Player::Player(const string pName) : playerName(pName)
{}
// Set default name for player
Player::Player()
{
playerName = "Dealer";
}
// Empty Player class destructor
Player::~Player()
{}
// Get player's name
// Can be used in multi-player game
string Player::GetPlayerName() const
{
return playerName;
}
// Set player's name
void Player::SetPlayerName(string name)
{
playerName = name;
}
// Check if player's hand has no card
bool Player::IsEmpty()
{
return playerHand.HandIsEmpty();
}
// Reset player's hand
void Player::Clear()
{
playerHand.ClearHand();
}
// Check if the player or dealer is still
// asking for additional cards
// In the dealer's case, if the card value
// is <= 16 then we continue giving additional
// cards
bool Player::IsHitting() const
{
if (playerName != "Dealer")
{
cout << endl << playerName << ", do you want to hit? (y/n): ";
char response;
cin >> response;
return (response == 'y' || response == 'Y');
}
else
{
return (playerHand.GetHandTotal() <= 16);
}
}
// Flip dealer's first card
void Player::FlipDealerFirstCard()
{
if (!(playerHand.HandIsEmpty()))
playerHand.FlipFirstCard();
}
// Add a new card to player's hand
void Player::ReceiveCard(Card playerCard)
{
playerHand.AddCardToHand(playerCard);
}
// Check if player or dealer is busted
bool Player::IsBusted() const
{
return (playerHand.GetHandTotal() > 21);
}
// Get hand total
unsigned int Player::GetCardTotal() const
{
return playerHand.GetHandTotal();
}
// Get the player's hand's last position
unsigned int Player::GetPosition() const
{
return playerHand.GetHandLastPosition();
}
/////////////////////////////////////////////////////////////////////////////
// This is the Game Class which represents the game itself. //
/////////////////////////////////////////////////////////////////////////////
class Game {
public:
Game(string s);
~Game();
void Play();
void ShowTable();
void AnnounceWinner();
void IfDeckIsEmpty();
void ClearGame();
private:
string name;
Deck *gameDeck;
Player dealer;
Player player1;
};
// Game class constructor
// string can be set up as an array of string
// for use with multiple players
Game::Game(string s) : name(s)
{
gameDeck = new Deck(0);
player1.SetPlayerName(name);
}
// Game destructor
Game::~Game()
{
delete gameDeck;
}
// The blackjack game logic
void Game::Play()
{
// Always check if we have an empty deck
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
else
{
// Deal 2 cards initially
for (int i = 0; i < 2; i++)
{
player1.ReceiveCard(gameDeck->GiveCardToPlayer());
dealer.ReceiveCard(gameDeck->GiveCardToPlayer());
}
// Hide dealer's first card
dealer.FlipDealerFirstCard();
// Display everyone's cards
ShowTable();
}
// Get more cards from deck
while (!player1.IsBusted() && player1.IsHitting())
{
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
else
{
player1.ReceiveCard(gameDeck->GiveCardToPlayer());
ShowTable();
}
}
// Show dealer's first card
dealer.FlipDealerFirstCard();
// Dealer's turn to hit
while (!dealer.IsBusted() && dealer.IsHitting())
{
if (gameDeck->DeckIsEmpty())
{
IfDeckIsEmpty();
}
dealer.ReceiveCard(gameDeck->GiveCardToPlayer());
}
// Show the cards and announce the winner
if (!gameDeck->DeckIsEmpty())
{
ShowTable();
AnnounceWinner();
ClearGame();
}
}
// Show the players and cards
void Game::ShowTable()
{
cout << string(50, '\n');
cout << "\tWelcome to Simple Casino's BlackJack Game!" << endl << endl;
cout << left << setw(10) << dealer.GetPlayerName() << dealer << endl;
cout << left << setw(10) << player1.GetPlayerName() << player1 << endl;
}
// Who won the game?
void Game::AnnounceWinner()
{
cout << endl;
if (player1.GetCardTotal() > 21)
cout << player1.GetPlayerName() << " busts, Dealer Wins." << endl;
else if (dealer.GetCardTotal() > 21)
cout << dealer.GetPlayerName() << " busts, " << player1.GetPlayerName() << " Wins!" << endl;
else if (player1.GetCardTotal() == 21)
cout << player1.GetPlayerName() << " hit a BlackJack, " << player1.GetPlayerName() << " Wins!" << endl;
else if (dealer.GetCardTotal() == 21)
cout << dealer.GetPlayerName() << " hit a BlackJack, " << player1.GetPlayerName() << " lose." << endl;
else if (player1.GetCardTotal() > dealer.GetCardTotal())
cout << player1.GetPlayerName() << " Wins!" << endl;
else if (dealer.GetCardTotal() > player1.GetCardTotal())
cout << dealer.GetPlayerName() << " Wins." << endl;
else
cout << "It's a tie!" << endl;
}
// This is what we do if we have an empty deck
// Just create a new deck object
void Game::IfDeckIsEmpty()
{
delete gameDeck;
gameDeck = new Deck(0);
}
// Reset the game
void Game::ClearGame()
{
dealer.Clear();
player1.Clear();
}
/////////////////////////////////////////////////////////////////////////////
// Client Program //
/////////////////////////////////////////////////////////////////////////////
// Set the function prototype for the overloaded << operator
ostream& operator<< (ostream& os, const Card aCard);
ostream& operator<< (ostream& os, const Player aPlayer);
int main()
{
string name;
char ans = 'y';
cout << "Enter your name: ";
cin >> name;
Game *aGame = new Game(name);
while (ans == 'y' || ans == 'Y')
{
aGame->Play();
cout << "\nPlay Again? (y/n): ";
cin >> ans;
}
delete aGame;
return 0;
}
// Overloaded << operator for use with the Card object
ostream& operator<< (ostream& os, const Card aCard)
{
const string RANKS[] = {"0", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K"};
if (aCard.cardIsFaceUp)
{
os << RANKS[aCard.cardRank] << (char) aCard.cardSuit << "\t";
}
else
{
// Hide card
os << "XX" << "\t";
}
return os;
}
// Overloaded << operator for use with the Player object
ostream& operator<< (ostream& os, Player aPlayer)
{
if (!aPlayer.IsEmpty())
{
for (int i = aPlayer.playerHand.GetHandLastPosition(); i >= 0; i--)
os << aPlayer.playerHand.RetrieveCard();
if (aPlayer.GetCardTotal() != 0)
cout << "[" << aPlayer.GetCardTotal() << "]";
}
else
{
os << "Error: Empty Hand";
}
return os;
}
TICTACTOE Game [C++]
#include<iostream.h>
#include<stdlib.h>
//ANG LIBRARY NA STDLIB.H EH PINAPAGANA UNG SYSTEM("CLS")
// ANG SYSTEM("CLS") EH PANGCLEAR SCREEN
//TAWAG DITO MGA FUNCTION HEADER. NOT SURE. LOLZ
void gamePlay();
void resetGame();
void playerOne();
void playerTwo();
void ticTac();
void ticTacEx();
void ticTacExOne();
void tryAgain();
void howtoPlay();
void contGame();
void contGameEx();
void displayScreen();
int gameWin(int& check);
char array[]={'1','2','3','4','5','6','7','8','9'};
void main() //MAIN FUNTION NATIN TOH.
{
displayScreen(); //TINATAWAG NI MAIN SI DISPLAYSCREEN
}
void gamePlay() //PAPASOK SI DISPLAYSCREEN DITO PAG '1' ANG ININPUT NG USER
{
int check, plyrA=0, plyrB=0, numGames, sum=0, again=0;
cout<<"\t\t\t Number Of Games You Want: ";
//MAY MALI DITO D KO MAGAWAN NG PARAAN.
cin>>numGames;
system("cls");
if (numGames<=0)
{
cout<<"\t\t\t\t Invalid Input"<<endl;
gamePlay();
}
system("cls");
ticTac(); //TATAWAGIN NI GAMEPLAY SI TICTAC
//BABALIK DITO SI TICTAC PAGKATAPOS MAPRINT YUNG BOX
while(sum!=numGames)
{
int ctr=0;
int tie=0;
//BAKIT YUNG TIE EH 9? KASI LAST MOVE YUN
//KASI DIBA PAG LAST MOVE NA SA TICTACTOE AUTOMATIC TIE NA SILA
while(ctr!=1 && tie!=9)
{
playerOne();//TATAWAGIN NI GAMEPLAY SI PLAYERONE
ctr=gameWin(check); //PUPUNTA SIYA KAY GAMEWIN(CHECK) AT MALALAGAY KAY CTR
//KAPAG YUNG CONDITION KAY GAMEWIN EH MAY TUMAMA,
//PAPASOK SIYA DITO SA IF STATEMENT NA UNA
if (ctr==1)
{
system("cls");
cout<<endl;
cout<<"\t\t\t\tPlayer One Wins The Game!"<<endl<<endl;
plyrA++;
//ETO UNG CONDITION PAG NANALO YUNG PLAYER
//PARANG NUMBRE OF WINS TOH
resetGame();
//ITONG RESETGAME EH PAG MAY NANALO LANG
//BALE MAALIS YUNG LETTER X OR LEETER O
//BABALIK ULIT SA MGA CHOICES NA NUMBERS
ticTac();
continue;
}
tie++;
//KAPAG UMABOT SILA NG HANGGANG 9 MOVES, EDI TIE SILA. LOLZ
if(tie==9)
{
system("cls");
cout<<endl;
cout<<"\t\t\t\t\tA Tie!"<<endl;
resetGame();
ticTac();
continue;
}
playerTwo(); //PAREHO LANG KAY PLAYER ONE
ctr=gameWin(check);
if (ctr==1)
{
system("cls");
cout<<endl;
cout<<" Player Two Wins The Game!"<<endl<<endl;
plyrB++; //PAREHO LANG KAY PLAYERONE
resetGame(); //PAREHO LANG KAY PLAYERONE
ticTac();
continue;
}
tie++;
//PAREHO LANG DIN KAY PLAYER ONE BASAHIN NIYO NA LANG
if(tie==9)
{
system("cls");
cout<<endl;
cout<<"\t\t\t\t\tA Tie!"<<endl;
resetGame();
ticTac();
continue;
}
}
//YUNG SUM++ NA TOH PARA DUN SA CONDITION STATEMENT
//DIBA SUM=0, TAPOS PAG ANG ININPUT NG USER EH 2GAMES
//MAUULIT ITONG PROGRAM NG DALAWANG BESES
//ANG PURPOSE NG SUM++ PARA D MAGTULOY-TULOY ANG LARO
sum++;
}
//PAG TAPOS NA YUNG GAME, ITO NA ANG MADIDISPLAY
cout<<endl;
cout<<"\t\t ========================================="<<endl;
cout<<"\t\t TOTAL SCORE"<<endl;
cout<<"\t\t WINS"<<endl;
cout<<"\t\t Player One: "<<plyrA<<endl;
cout<<"\t\t Player Two: "<<plyrB<<endl;
cout<<endl;
tryAgain(); //TATAWAGIN NI GAMEPLAY SI TRYAGAIN KUNG GUSTO PA O HINDI NA
}
void resetGame() //DITO PAPASOK SI GAMEPLAY PAG MAY NANALO
{
int b='1';
for(int a=0; a<9;a++)
{
array[a]=b;
b++;
}
}
{
if(array[0] == array[1] && array[2] == array[0])
{
check=1;
return check;
}
else if(array[3] == array[4] && array[5] == array[3])
{
check=1;
return check;
}
else if(array[6] == array[7] && array[8] == array[6])
{
check=1;
return check;
}
else if(array[0] == array[3] && array[6] == array[0])
{
check=1;
return check;
}
else if(array[1] == array[4] && array[7] == array[1])
{
check=1;
return check;
}
else if(array[2] == array[5] && array[8] == array[2])
{
check=1;
return check;
}
else if(array[0] == array[4] && array[8] == array[0])
{
check=1;
return check;
}
else if(array[2] == array[4] && array[6] == array[2])
{
check=1;
return check;
}
else
{
check=0;
return check;
}
}
void displayScreen()
{
char choose;
cout<<endl;
cout<<" [1] Start The Game"<<endl;
cout<<endl;
cout<<" [2] How To Play The Game"<<endl;
cout<<endl;
cout<<" [3] Exit"<<endl;
cout<<endl;
cout<<endl;
cout<<"\t\t\tEnter A Number In The Menu That You Want: ";
cin>>choose;
system("cls");
switch(choose)
{
case '1':
gamePlay();
break;
case '2':
howtoPlay();
break;
case '3':
cout<<"\t\t\t Thank You For Using Our Program"<<endl<<endl;
break;
default:
cout<<"\t\t\t\tInvalid Input"<<endl;
tryAgain();
break;
}
}
void howtoPlay() //DITO MAPUPUNTA SI DISPLAYSCREEN PAG 2 ANG PINILI NG USER
{
cout<<"\t\tThis Is A Simple Program Made In C++ Called TicTacToe"<<endl;
cout<<"\t\t\tThis Is A Sample Preview Of The Program"<<endl<<endl;
resetGame(); //NILAGAY KO TOH KASI BAKA MAGLARO MUNA SILA BAGO TIGNAN ANG HOWTOPLAY
ticTac(); //TAPOS IPRIPRINT NIYA SI TICTAC
contGameEx(); //PUPUNTA SI HOWTOPLAY KAY CONTGAMEEX
cout<<"\t\tThe Player One Will Be The One To Choose A Number In The Box"<<endl;
cout<<"\t\tThe Player One's Legend is 'X' and Player Two's Legend Is 'O'"<<endl;
cout<<"\t\tThis Is A Sample Output If Player One Choose Box 1 and"<<endl;
cout<<"\t\t\t Player Two Choose Box 5"<<endl<<endl;
resetGame(); //PAREHO LANG SA UNA
ticTacEx(); //IDIDISPLAY NIYA YUNG SAMPLE FIGURE NG BOX
contGameEx(); //PAREHO LANG SA UNA
cout<<"\t\tA Player Wins If He/She Get A Three Legend In Straight Line"<<endl;
cout<<"\t\tor Diagonal Line"<<endl<<endl;
cout<<"\t\tThis Is A Sample Of A Player's Move Who Wins The Game"<<endl<<endl;
ticTacExOne();
}
void contGame()
{
char cont;
cout<<endl;
cout<<"\t\t\tDo You Want To Proceed To The Game [y/n]: ";
cin>>cont;
//KAPAG Y, PUNTA NA SIYA AGAD KAY GAMEPLAY
if(cont=='y' || cont=='Y')
{
system("cls");
gamePlay();
}
//PAG N NAMAN, BABALIK SIYA KAY MAIN
else if(cont=='n' || cont=='N')
{
system("cls");
main();
}
//PAG WALA NAMAN, INVALID ANG INPUT
else
{
cout<<"\t\t\t\t Invalid Input"<<endl;
contGame(); //BABALIK LANG SIYA KAY CONTGAME
}
}
void contGameEx()
{
char cont;
cout<<endl;
cout<<"\t\t\t Do You Want Read More? [y/n]: ";
cin>>cont;
if(cont=='y' || cont=='Y')
{
system("cls");
}
else if(cont=='n' || cont=='N')
{
system("cls");
main();
}
else
{
cout<<"\t\t\t\t Invalid Input"<<endl;
contGameEx();
}
}
void tryAgain()
{
char tryA;
cout<<"\t\tInput letter m if you want to go back to main menu"<<endl;
cout<<"\t\t\t Do You Want Try Again?[y/n]: ";
cin>>tryA;
if(tryA=='y' || tryA=='Y')
{
system("cls");
resetGame();
gamePlay();
}
else if(tryA=='n' || tryA=='N')
{
system("cls");
cout<<"\t\t That Was A Great Game! Thanks For Playing"<<endl<<endl;
}
else if (tryA=='m' || tryA=='M')
{
system("cls");
main();
}
else
{
cout<<"\t\t\t\t Invalid Input"<<endl;
tryAgain();
}
}
void ticTac()
{
cout<<endl<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[0]<<" | "<<array[1]<<" | "<<array[2]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[3]<<" | "<<array[4]<<" | "<<array[5]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[6]<<" | "<<array[7]<<" | "<<array[8]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<endl;
}
void ticTacEx()
{
//IDIDISPLAY NIYA YUNG SAMPLE OUTPUT MAY NAINPUT
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<"X"<<" | "<<array[1]<<" | "<<array[2]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[3]<<" | "<<"O"<<" | "<<array[5]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[6]<<" | "<<array[7]<<" | "<<array[8]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<endl;
}
void ticTacExOne()
{
//SAMPLE OUTPUT NAMAN NG PANALO TAPOS BABALIK ULIT KAY HOWTOPLAY
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<"X"<<" | "<<array[1]<<" | "<<array[2]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[3]<<" | "<<"X"<<" | "<<array[5]<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t| "<<array[6]<<" | "<<array[7]<<" | "<<"X"<<" |"<<endl;
cout<<"\t\t\t| | | |"<<endl;
cout<<"\t\t\t|===========|===========|===========|"<<endl;
cout<<endl;
}
void playerOne()
{
char boxOne;
int ctr=0;
while(ctr!=1)
{
cout<<"\t\t\t\t Player One: "<<endl;
cout<<"\t\t\t Choose A Number In The Box: ";
cin>>boxOne;
switch(boxOne)
{
case '1':
if (array[0] == 'X' || array[0] =='O')
cout<<endl<<"\t\tThe Box [1] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[0]='X';
ctr++;
}
break;
case '2':
if (array[1] == 'X' || array[1] =='O')
cout<<endl<<"\t\tThe Box [2] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[1]='X';
ctr++;
}
break;
case '3':
if (array[2] == 'X' || array[2] == 'O')
cout<<endl<<"\t\tThe Box [3] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[2]='X';
ctr++;
}
break;
case '4':
if (array[3] == 'X' || array[3] == 'O')
cout<<endl<<"\t\tThe Box [4] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[3]='X';
ctr++;
}
break;
case '5':
if (array[4] == 'X' || array[4] == 'O')
cout<<endl<<"\t\tThe Box [5] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[4]='X';
ctr++;
}
break;
case '6':
if (array[5] == 'X' || array[5] == 'O')
cout<<endl<<"\t\tThe Box [6] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[5]='X';
ctr++;
}
break;
case '7':
if (array[6] == 'X' || array[6] == 'O')
cout<<endl<<"\t\tThe Box [7] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[6]='X';
ctr++;
}
break;
case '8':
if (array[7] == 'X' || array[7] =='O')
cout<<endl<<"\t\tThe Box [8] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[7]='X';
ctr++;
}
break;
case '9':
if (array[8] == 'X' || array[8] =='O')
cout<<endl<<"\t\tThe Box [9] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[8]='X';
ctr++;
}
break;
default:
cout<<endl<<"\t\t\tInvalid Input. Please Enter A Valid Number"<<endl<<endl;
break;
}
}
system("cls");
}
void playerTwo()
{
char boxTwo;
int ctr=0;
while(ctr!=1)
{
cout<<"\t\t\t\t Player Two: "<<endl;
cout<<"\t\t\t Choose A Number In The Box: ";
cin>>boxTwo;
//PAREHO LANG TOH KAY PLAYERONE PERO LETTER O NAMAN KAY PLAYERTWO
//KAY PLAYER ONE KASI LETTER X
switch(boxTwo)
{
case '1':
if (array[0] == 'X' || array[0] =='O')
cout<<endl<<"\t\tThe Box [1] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[0]='O';
ctr++;
}
break;
case '2':
if (array[1] == 'X' || array[1] =='O')
cout<<endl<<"\t\tThe Box [2] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[1]='O';
ctr++;
}
break;
case '3':
if (array[2] == 'X' || array[2] == 'O')
cout<<endl<<"\t\tThe Box [3] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[2]='O';
ctr++;
}
break;
case '4':
if (array[3] == 'X' || array[3] == 'O')
cout<<endl<<"\t\tThe Box [4] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[3]='O';
ctr++;
}
break;
case '5':
if (array[4] == 'X' || array[4] == 'O')
cout<<endl<<"\t\tThe Box [5] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[4]='O';
ctr++;
}
break;
case '6':
if (array[5] == 'X' || array[5] == 'O')
cout<<endl<<"\t\tThe Box [6] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[5]='O';
ctr++;
}
break;
case '7':
if (array[6] == 'X' || array[6] == 'O')
cout<<endl<<"\t\tThe Box [7] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[6]='O';
ctr++;
}
break;
case '8':
if (array[7] == 'X' || array[7] =='O')
cout<<endl<<"\t\tThe Box [8] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[7]='O';
ctr++;
}
break;
case '9':
if (array[8] == 'X' || array[8] =='O')
cout<<endl<<"\t\tThe Box [9] Has Been Chosen. Choose Valid Number In The Box"<<endl<<endl;
else
{
array[8]='O';
ctr++;
}
break;
default:
cout<<endl<<"\t\t\tInvalid Input. Please Enter A Valid Number"<<endl<<endl;
break;
}
}
system("cls");
ticTac();
}
Simple Game [C++]
#include <iostream>
#include <Windows.h>
#include <conio.h>
using namespace std;
void gotoxy(int,int);
void ChangeCursorStatus(bool Visible);
void textcolor(int colorNo);
void Loading(int i, int d);
void raygun(int,int,int);
int main()
{
int x(39), y(12);
ChangeCursorStatus(false);
gotoxy(x,y);
textcolor(14);
cout << "X";
int keychar;
do{
keychar=getch();
switch(keychar)
{
case 77:
if(x<=60)
{
gotoxy(x,y);
cout << " ";
gotoxy(++x,y);
cout << "X";
}
break;
case 75:
if(x>=5)
{
gotoxy(x,y);
cout << " ";
gotoxy(--x,y);
cout << "X";
}
break;
case 72:
if(y>=3)
{
gotoxy(x,y);
cout << " ";
gotoxy(x,--y);
cout << "X";
}
break;
case 80:
if(y<=20)
{
gotoxy(x,y);
cout << " ";
gotoxy(x,++y);
cout << "X";
}
break;
case 32:
raygun(x,y,30);
break;
}
}while(1);
system("pause>0");
return 0;
}
void raygun(int a, int b, int d)
{
int c;
for(c=b-2;c>0;c--)
{
Sleep(d);
gotoxy(a,c+1); cout<<" ";
gotoxy(a,c); cout<<"|";
}
gotoxy(a,c+1); cout<<" ";
}
void Loading(int i, int d)
{
cout << "Loading ";
for(int e=0;e<i;e++)
{
Sleep(d); cout<<".";
}
}
void gotoxy(int x, int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
cout.flush();
dwCursorPosition.X = x;
dwCursorPosition.Y = y;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition);
}
void textcolor(int colorNo)
{
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole,colorNo);
}
void ChangeCursorStatus(bool Visible)
{
CONSOLE_CURSOR_INFO *c= new CONSOLE_CURSOR_INFO;
HANDLE h=GetStdHandle(STD_OUTPUT_HANDLE);
if (Visible)
{
c->bVisible=TRUE;
c->dwSize=0;
}
else
{
c->bVisible=FALSE;
c->dwSize=1;
}
SetConsoleCursorInfo(h,c);
}
#include <Windows.h>
#include <conio.h>
using namespace std;
void gotoxy(int,int);
void ChangeCursorStatus(bool Visible);
void textcolor(int colorNo);
void Loading(int i, int d);
void raygun(int,int,int);
int main()
{
int x(39), y(12);
ChangeCursorStatus(false);
gotoxy(x,y);
textcolor(14);
cout << "X";
int keychar;
do{
keychar=getch();
switch(keychar)
{
case 77:
if(x<=60)
{
gotoxy(x,y);
cout << " ";
gotoxy(++x,y);
cout << "X";
}
break;
case 75:
if(x>=5)
{
gotoxy(x,y);
cout << " ";
gotoxy(--x,y);
cout << "X";
}
break;
case 72:
if(y>=3)
{
gotoxy(x,y);
cout << " ";
gotoxy(x,--y);
cout << "X";
}
break;
case 80:
if(y<=20)
{
gotoxy(x,y);
cout << " ";
gotoxy(x,++y);
cout << "X";
}
break;
case 32:
raygun(x,y,30);
break;
}
}while(1);
system("pause>0");
return 0;
}
void raygun(int a, int b, int d)
{
int c;
for(c=b-2;c>0;c--)
{
Sleep(d);
gotoxy(a,c+1); cout<<" ";
gotoxy(a,c); cout<<"|";
}
gotoxy(a,c+1); cout<<" ";
}
void Loading(int i, int d)
{
cout << "Loading ";
for(int e=0;e<i;e++)
{
Sleep(d); cout<<".";
}
}
void gotoxy(int x, int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
cout.flush();
dwCursorPosition.X = x;
dwCursorPosition.Y = y;
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition);
}
void textcolor(int colorNo)
{
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole,colorNo);
}
void ChangeCursorStatus(bool Visible)
{
CONSOLE_CURSOR_INFO *c= new CONSOLE_CURSOR_INFO;
HANDLE h=GetStdHandle(STD_OUTPUT_HANDLE);
if (Visible)
{
c->bVisible=TRUE;
c->dwSize=0;
}
else
{
c->bVisible=FALSE;
c->dwSize=1;
}
SetConsoleCursorInfo(h,c);
}
Add 3 Number in Column [C/C++]
#include<stdio.h>
#include<conio.h>
main()
{
int arr1[3],arr2[3],arr3[4];
printf("Please Enter 1st 3 #\'s\n");
for(int x=0; x<3 ; x++)
{
scanf("%d",& arr1[x]);
}
printf("Please Enter 2nd 3 #\'s\n");
for(int x=0; x<3 ; x++)
{
scanf("%d",& arr2[x]);
}
printf("\nARR1\t+\tARR2\t=\tARR3");
for(int x=0; x<3 ; x++)
{
arr3[x]=arr1[x]+arr2[x];
printf("\n%d\t+\t%d\t=\t%d",arr1[x],arr2[x],arr3[x]);
}
getch();
}
#include<conio.h>
main()
{
int arr1[3],arr2[3],arr3[4];
printf("Please Enter 1st 3 #\'s\n");
for(int x=0; x<3 ; x++)
{
scanf("%d",& arr1[x]);
}
printf("Please Enter 2nd 3 #\'s\n");
for(int x=0; x<3 ; x++)
{
scanf("%d",& arr2[x]);
}
printf("\nARR1\t+\tARR2\t=\tARR3");
for(int x=0; x<3 ; x++)
{
arr3[x]=arr1[x]+arr2[x];
printf("\n%d\t+\t%d\t=\t%d",arr1[x],arr2[x],arr3[x]);
}
getch();
}
1 to N ODD Numbers [C/C++]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int a,b;
main()
{
printf("Enter a Number :");
scanf("%d",&a);
b=0;
while(b <= a)
{
if ( b != 0 && b%2 == 1)
{
printf("\n%d",b);
}
b++;
}
getch();
}
#include<conio.h>
#include<stdlib.h>
int a,b;
main()
{
printf("Enter a Number :");
scanf("%d",&a);
b=0;
while(b <= a)
{
if ( b != 0 && b%2 == 1)
{
printf("\n%d",b);
}
b++;
}
getch();
}
1 to N Even Numbers [C/C++]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int a,b;
main()
{
printf("Enter a Number :");
scanf("%d",&a);
b=0;
while(b <= a)
{
if ( b != 0 && b%2 == 0)
{
printf("\n%d",b);
}
b++;
}
getch();
}
#include<conio.h>
#include<stdlib.h>
int a,b;
main()
{
printf("Enter a Number :");
scanf("%d",&a);
b=0;
while(b <= a)
{
if ( b != 0 && b%2 == 0)
{
printf("\n%d",b);
}
b++;
}
getch();
}
Count the number of letter [C/C++]
#include<iostream>
#include<string>
using namespace std;
void main()
{
char c;
string str;
int len, count = 0;
cout << "Type the word you want: ";
getline(cin,str);
cout << "Type the letter you want to count: ";
cin >> c;
len = str.length();
for (int ctr = 0; ctr < len; ctr++)
{
if (str.at(ctr) == c)
{
count = count + 1;
}
}
cout << "\n";
cout << "There are " << count << " letters in " << str << endl;
}
#include<string>
using namespace std;
void main()
{
char c;
string str;
int len, count = 0;
cout << "Type the word you want: ";
getline(cin,str);
cout << "Type the letter you want to count: ";
cin >> c;
len = str.length();
for (int ctr = 0; ctr < len; ctr++)
{
if (str.at(ctr) == c)
{
count = count + 1;
}
}
cout << "\n";
cout << "There are " << count << " letters in " << str << endl;
}
Magic Square Odd Numbers Only [C/C++]
#include <iostream.h>
int main()
{
int magic[100][100];
int i, j, n, x, y;
for ( i=0 ; i<100; i++ )
for ( j=0 ; j<100 ; j++ )
magic[i][j] = 0;
cout << "Enter value for n (odd only): ";
cin >> n;
x = 0 ; y = (n-1) / 2;
magic[x][y] = 1;
for ( i=2 ; i <= n*n ; i++ )
{
x--; y++;
if ( x < 0 && y == n )
{
x = x + 2;
y--;
}
if ( x < 0 ) { x = n - 1; }
if ( y >= n ) { y = 0; }
if ( magic[x][y] != 0 )
{
x = x + 2;
y = y - 1;
}
magic[x][y] = i;
}
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
cout << magic[i][j] << "\t";
}
cout << endl;
}
return 0;
}
int main()
{
int magic[100][100];
int i, j, n, x, y;
for ( i=0 ; i<100; i++ )
for ( j=0 ; j<100 ; j++ )
magic[i][j] = 0;
cout << "Enter value for n (odd only): ";
cin >> n;
x = 0 ; y = (n-1) / 2;
magic[x][y] = 1;
for ( i=2 ; i <= n*n ; i++ )
{
x--; y++;
if ( x < 0 && y == n )
{
x = x + 2;
y--;
}
if ( x < 0 ) { x = n - 1; }
if ( y >= n ) { y = 0; }
if ( magic[x][y] != 0 )
{
x = x + 2;
y = y - 1;
}
magic[x][y] = i;
}
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
cout << magic[i][j] << "\t";
}
cout << endl;
}
return 0;
}
C and C++ E-Books
"C++" E-Books
- Applied C++ - Practical Techniques For Building Better Software (2003).chm
- Beginning C++ Game Programming (2004).pdf
- Beyond The C++ Standard Library - An Introduction To Boost (2005).chm
- C++ - How To Program, 5th Edition (2005).chm
- C++ By Dissection (2002).pdf
- C++ Coding Standards - 101 Rules, Guidelines, And Best Practices (2004).chm
- C++ Cookbook (2005).chm
- C++ Demystified - A Self Teaching Guide (2004).chm
- C++ For Business Programming, 2nd Edition (2005).chm
- C++ For Dummies, 5th Edition (2004).pdf
- C++ For Mathematicians - An Introduction For Students And Professionals (2006).pdf
- C++ From The Ground Up, 3rd Edition (2003).pdf
- C++ GUI Programming With Qt 4 (2006).chm
- C++ In A Nutshell (2003).chm
- C++ Plus Data Structures, 3rd Edition (2003).pdf
- C++ Primer, 4th Edition (2005).chm
- C++ Templates - The Complete Guide (2002).chm
- C++ Timesaving Techniques For Dummies (2005).pdf
- C++ Tutorial By Clayman.html
- c++ tutorial.pdf
- C-C++ Programmer's Reference, 3rd Edition (2003).chm
- Creating Games In C++ - A Step By Step Guide (2006).chm
- Cryptography In C And C++ (2001).chm
- Effective C++, 3rd Edition (2005).chm
- Exceptional C++ - 47 Engineering Puzzles, Programming Problems, And
- Solutions (1999).chm
- Exceptional C++ Style - 40 New Engineering Puzzles, Programming
- Problems, And Solutions (2004).chm
- How Not To Program In C++ (2003).chm
- Ivor Horton's Beginning Visual C++ 2005 (2006).pdf
- Learn To Program With C++ (2003).pdf
- McGraw Hill Herb Schildts C plus plus Programming Cookbook Apr 2008.pdf
- Packt Publishing Microsoft Visual C++ Windows Applications by Example Jun 2008.pdf
- Teach Yourself C++ in 21 Days
- think in cpp.pdf
- Visual C++ 6 for Dummies Quick Reference.pdf
- BASIC C Socket Programming In Unix For Newbies.txt
- C & C++ Programming Style Guidlines.pdf
- C for Dummies, 2nd Edition.pdf
- Sams Teach Yourself Visual C Sharp 2008 in 24 Hours Complete Starter Kit Jul 2008.pdf
- The C Programming Language Torn Apart.html
-
Guessing Game [C/C++]
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<iostream>
main()
{
int a,b,c,d,e,f,f1,points,ctr;
do{
system("cls");
system("color 6");
srand(time(NULL));
b=1+rand()%10;
ctr=3;
e=b;
system("cls");
do{
printf("Guess a Number: ");
scanf("%d",&a);
if(a>b)
{
printf("Lower Please!!\n");
}
if(a<b)
{
printf("Higher Please!!\n");
}
ctr--;
if( ctr==2)
{
points=15;
}
if( ctr==1)
{
points=10;
}
if( ctr==0)
{
points=5;
}
if(a == b)
{
system("color 7");
printf("\n\nExcellent You Got it!!\n");
printf("Your Score is %d\n",points);
}
}while(a!=b && ctr!=0);
if(a!=b && ctr==0)
{
system("color 4");
printf("\n\nYou did not Get it !! \n%d is the Number!!",e);
printf("Your Score is 0");
}
printf("\n\n\nTry Again ? 1=Yes 2=No");
scanf("%d",&d);
if(d==1)
{
ctr+3;
}
if(d==2)
{
break;
}
}while(1);
return(0);
}
#include<conio.h>
#include<stdlib.h>
#include<iostream>
main()
{
int a,b,c,d,e,f,f1,points,ctr;
do{
system("cls");
system("color 6");
srand(time(NULL));
b=1+rand()%10;
ctr=3;
e=b;
system("cls");
do{
printf("Guess a Number: ");
scanf("%d",&a);
if(a>b)
{
printf("Lower Please!!\n");
}
if(a<b)
{
printf("Higher Please!!\n");
}
ctr--;
if( ctr==2)
{
points=15;
}
if( ctr==1)
{
points=10;
}
if( ctr==0)
{
points=5;
}
if(a == b)
{
system("color 7");
printf("\n\nExcellent You Got it!!\n");
printf("Your Score is %d\n",points);
}
}while(a!=b && ctr!=0);
if(a!=b && ctr==0)
{
system("color 4");
printf("\n\nYou did not Get it !! \n%d is the Number!!",e);
printf("Your Score is 0");
}
printf("\n\n\nTry Again ? 1=Yes 2=No");
scanf("%d",&d);
if(d==1)
{
ctr+3;
}
if(d==2)
{
break;
}
}while(1);
return(0);
}
Area of Rectangle Calculator [C/C++]
#include<stdio.h>
#include<conio.h>
main()
{
int length,width,area;
printf("Enter the Lenght of a rectangle:");
scanf("%d",&length);
printf("\nEnter the Width of a rectangle:");
scanf("%d",&width);
area = length*width;
printf("\n\n\n\nThe Area of the Rectangle is %d",area);
getch();
}
#include<conio.h>
main()
{
int length,width,area;
printf("Enter the Lenght of a rectangle:");
scanf("%d",&length);
printf("\nEnter the Width of a rectangle:");
scanf("%d",&width);
area = length*width;
printf("\n\n\n\nThe Area of the Rectangle is %d",area);
getch();
}
Simple Time Converter [C/C++]
#include<stdio.h>
#include<conio.h>
int a,b,c,d;
main()
{
printf("****************************************\n");
printf("* Time Conversion *\n");
printf("* *\n");
printf("* 1] 60 secs = 1 min *\n");
printf("* 2] 60 min = 1 hour *\n");
printf("* *\n");
printf("****************************************\n");
printf("Input 1 for sec to min ; 2 for min to hour: ");
/*dL1nkx*/
scanf("%d",&a);
if ( a == 1)
{/*dL1nkx*/
printf("\n\nPlease Enter SECONDS: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d secs there are %d min and %d secs ",b,c,d);
}/*dL1nkx*/
if ( a == 2)
{
printf("\n\nPlease Enter MINUTES: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d mins there are %d hour and %d mins ",b,c,d);
}
if (a != 1 && a!=2)
{
printf("Please Enter 1 or 2 Only");/*dL1nkx*/
}
getch();
}
#include<conio.h>
int a,b,c,d;
main()
{
printf("****************************************\n");
printf("* Time Conversion *\n");
printf("* *\n");
printf("* 1] 60 secs = 1 min *\n");
printf("* 2] 60 min = 1 hour *\n");
printf("* *\n");
printf("****************************************\n");
printf("Input 1 for sec to min ; 2 for min to hour: ");
/*dL1nkx*/
scanf("%d",&a);
if ( a == 1)
{/*dL1nkx*/
printf("\n\nPlease Enter SECONDS: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d secs there are %d min and %d secs ",b,c,d);
}/*dL1nkx*/
if ( a == 2)
{
printf("\n\nPlease Enter MINUTES: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d mins there are %d hour and %d mins ",b,c,d);
}
if (a != 1 && a!=2)
{
printf("Please Enter 1 or 2 Only");/*dL1nkx*/
}
getch();
}
Simple Time Converter [C/C++]
#include<stdio.h>
#include<conio.h>
int a,b,c,d;
main()
{
printf("****************************************\n");
printf("* Time Conversion *\n");
printf("* *\n");
printf("* 1] 60 secs = 1 min *\n");
printf("* 2] 60 min = 1 hour *\n");
printf("* *\n");
printf("****************************************\n");
printf("Input 1 for sec to min ; 2 for min to hour: ");
/*dL1nkx*/
scanf("%d",&a);
if ( a == 1)
{/*dL1nkx*/
printf("\n\nPlease Enter SECONDS: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d secs there are %d min and %d secs ",b,c,d);
}/*dL1nkx*/
if ( a == 2)
{
printf("\n\nPlease Enter MINUTES: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d mins there are %d hour and %d mins ",b,c,d);
}
if (a != 1 && a!=2)
{
printf("Please Enter 1 or 2 Only");/*dL1nkx*/
}
getch();
}
#include<conio.h>
int a,b,c,d;
main()
{
printf("****************************************\n");
printf("* Time Conversion *\n");
printf("* *\n");
printf("* 1] 60 secs = 1 min *\n");
printf("* 2] 60 min = 1 hour *\n");
printf("* *\n");
printf("****************************************\n");
printf("Input 1 for sec to min ; 2 for min to hour: ");
/*dL1nkx*/
scanf("%d",&a);
if ( a == 1)
{/*dL1nkx*/
printf("\n\nPlease Enter SECONDS: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d secs there are %d min and %d secs ",b,c,d);
}/*dL1nkx*/
if ( a == 2)
{
printf("\n\nPlease Enter MINUTES: ");
scanf("%d",&b);
c = b/60;
d = b%60;
printf("\nIn %d mins there are %d hour and %d mins ",b,c,d);
}
if (a != 1 && a!=2)
{
printf("Please Enter 1 or 2 Only");/*dL1nkx*/
}
getch();
}
Subscribe to:
Posts (Atom)