fork download
  1. // **************************************************
  2. // Function: blackJackValue
  3. //
  4. // Description: Calculates the blackjack value of two cards
  5. //
  6. // Parameters: card1 - first card (char)
  7. // card2 - second card (char)
  8. //
  9. // Returns: total hand value
  10. // -1 if invalid card
  11. //
  12. // **************************************************
  13.  
  14. #include <stdio.h>
  15.  
  16. // function prototype
  17. int blackJackValue(char card1, char card2);
  18.  
  19. int main()
  20. {
  21. char card1, card2;
  22. int result;
  23.  
  24. // prompt user for cards
  25. printf("Enter first card (2-9, T, J, Q, K, A): ");
  26. scanf(" %c", &card1);
  27.  
  28. printf("Enter second card (2-9, T, J, Q, K, A): ");
  29. scanf(" %c", &card2);
  30.  
  31. // call function
  32. result = blackJackValue(card1, card2);
  33.  
  34. // check for invalid result
  35. if(result != -1)
  36. {
  37. printf("\nFinal Hand Value: %d\n", result);
  38. }
  39.  
  40. return 0;
  41. }
  42.  
  43. int blackJackValue(char card1, char card2)
  44. {
  45. int handValue = 0; // MUST initialize
  46. char hand[2] = {card1, card2};
  47.  
  48. // check for two Aces
  49. if(hand[0] == 'A' && hand[1] == 'A')
  50. {
  51. handValue = 12;
  52. printf("\nThe score is %d", handValue);
  53. return handValue;
  54. }
  55.  
  56. // loop to determine hand value
  57. for(int i = 0; i < 2; ++i)
  58. {
  59. // number cards
  60. if(hand[i] >= '2' && hand[i] <= '9')
  61. {
  62. handValue += hand[i] - '0';
  63. }
  64.  
  65. // face cards
  66. else if(hand[i] == 'T' || hand[i] == 'J' || hand[i] == 'Q' || hand[i] == 'K')
  67. {
  68. handValue += 10;
  69. }
  70.  
  71. // Ace
  72. else if(hand[i] == 'A')
  73. {
  74. handValue += 11;
  75. }
  76.  
  77. // invalid
  78. else
  79. {
  80. printf("\nInvalid card");
  81. return -1;
  82. }
  83. }
  84.  
  85. printf("\nThe score is %d", handValue);
  86. return handValue;
  87. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Enter first card (2-9, T, J, Q, K, A): Enter second card (2-9, T, J, Q, K, A): 
Invalid card