2nd c++ Problem

Manish Goyal

Manish Goyal

@manish-r2Hoep Oct 25, 2024
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

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • pradeep_agrawal

    pradeep_agrawal

    @pradeep-agrawal-rhdX5z Dec 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
  • gaurav.bhorkar

    gaurav.bhorkar

    @gauravbhorkar-Pf9kZD Dec 30, 2009

    Good, Pradeep.
  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Dec 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
  • Sahithi Pallavi

    Sahithi Pallavi

    @sahithi-oJZaYj Dec 31, 2009

    You have done a good job pradeep...!

    keep it up..!