fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int blackjackScore(char card1, char card2)
  5. {
  6.  
  7. // Convert cards to uppercase
  8. card1 = toupper(card1);
  9. card2 = toupper(card2);
  10.  
  11. int value1 = 0;
  12. int value2 = 0;
  13.  
  14. // Card value calculations made into another function for better maintainability
  15. int calcCardValue(char card)
  16. {
  17. if (card >= '2' && card <= '9')
  18. {
  19. return card - '0'; // Regular cards 2 through 9
  20. }
  21.  
  22. else if (card == 'T' || card == 'J' || card == 'Q' || card == 'K')
  23. {
  24. return 10; // For face cards
  25. }
  26.  
  27. else if (card == 'A')
  28. {
  29. return 11; // For ace
  30. }
  31.  
  32. else
  33. {
  34. return -1; // Invalid card
  35. } // If end
  36. }
  37.  
  38. value1 = calcCardValue(card1);
  39. value2 = calcCardValue(card2);
  40.  
  41. // Check for invalid input
  42. if (value1 == -1 || value2 == -1)
  43. {
  44. printf("*** Invalid card entered.\n");
  45. return -1;
  46. }
  47.  
  48. // Checks if you are dealt two aces, makes them equal 11+1=12
  49. if (card1 == 'A' && card2 == 'A')
  50. {
  51. return 12;
  52. }
  53.  
  54. // makes one ace equal 1 instead so you don't bust
  55. int total = value1 + value2;
  56. if ((card1 == 'A' || card2 == 'A') && total > 21)
  57. {
  58. total -= 10; // 11 - 10 = 1
  59. }
  60.  
  61. return total;
  62. }
  63.  
  64. int main()
  65. {
  66. char c1, c2;
  67. printf("Enter two cards: ");
  68. scanf(" %c %c", &c1, &c2);
  69.  
  70. int score = blackjackScore(c1, c2);
  71. if (score != -1)
  72. {
  73. printf("The score is %d\n", score);
  74. }
  75.  
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 5296KB
stdin
K A
stdout
Enter two cards: The score is 21