21 Matchstick Game: C Program

Write a C 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.

Related Read:
while loop in C programming
if else statement in C
Relational Operators In C

Logic of 21 Matchstick Game C Program

There are in total 21 match sticks to start the game. First we ask the user to pick either 1 or 2 or 3 or 4 matches per pick. Once the user makes his/her pick, computer makes the picking(same rules apply to the computer i.e., it can pick either 1 or 2 or 3 or 4 matches per pick). The trick is, computers pick is always 5 minus the pick of the user. For example, if computers pick is variable c and user pick is stored in variable p, then:
c = 5 – p;
This makes sure computer always wins the game. That is, the last pick will always be of the user.

Note: We have 1 as the condition in while loop to make sure the while loop keeps executing until a break statement is occurred inside the loop to terminate the execution of the loop. while(1) is considered as an infinite loop(unless we have some ways to break out of the loop programmatically).

Note:
break; breaks out of the loop or terminates the execution of the loop.

continue; skips execution of all the code after it in the loop and goes for the next iteration of the loop.

Video Tutorial: 21 Matchstick Game: C Program


[youtube https://www.youtube.com/watch?v=VO_5XTLxKmc]

YouTube Link: https://www.youtube.com/watch?v=VO_5XTLxKmc [Watch the Video In Full Screen.]

Source Code: 21 Matchstick Game: C Program

#include<stdio.h>

int main()
{
    int m = 21, p, c;

    while(1)
    {
        printf("\nNumber of Match sticks left = %d\n", m);
        printf("Pick 1 or 2 or 3 or 4 matches\n");
        scanf("%d", &p);

        if(p > 4 || p < 1)
            continue;

        m = m - p;

        printf("Number of matches left = %d\n", m);

        c = 5 - p;

        printf("out of which computer picked up %d\n", c);

        m = m - c;

        if(m == 1)
        {
            printf("\nNumber of matches left = %d\n", m);
            printf("You lost the Game\n");
            break;
        }
    }

    return 0;
}

Output:
Number of Match sticks left = 21
Pick 1 or 2 or 3 or 4 matches
2
Number of matches left = 19
out of which computer picked up 3

Number of Match sticks left = 16
Pick 1 or 2 or 3 or 4 matches
3
Number of matches left = 13
out of which computer picked up 2

Number of Match sticks left = 11
Pick 1 or 2 or 3 or 4 matches
1
Number of matches left = 10
out of which computer picked up 4

Number of Match sticks left = 6
Pick 1 or 2 or 3 or 4 matches
4
Number of matches left = 2
out of which computer picked up 1

Number of matches left = 1
You lost the Game

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

while loop in C programming

So far we’ve seen sequential flow of our programs. Next we saw decision control statements like if, if else, else if etc. Now lets learn about loop control statements present in C programming language.

In this video tutorial lets learn about while loop in particular.

Related Read:
Programming Interview / Viva Q&A: 5 (Infinite or Indefinite while loop)

General Syntax of while loop

 
#include < stdio.h >

int main()
{
    while(pre_test_condition)
      statement1;

    return 0;
}

Here while is the keyword. Inside parenthesis we need to write the condition. These conditions must evaluate to Boolean value. i.e., true(non-zero number) or false(0);

The ‘body of while’ loop keeps executing until the condition is true. Control exits while loop once the condition is false.

 
#include < stdio.h >

int main()
{
    while(pre_test_condition)
   {
      statement1;
      statement2;
   }
    return 0;
}

Enclose the statements with curly braces if there are multiple statements within while loop or body of while loop.

while loop in C programming Language


[youtube https://www.youtube.com/watch?v=2Mkc80-uqrs]

YouTube Link: https://www.youtube.com/watch?v=2Mkc80-uqrs [Watch the Video In Full Screen.]


Example Source Code: while loop

 
#include < stdio.h >

int main()
{
    int count = 1;

    while(count <= 5)
    {
        printf("%d\n", count);
        count = count + 1;
    }

    printf("End of loop\n");

    return 0;
}

Output:
1
2
3
4
5
End of loop

In above C source code, variable count is initialized to 1. Inside while condition we check if variable count is less than or equal to 5. Until variable count is less than or equal to 5, the while loop keeps executing. Inside body of the while loop we increment the value of count by 1 upon each execution of the loop. The condition is checked on execution of the loop. Once variable count is more than 5, the condition becomes false count <= 5 (once count value is 6, the condition becomes false), the execution control exits while loop.

Note: Here the loop execution counter is called ‘loop counter’ or ‘index variable’.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Cursor Object: MongoDB

Lets have a deeper look into the MongoDB cursor object.

cursor-object-mongodb

Documents in our collection
test database, names collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> use test
switched to db test
> show collections
names
system.indexes
> db.names.find();
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

We have 8 documents with name in alphabetical order, and 1 document with name as 25. So in total we have 9 documents in our names collection.

Establishing Cursor

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> cur
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

Look at the contents of our cursor object cur.

hasNext() and next() methods on Cursor

1
2
3
4
5
6
7
8
9
> var cur = db.names.find();
> cur.hasNext();
true
> cur.next()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
> cur.next()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
> cur.next()
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }

If there are any documents to iterate inside cursor object, then hasNext() will return true orelse it’ll return false. If hasNext() returns true, then we can iterate through the documents using next() method on the cursor object.

sort() method on Cursor Object

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> cur.sort({"name": -1});
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

We could modify the cursor object using methods like sort(), limit() and skip(). In above example, we are modifying cursor object using sort() method, and we are sorting it in reverse lexicographical order on the name field.

limit() method on Cursor Object

1
2
3
4
5
> var cur = db.names.find();
> cur.limit(3);
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }

We could limit the output/result using limit() method.

Chaining method on Cursor Object

1
2
3
4
5
6
7
8
> var cur = db.names.find();
 
> cur.sort({"name": -1}).limit(5).skip(2);
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }

Here we chain the methods sort(), limit() and skip(). We are sorting in reverse lexicographical order on the name field, then skipping the first 2 documents and then limiting the result/output to 5 documents.

The order in which these 3 methods are applied are: First sort, then skip and then limit.
Also note that, these methods modify cursor object at the server side and not on client site.

Cursor Object: MongoDB


[youtube https://www.youtube.com/watch?v=_LexQW0vSlQ]

YouTube Link: https://www.youtube.com/watch?v=_LexQW0vSlQ [Watch the Video In Full Screen.]



explain() method on Cursor Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> db.names.find().explain();
{
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 9,
        "nscannedObjects" : 9,
        "nscanned" : 9,
        "nscannedObjectsAllPlans" : 9,
        "nscannedAllPlans" : 9,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "server" : "PC:27017",
        "filterSet" : false
}

explain() method shows that find() returns a basic cursor. More on explain() method in coming videos.

Programmatic way of printing Cursor Object content

1
2
3
4
5
6
7
8
9
10
11
12
> var cur = db.names.find();
 
> while(cur.hasNext()) printjson(cur.next());
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }

While loop executes until cur.hasNext() returns true. Until cur.hasNext() is true, cur.next() keeps printing next document in the cursor cur.