CrazyEngineers
  • 2nd c++ Problem

    Manish Goyal

    Member

    Updated: Oct 25, 2024
    Views: 1.2K
    Write a Program for matchstick game between the computer and a user ..Your program should ensure that the computer always wins ..Rules for game are
    1:-There are 21 matchsticks
    2:-The computer asks the player to pick 1,2,3,4 matchsticks
    3:-After the person picks,the computer does its picking.
    whoever is forced to pick up the last match-stick loses the Game
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • pradeep_agrawal

    MemberDec 30, 2009

    Find below my piece of code for same.

    #include "stdio.h"
    
    int main() {
      int choice = 0;
      int sum = 0;
    
      while(sum != 20) {
        while((choice < 1) || (choice > 4)) {
          printf("Enter number of matchstick you want to pick (between 1 to 4): ");
          scanf("%d", &choice);
          if((choice < 1) || (choice > 4)) {
            printf("Invalid input\n");
          }
        }
        sum += choice;
        printf("Matchstick left: %d\n", 21 - sum);
        printf("Matchsticks picked by computer: %d\n", 5 - choice);
        sum += 5 - choice;
        printf("Matchstick left: %d\n", 21 - sum);
        scanf("%c", &choice);
        choice = 0;
      }
    
      printf("Only one stick left and your turn to pick. You lost.\n");
    
      return 0;
    }
    
    -Pradeep
    Are you sure? This action cannot be undone.
    Cancel
  • gaurav.bhorkar

    MemberDec 30, 2009

    Good, Pradeep.
    Are you sure? This action cannot be undone.
    Cancel
  • Manish Goyal

    MemberDec 31, 2009

    pradeep_agrawal
    Find below my piece of code for same.

    #include "stdio.h"
    
    int main() {
      int choice = 0;
      int sum = 0;
    
      while(sum != 20) {
        while((choice < 1) || (choice > 4)) {
          printf("Enter number of matchstick you want to pick (between 1 to 4): ");
          scanf("%d", &choice);
          if((choice < 1) || (choice > 4)) {
            printf("Invalid input\n");
          }
        }
        sum += choice;
        printf("Matchstick left: %d\n", 21 - sum);
        printf("Matchsticks picked by computer: %d\n", 5 - choice);
        sum += 5 - choice;
        printf("Matchstick left: %d\n", 21 - sum);
        scanf("%c", &choice);
        choice = 0;
      }
    
      printf("Only one stick left and your turn to pick. You lost.\n");
    
      return 0;
    }
    
    -Pradeep
    Good ...you have correct output
    Are you sure? This action cannot be undone.
    Cancel
  • Sahithi Pallavi

    MemberDec 31, 2009

    You have done a good job pradeep...!

    keep it up..!
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register