Tuesday 28 May 2013

Recursion

Let Us C, Ch-5.

In my first post I wrote that I'm am going to learn about pointers. Have learnt a bit, at least as much as that lesson taught (I know what the differences between '*i', '&i" and, 'i' are), but nothing interesting really.

So going straight to one of the next lessons. This program seems worth recording.
Still have a while to understand Recursion enough to write my own exercise program. When I look through the program, I can understand how it does what it is doing.

This program finds the factorial of a number. At least I learned that a factorial is the product of a number and all numbers before it.

Factorial of 1= 1
Factorial of 2= 2 X 1= 2
Factorial of 3=3 X 2 X 1 = 6
Factorial of 4= 4 X 3 X 2 X 1= 24
So on and so forth. (More about Factorials at http://en.wikipedia.org/wiki/Factorial ).

The following is the same program in the book with very minor modifications.

#include <stdio.h>

int rec(int x);

main()
{
    int a,fact;

    printf("\nEnter The number you want to find the Factorial of: ");
    scanf(" %d",&a);

    fact=rec(a);
    printf("\nThe factorial value of %i= %i",a,fact);
}

int rec(int x)
{
    int f;

    if(x==1)
    {
        return(1);
    }

    else
    {
        f=x*rec(x-1); //Recursion right here because the function
                      //    rec(x) calls itself subtracting 1 from x.
                      //     Whatever x may be, it is multiplied by 1 less than itself.
                      //     But when it calls itself, it finds the line  f=x*rec(x-1);
                      //    again, and calls itself again and again.
                      //     This will go on until the condition 'if(x==1)' is met

        return(f); //Then it finally returns the finished product to main.
    }
}

Sunday 26 May 2013

Mario & Luigi

 I referred to a picture at http://alexno.com/super-mario/pixel-mario/ for Mario.

For Luigi, it's the same pattern, except change colours from red to green (from 12 to 10....find and replace).
There may be better ways to do this, but i don't know, maybe i'll learn later.



<─ This is what it displays.







Here is the code (I still dont understand how the colours thing works):

/*Program to display ASCII Mario & Luigi */

#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <windows.h>

#define TRUE 1
#define FALSE !TRUE


void SetColorAndBackground(int ForgC, int BackC);
void green(int c);
void grey(int d);
void flesh(int e);
void black(int f);
void red(int h);
void nl(int g);
void luigi(void);
void mario(void);

int x,y=176,z,state;

main()
{
    state=TRUE;
    while(state)
    {
        char k;
        system("cls");
        printf("A: Mario\nB: Luigi\nC: Both\nD: Exit\n");
        printf("Choice: ");
        k=toupper(getch());

        if (k=='A' || k=='B' || k=='C' || k=='D')
        {
            if(k=='A')
            {
                system("cls");
                mario();
                SetColorAndBackground(7,0);
                getch();
            }
            else if(k=='B')
            {
                system("cls");
                luigi();
                SetColorAndBackground(7,0);
                getch();
            }
            else if(k=='C')
            {
                system("cls");
                mario();
                nl(1);
                luigi();
                SetColorAndBackground(7,0);
                getch();
            }
            else if(k=='D')
            {
                system("cls");
                SetColorAndBackground(7,0);
                state=FALSE;
            }
        }
    }
}

void mario(void)      /*This took a while to figure and write. Run, compare between
                                 Output and picture at http://alexno.com/super-mario/pixel-mario/ 
                                 and put in a few more or remove a few*/
{
    black(6);
    red(8);
    black(6);
    nl(1);

    black(4);
    red(14);
    nl(1);

    black(4);
    grey(6);
    flesh(3);
    grey(1);
    flesh(1);
    nl(1);

    black(2);
    grey(2);
    flesh(2);
    grey(2);
    flesh(5);
    grey(1);
    flesh(3);
    nl(1);

    black(2);
    grey(2);
    flesh(2);
    grey(4);
    flesh(4);
    grey(1);
    flesh(4);
    nl(1);

    black(2);
    grey(4);
    flesh(7);
    grey(4);
    nl(1);

    black(6);
    flesh(10);
    nl(1);

    black(4);
    grey(3);
    red(1);
    grey(6);
    nl(1);

    black(2);
    grey(5);
    red(1);
    grey(5);
    red(1);
    grey(4);
    nl(1);

    grey(7);
    red(7);
    grey(6);
    nl(1);

    flesh(4);
    grey(2);
    red(1);
    flesh(2);
    red(3);
    flesh(2);
    red(1);
    grey(1);
    flesh(4);
    nl(1);

    flesh(6);
    red(1);
    flesh(2);
    red(3);
    flesh(2);
    red(1);
    flesh(5);
    nl(1);

    flesh(4);
    red(10);
    red(2);
    flesh(4);
    nl(1);

    black(4);
    red(5);
    black(2);
    red(5);
    nl(1);

    black(2);
    grey(6);
    black(4);
    grey(6);
    nl(1);

    grey(8);
    black(4);
    grey(8);
    nl(1);
}
void luigi(void)
{
    black(6);
    green(8);
    black(6);
    nl(1);

    black(4);
    green(14);
    nl(1);

    black(4);
    grey(6);
    flesh(3);
    grey(1);
    flesh(1);
    nl(1);

    black(2);
    grey(2);
    flesh(2);
    grey(2);
    flesh(5);
    grey(1);
    flesh(3);
    nl(1);

    black(2);
    grey(2);
    flesh(2);
    grey(4);
    flesh(4);
    grey(1);
    flesh(4);
    nl(1);

    black(2);
    grey(4);
    flesh(7);
    grey(4);
    nl(1);

    black(6);
    flesh(10);
    nl(1);

    black(4);
    grey(3);
    green(1);
    grey(6);
    nl(1);

    black(2);
    grey(5);
    green(1);
    grey(5);
    green(1);
    grey(4);
    nl(1);

    grey(7);
    green(7);
    grey(6);
    nl(1);

    flesh(4);
    grey(2);
    green(1);
    flesh(2);
    green(3);
    flesh(2);
    green(1);
    grey(1);
    flesh(4);
    nl(1);

    flesh(6);
    green(1);
    flesh(2);
    green(3);
    flesh(2);
    green(1);
    flesh(5);
    nl(1);

    flesh(4);
    green(10);
    green(2);
    flesh(4);
    nl(1);

    black(4);
    green(5);
    black(2);
    green(5);
    nl(1);

    black(2);
    grey(6);
    black(4);
    grey(6);
    nl(1);

    grey(8);
    black(4);
    grey(8);
    nl(1);
}

void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC&0x0F)<<4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),wColor);
     return;
}

void green(int c)
{
    SetColorAndBackground(10,0);
    for(z=0;z<c;z++)
    {
        printf("%c",y);
    }
}

void grey(int d)
{
    SetColorAndBackground(6,0);
    for(z=0;z<d;z++)
    {
        printf("%c",y);
    }
}

void flesh(int e)
{
    SetColorAndBackground(14,0);
    for(z=0;z<e;z++)
    {
        printf("%c",y);
    }
}

void black(int f)
{
    SetColorAndBackground(0,0);
    for(z=0;z<f;z++)
    {
        printf("%c",y);
    }
}

void red(int h)
{
    SetColorAndBackground(12,0);
    for(z=0;z<h;z++)
    {
        printf("%c",y);
    }
}

void nl(int g)
{
    for(z=0;z<g;z++)
    {
        printf("\n");
    }
}
_______________________________________
That's the code there. Try it out.

Saturday 25 May 2013

Let Us C: Matchstick Game

There is an exercise in Let us C, Chapter 3, Question C-f

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.

This is what I came up with. I know it is a lot of stuff for a simple question, but I enjoy tweaking stuff trying it make it a bit more 'joy giving' to me :D. I couldn't figure out my own program :O so i decided to sit down and comment it line by line, and as I'd hoped it reminded me how it does what it does.

The logic here is this:
Since the player always goes first, you must remove enough so that the sum of what you removed and the player removed is 5.
Player removes 4, you remove 1.
Player removes 3, you remove 2.
Player removes 2, you remove 3.
Player removes 1, you remove 4.

Following this simple rule, you always win.
If I remember correctly, I read in a book that this was a stunt that famed British TV Magician Paul Daniels used in his TV shows. He would do it with candy. Whoever had to pick up the last candy had to forfeit all his/her candy to the other (The winner was always the magician).

It looks very messy when pasted and posted here. Copy and paste the code into Code Blocks, it should look better. I tried it, and it looks just as it did originally & is a lot easier to comprehend.
Here is the code:



#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#define TRUE 1
#define FALSE !TRUE

int rmd=21,x,rmv,y=244,z=0,a,state,turns; //A. global variables are declared. rmd=21(number of matchsticks),x for loops,
                                            //rmv for number of sticks removed,y=244 for the matchstick ASCII character
                                            //z=0 for calculating win (see 15), a to calculate the number of sticks
                                            //the program will remove,state for TRUE FALSE loops,turns to store
                                            //number of turns taken

unsigned t;                             //B. t for pause loops. It stores upto 500 mil hence unsigned
void match1(void);      //1. this function processes user input
void match2(void);      //2. processes program output.
void SetColorAndBackground(int ForgC,int BackC);   //3. small function for colours.

main()
{
    do  //4. do this till there is only one matchstick remaining(variable rmd) see 14.
    {
        SetColorAndBackground(10,0); //5. text is set to green (10) and background remains at 0(black)
        state=TRUE;                    //6. This is required in function match1() later in the program
        system("cls");                 //7. Clears the screen using DOS cls command
        printf("Assume these are 21 matchsticks. Please remove 1 to 4 stick/s\n");
        printf("and I will do the same. The person who has to pick the last stick loses.\n");
        printf("\nStick/s Left %i \tTurns taken %i\n\n\n",rmd,turns);   //8. shows sticks left and turns taken rmd,turns

        for(x=0;x<rmd;x++)                  //9. prints the number of sticks remaining to the screen,
        {
            SetColorAndBackground(6,0);     //10. colour of the sticks is set to yellow(6)
            printf("%c\t",y);               //11. y has been declared as 244. This will print its ASCII character.
        }
        match1();   //12. Processes user input
        match2();      //13. processes program output.
    }

    while(rmd>1); //14. above 'do' runs till this condition is met

    z=z%2;         //15. when condition is met number of turns taken is divided by 2,
                    //if it is divisible(IE remainder will be zero stored in z)
                    //it was an even number of turns with one match remaining. Means the computer won
    if(z==0)    //16. The computer won.
    {
        SetColorAndBackground(10,0); //17. text colour is set to green again because it
                                        //has been set to yellow when printing the matchsticks (see 17.5)
        system("cls");
        printf("Assume these are 21 matchsticks. Please remove 1 to 4 stick/s\n");
        printf("and I will do the same. The person who has to pick the last stick loses.\n");
        printf("\nStick/s Left %i \tTurns taken %i\n\n\n",rmd,turns);

        for(x=0;x<rmd;x++)
        {
            SetColorAndBackground(6,0);         //17.5 Look here
            printf("%c\t",y);
        }
        SetColorAndBackground(12,0);    //18. The ending note is displayed in red(12)
        printf("\n\n\n\aYou lose. *NOTE* This game cannot be beaten. It was designed that way."); // 19. \a makes the computer beep
                                                                                                    //when the end note is displayed.
    }
    else                            //20. This part of the program is put here as a courtesy.
                                        //It will never run because the user will never win.
    {
        SetColorAndBackground(10,0);
        system("cls");
        printf("Assume these are 21 matchsticks. Please remove 1 to 4 stick/s\n");
        printf("and I will do the same. The person who has to pick the last stick loses.\n");
        printf("\nStick/s Left %i \tTurns taken %i\n\n\n",rmd,turns);

        for(x=0;x<rmd;x++)
        {
            SetColorAndBackground(6,0);
            printf("%c\t",y);
        }
        SetColorAndBackground(12,0);
        printf("\a\n\n\nYou Win!");
    }
}

void match1(void)                   //function to process user input
{
    SetColorAndBackground(10,0);       //text colour green (10)
    if(z==2 || z==4)                    //if number of turns is 2 or 4 a newline character is introduced
                                        //to prevent the prompt from appearing to go up one line as the
                                        //matchsticks dissapear
        {
            printf("\n");
        }
    else if(z==6)                       //if turns = 6 2 newlines are introduced for same reason as above.
        {
            printf("\n\n");
        }
    printf("\n\n\nPlease enter number of stick/s to remove: ");
    while(state)                    //Start of loop for user input
    {
        scanf(" %i",&rmv);          //scans user input
        if(rmv>=1 && rmv <=4)       //If users input is valid IE 1,2,3 or 4
        {
            state=FALSE;            //state is set to false and loop breaks
        }
        else                        //If users input is invalid
        {
            printf("You may only remove 1,2,3 or 4 sticks: ");
        }
    }
    printf("\nYou remove %i stick/s.",rmv); //shows user how many sticks s/he removed
    a=5-rmv;                                //a is the number of sticks the program will remove. We want the number of
                                            //sticks removed to always be 5 so that the program never loses.
    rmd=rmd-rmv;                            //rmd(remainder) stores the number of matchsticks remaining.
    z++;                                    //z(number of turns taken) is incremented by 1. We need this variable
                                            //even if we also store the number of turns in the 'turns' variable.
                                            //We need it to decide who won. See 15
}
void match2(void)
{
    printf("\t\tThe Computer removes: ");
    for(t=0;t<500000000;t++);               //computer counts to 500 million to provide a pause of about 1 second.
    printf(" %i stick/s",a);                //computer removes a to equal the # of sticks removed to 5
    rmd=rmd-a;                              //remainder of sticks is updated.
    for(t=0;t<500000000;t++);               //another pause so user sees what the program removed.
    z++;                                    //z(number of turns taken) is incremented by 1
    turns=z;                                //'turns' number of turns taken gets its value from z
                                            //since we will be using z to modolus the win. See 15.
}

void SetColorAndBackground(int ForgC, int BackC)    //small function for colours.
{
     WORD wColor=((BackC&0x0F)<<4)+(ForgC&0x0F);
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),wColor);
     return;
}



This uses the function for colours that I mentioned in my previous post. Besides that everything else is what I learnt from C For Dummies.



Change Console Text and Background Colours (A Stolen Colour Function)

About a week back I copied a function that allows me to change the text and background colours in the DOS window. I copied it from someone else's program when I was looking through some programs on the internet. Please understand I don't know how this works, at least not now, but maybe eventually I will. But it works, so there.

I modified it a bit to give me a list of colours with their numbers. I use it for reference to know which number is which colour. Here it is. Oh and I do everything in Code Blocks (It's a free IDE compiler) www.codeblocks.org. Started with Dev C++ but it crashed a lot, Code Blocks hasn't given me any hassles yet. I save the files with the .cpp extension. Now here is the code for "textcol.cpp":


//Please note the first line of output will be blank because both the text and background is 
//BLACK so it looks like a blank line.

#include <windows.h>
#include <stdio.h>

void SetColorAndBackground(int ForgC, int BackC);
int main()
{
    int x,y;
    y=176;
    for(x=0;x<16;)
    {
    SetColorAndBackground(x,0);
    printf("%3i. Colour %c\n",x,y);
    x++;
    }
}
void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC & 0x0F)<< 4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}

_______________________________________________________________________
If we include the following in our code:

#include <windows.h>
void SetColorAndBackground(int ForgC, int BackC);

void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC & 0x0F)<< 4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}


we can say:


SetColorAndBackground(x,y);

Where x is the text colour and y is the background colour (get the numbers from "Textcol.cpp"). Any text printed after that line will have the colour attributes you set in x & y.

The original code can be found here:
http://codeincodeblock.blogspot.in/2011/03/text-background-color-of-console.html


Start

With too much time on my hands, there was this book I had bought in the mid nineties; it's called "C For Dummies", started reading it.

Flipping through it I thought maybe I could do some of the things in there.
It took me about a month or 2 to finish it.

I found 2 other C books here and there, they are pretty old, but I intend to work through them.

I have a friend who runs a shop selling Traditional Attire (Nagaland). When he found out I'm working on C, he asked me if I could write him a program that will manage his shop inventory and books.
I guess that is still a while away, because I'm nowhere near writing anything close to a database program lol.

But now I guess I have my first goal: to write a program for him.

Here are the 3 books I am working through:
1. C For Dummies (1994) Vol 1. Dan Gookin, IDG Books. Vol 2 hadn't come out yet. I have
                                                                                  finished this book, but do need it for
                                                                                  reference as I write my noob
                                                                                  programs.

2. Let Us C (2002) 4th Edition, Yashavant Kanetkar. At chapter 5, about to learn
                                                                                  pointers. So far the first few
                                                                                  chapters haven't taught me anything
                                                                                  I didn't know from C for Dummies.

3. Programming With C (1991) Byron S. Gottfried. This book is a bit difficult for me to
                                                                                  comprehend, so I'm saving it for
                                                                                  later.


Yeah they are pretty old, but lets see how far I get, besides I also have one of the biggest knowledge resource at my disposal (the internet). I'll post some of the programs I have written and will write on this blog.

The primary intent is to have a place I can look back to and maybe note my progress.
This is my first attempt at blogging and also programming, so go easy on me :P