luc030.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 12 Dec 2025
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Write a program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows : - There are 21 matchsticks. - The computer asks the player to pick 1, 2, 3, or 4 matchsticks. - After the person picks, the computer does its picking. - Whoever is forced to pick up the last matchstick loses the game.
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#include <stdio.h>
int main()
{
int remaining_matchsticks = 21, player_pick, computer_pick;
printf(" --- Matchstick Game ---\n");
printf("Rules: There are 21 matchsticks. You can pick 1, 2, 3, or 4.\n");
printf("Whoever is forced to pick the last matchstick loses the game.\n");
while (remaining_matchsticks > 1)
{
// game start
printf("\n--------------------------");
printf("\nRemaining Matchsticks : %d", remaining_matchsticks);
// player pick and checking input is valid or not
printf("\nYour turn: Pick 1, 2, 3, or 4 matchsticks: ");
if (scanf("%d", &player_pick) != 1)
{
printf("\n\tPlease enter a number.");
while (getchar() != '\n')
;
continue;
}
// checking player pick is valid or not
if (player_pick < 1 || player_pick > 4)
{
printf("\n\tPlease enter a number among 1, 2, 3 and 4.");
while (getchar() != '\n')
;
continue;
}
if (player_pick > remaining_matchsticks)
{
printf("\nInvalid choice! There are not enough matchsticks left.");
while (getchar() != '\n')
;
continue;
}
// computer_picks
computer_pick = 5 - player_pick;
printf("\ncomputer_picks : %d", computer_pick);
// remaining matchsticks
remaining_matchsticks = remaining_matchsticks - (player_pick + computer_pick);
}
// game over
printf("\n----------------------------------\n");
printf("Only 1 matchstick is left.\n");
printf("You are forced to pick the last matchstick. You lose!\n");
printf("The computer wins.\n");
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56