C Programming

Solved Example

Practice Questions

Exercise Question

Match Stick game

Objective

Write a program for a match-stick game between the user and the computer. Your program should ensure that the computer always wins. Rules for the game are as follows:

  • There are 21 match-sticks
  • The computer asks the player to pick 1,2,3, or 4 match-sticks.
  • After the person picks, the computer does its picks.
  • Whoever is forced to pick up the last matchstick loses the game.

Program / Solution

#include<stdio.h>
int main() {
	int m = 21;
	int picks,cpicks;
	
	while(1) {
		printf("\nMatch sticks left %d\n--------------------------------------------\n",m);
		
		printf("\nPick the match sticks 1,2,3, or 4: ");
		scanf("%d",&picks);
		
		if(picks < 1 || picks > 4) {
			printf("Invalid Picks\n\n");
			continue;
		}
		
		m = m - picks;
		printf("Your picks = %d\n",picks);
		
		cpicks = 5 - picks;
		printf("Computer picks  = %d\n",cpicks);
		
		m = m - cpicks;
		
		if(m == 1) {
			printf("\n\nNumber of matchsticks left %d",m);
			printf("\nYou lost the game!!");
			break;
		}
	}
	return 0;
}

Sample Output

Match sticks left 21
--------------------------------------------

Pick the match sticks 1,2,3, or 4: 5
Invalid Picks


Match sticks left 21
--------------------------------------------

Pick the match sticks 1,2,3, or 4: 2
Your picks = 2
Computer picks  = 3

Match sticks left 16
--------------------------------------------

Pick the match sticks 1,2,3, or 4: 1
Your picks = 1
Computer picks  = 4

Match sticks left 11
--------------------------------------------

Pick the match sticks 1,2,3, or 4: 2
Your picks = 2
Computer picks  = 3

Match sticks left 6
--------------------------------------------

Pick the match sticks 1,2,3, or 4: 3
Your picks = 3
Computer picks  = 2


Number of matchsticks left 1
You lost the game!!