In: Computer Science
(General math) In the game of blackjack, the cards 2 through 10 are counted at their face values, regardless of suit; all face cards (jack, queen, and king) are counted as 10; and an ace is counted as a 1 or an 11, depending on the total count of all cards in a player’s hand. The ace is counted as 11 only if the resulting total value of all cards in a player’s hand doesn’t exceed 21; otherwise, it’s counted as 1. Using this information, write a C++ program that accepts three card values as inputs (a 1 corresponding to an ace, a 2 corresponding to a two, and so on), calculates the total value of the hand, and displays the value of the three cards.
#include <iostream>
using namespace std;
#include<stdlib.h>
int value(char card)
{
int val;
if (card=='A')
val=1;
else if (card=='J' or card=='K' or card=='Q')
val=10;
else
{
val=card-48;
if(val>10 or val<0)
{
return 0;
}
}
return val;
}
int main()
{
char card; int total;
int card1,card2,card3;
cout<<"Type the card- A for Ace;J for Jack; K for King; Q for Queen";
cout<<"\nCard 1:";
cin>>card; // Get the input as character
card1=value(card);
cout<<"\nCard 2:";
cin>>card;
card2=value(card);
cout<<"\nCard 3:";
cin>>card;
card3=value(card);
total=card1+card2+card3; // total value of cards
if (card1==1 && total<=21)
card1=11;
else if (card2==1 && total<=21)
card2=11;
else if (card3==1 && total<=21)
card3=11;
total=card1+card2+card3;
cout<<"\nTotal Value in Hand"<<total;
cout<<"\nCard 1 Value"<<card1;
cout<<"\nCard 2 Value"<<card2;
cout<<"\nCard 3 Value"<<card3;
return 0;
}
SCREENSHOT OF PROGRAM
EXPLANATION
Read card from user as character and calculate the value of card. If the card is a number from 2 to 10, the character input obtained can be converted into an integer for further value processing. To accomplish this, the ASCII value is used- the ASCII value of 0 is 48. So, subtract 48 from the card's value. If the card is K,J and Q, the value is 10. Else if the input is A, then find the total value in hand. When it does not exceed 21, consider the value of card as 11.
OUTPUT - SCREENSHOT