Sunday, April 30, 2017

C Program for creating animated circles

Graphics in C – Program to Generate Animated Circles


.Generating animation in C programming language is very interesting Here is one more program in C computer language using animation. This program generates ten concentric circles bit by bit. To clear the point, please type this program in your editor.

#include<graphics.h>
#include<stdlib.h>
#include<time.h>
void main()
{
        int gd = DETECT, gm;
        int i, j, start = 0, end = 5;
        int maxx, maxy, rad = 20;
        initgraph(&gd, &gm, "c:\\tc\\bgi");
        maxx = getmaxx();
        maxy = getmaxy();
        randomize();
        for(i = 0; i < 10; i++)
        {
                setcolor(random(15) + 1);
                for(j = 0; j <= 360; j+=5)
                {
                       arc(maxx/2, maxy/2, start, end, rad);
                       delay(40);
                       start = end;
                       end += 5;
                }
                rad += 20;
        }
        setcolor(WHITE);
        outtextxy(maxx/2-50, maxy-20, "Press any key...");
        getch();
        closegraph();
        restorecrtmode();
}

Compile and execute this program. You will see ten concentric circles completing the circumference slowly and one by one in different colors. One circle completes then other starts. In this manner, ten concentric circles have been created completing slowly in the outward direction.

In this program, I have taken two nested ‘for’ loops. Outer ‘for’ loop iterates ten times, hence creates ten circles. Inner ‘for’ loop is responsible for creating animation effect.

In the start, outer ‘for’ loop picks a random value for the color, and sets that color.

In the inner ‘for’ loop, loop variable starts from the value ‘0’ and iterates until its value reaches ‘360 degrees’. It is because of the fact that a point on the circumference of a circle moves 360 degrees, while returning on the same point after completing the circle. This variable is incremented ‘5’ after each iteration. Function arc() draws an arc of ‘5’ degrees in each iteration. Then, variable ‘start’ is given the value of variable ‘end’, and ‘end’ is incremented ‘5’ degrees. This way, circle completes bit by bit. Function delay() has been used to give a delay of  ‘40’ milliseconds after every arc of 5 degrees, thus giving the effect of animation. After each iteration, variable ‘rad’(radius of the circle) is incremented ’20 px’ for forming a bigger  circle. Please note that the coordinates of the centers of the circles do not change, thus forming concentric circles.


So, this is a very simple program  giving great effect. For the explanation of the functions and terms I have used in this program, please refer my previous posts.

OUTPUT:

Sunday, April 23, 2017

C Program for moving a ball on screen

Graphics in C – Program for Moving a Ball on Screen


Here is a simple graphics program in C computer language, which demonstrates the animation of a moving ball. This ball changes its direction and color when it reaches and touches a boundary. Actually, ball does not move. New graphic of the ball is being generated, and old graphic of the ball is being erased continuously, thus giving the illusion of motion. To clear the point, please type this program in your editor.

#include<graphics.h>
#include<stdlib.h>
#include<time.h>
#include<conio.h>
#include<dos.h>
void main()
{
        int gd = DETECT, gm;
        int x, y, maxx, maxy;
        int xdir = 1, ydir = 1;
        int color = 1;
        initgraph(&gd, &gm, "c:\\tc\\bgi");
        maxx = getmaxx();
        maxy = getmaxy();
        x = 25;
        y = 45;
        randomize();
        while(!kbhit())
        {
                cleardevice();
                rectangle(0, 20, maxx, maxy-20);
                outtextxy(maxx/2-80, 0, "Moving Ball");
                outtextxy(maxx/2-80, maxy-15, "Press any key to exit...");
                setcolor(WHITE);
                setfillstyle(SOLID_FILL, color);
                circle(x, y, 25);
                floodfill(x, y, WHITE);
                delay(40);
                x = x + (xdir * 5);
                y = y + (ydir * 5);
                if(x >= maxx - 25 || x <= 25)
                {
                       xdir *= -1;
                       color = random(15) + 1;
                }
                if(y >= maxy - 45 || y <= 45)
                {
                       ydir *= -1;
                       color = random(15) + 1;
                }
        }
        closegraph();
        restorecrtmode();
}

Compile and execute this program. In the output, there is a moving ball, which changes its color and direction whenever it touches any boundary. It moves inside a rectangular area.

In the given program I have declared two integer type variables ‘xdir’ and ‘ydir’ and initialized with the value ‘1’, two integer type variables ‘x’ and ‘y’, and given the initial value ‘25’, and ‘45’, an integer type variable ‘color’ with initial value ‘1’.

I have found maximum screen coordinates with these statements.

maxx = getmaxx();
maxy = getmaxy();

I initialized a random number generator with an initial random value.

randomize();

I started a ‘while’ loop. The statements in this loop will be executed endlessly till the user presses any key on the keyboard.

while(!kbhit())
{
    …
    …
    …
}

Function kbhit() checks to see if a keystroke is currently available. If a key is pressed, it returns a non-zero integer. If a key is not pressed, it returns ‘0’.

Declaration:

int kbhit(void);

Syntax for calling this function is:

kbhit();

Therefore, !kbhit() will evaluate to ‘1’, if a key is not pressed, and while loop will remain true. If a key is pressed, !kbhit() will evaluate to ‘0’, while loop becomes false, and terminates. For function kbhit(), file “dos.h” should be included.

In the while loop, function cleardevice() will clear the screen every time the loop executes, and function rectangle() will draw the boundary walls for the moving ball.

cleardevice();
rectangle(0, 20, maxx, maxy-20);

Function outtextxy() has been used to display appropriate messages on the screen.

outtextxy(maxx/2-80, 0, "Moving Ball");
outtextxy(maxx/2-80, maxy-15, "Press any key to exit...");

Function setfillstyle() has been used to set the color and fill style of the ball,  function circle() for drawing a circle, and function floodfill() for filling the color in the circle or ball.

setfillstyle(SOLID_FILL, color);
circle(x, y, 25);
floodfill(x, y, WHITE);

In the function setfillstyle(), second argument is ‘color’, which is a variable, and has been given an initial value ‘1’ (enumerated value for blue color), then its value will be picked randomly during the execution of an ‘if’ construct, which checks whether the ball touches the boundary wall or not. If touches, then value between ‘1’ and ‘15’ will be given to the ‘color’ variable. This way, ball changes its color after touching and bouncing back the boundary.

if(x >= maxx - 25 || x <= 25)
{
       xdir *= -1;
       color = random(15) + 1;
 }
if(y >= maxy - 45 || y <= 45)
{
       ydir *= -1;
       color = random(15) + 1;
 }

I have added ‘1’ in the random number, because I don’t want to give the value ‘0’ to ‘color’, which is the color code for black color. What is the meaning of statements xdir *= -1,  ydir *= -1, I’ll explain later on.

For smooth movement of ball, I have used the function delay(), and given the delay of 40 milliseconds. To change the position of ball, I have incremented or decremented the values of coordinates of the center of the  ball (x, y).

delay(40);
x = x + (xdir * 5);
y = y + (ydir * 5);

Function delay() suspends the execution of the current program for the time specified in milliseconds. 

Declaration:

void delay(unsigned milliseconds);

Syntax for calling this function is:

delay(milliseconds);

For function delay(), file “conio.h” should be included.

When ‘xdir’ and/or  ‘ydir’ are having the value ‘1’, value(s) of ‘x’ and/or ‘y’ will be incremented by 5px in every iteration of ‘while’ loop. If either ‘xdir’ or ‘ydir’ or both has the value ‘-1’, as changed by ‘if’ construct, value of ‘x’ or ‘y’ or both will be decremented by 5px.

In the ‘if’ construct, the statement xdir *= -1 implies that if ball touches any of the boundary wall, the value of ‘xdir’ will change to ‘-1’, if it has the value ‘+1’, and will change to ‘+1’, if it has ‘-1’ previously. Same way, statement ydir *= -1 can be explained. This way, ball changes the direction of its movement.

So this, a very simple program, is now well explained. You can find the explanation of all the functions and terms, which I have not explained here, in my previous posts.

   


Sunday, April 16, 2017

C Program to generate captcha code

Graphics in C - Program to Generate Captcha Code


Here is an interesting graphics program in C computer language for generating ‘captcha’ code. Please type this program in your editor.

#include<graphics.h>
#include<stdlib.h>
#include<time.h>
void main()
{
          int gd = DETECT, gm, i, n;
          char str[10], str1[20], ch;
          initgraph(&gd, &gm, "c:\\tc\\bgi");
          randomize();
          while(1)
          {
                cleardevice();
                clrscr();
                settextstyle(BOLD_FONT, HORIZ_DIR, 2);
                setcolor(RED);
                rectangle(10, 40, 250, 130);
                for(i = 0; i < 8; i++)
                {
                        n = random(3);
                        if(n == 0)
                                   str[i] = 65 + random(26);
                        else if(n == 1)
                                   str[i] = 97 + random(26);
                        else if(n == 2)
                                   str[i] = 48 + random(10);
                     }
                     str[i] = '\0';
                     outtextxy(20, 60, str);
                     puts("Enter the captcha code:");
                     gets(str1);
                     settextstyle(SANS_SERIF_FONT, HORIZ_DIR, 2);
                     setcolor(BLUE);
                     if(strcmp(str, str1) == 0)
                                outtextxy(20, 150, "Right code!");
                     else
                                outtextxy(20, 150, "Wrong code!");
                     settextstyle(DEFAULT_FONT, HORIZ_DIR, 1);
                     setcolor(BLUE);
                     outtextxy(20, 230, "Press any key to change the code…");
                     outtextxy(20, 260, "Press <esc> to exit…");
                     ch = getch();
                     if(ch == 27)
                                  break;
          }
          closegraph();
          restorecrtmode();
}

Compile and execute the program. Output would be a screen displaying a ‘captcha’ code, and you would be prompted to enter this code. If you enter the right code, a message ‘Right Code!’ will appear on the screen. If you enter the wrong code, message ‘Wrong Code!’ will be displayed. You can change the ‘captcha’ code by pressing any key. You can terminate the program by pressing the <esc> key. For this, appropriate messages have been displayed on the screen.

In the program, firstly, I have used a macro randomize(). This will initialise a random number generator with a random value. For this macro, I have included the header file “time.h”.

randomize();

After this, I have taken a ‘while true’ loop. This loop would be executed endlessly, until it is terminated by a ‘break’ statement. User is prompted to enter the <esc> key to terminate the program. The ASCII value for <esc> key is 27. An ‘if’ construct checks whether the ASCII value of the key pressed is 27. If true, program comes out of the ‘while true’ loop, executes the remaining instructions, and then terminates.

Inside the ‘while true’ loop, function cleardevice() clears the screen in graphics mode, function clrscr() clears the screen in text mode. I have used this function, because there are some input/output functions of text mode in the program. Then, set the text style, colour, etc. and draw a rectangle to enclose the ‘captcha’ code.

settextstyle(BOLD_FONT, HORIZ_DIR, 2);
setcolor(RED);
rectangle(10, 40, 250, 130);

A ‘for’ loop has been taken to generate the ‘captcha’ code. This loop executes eight times. In every iteration, a random number among 0, 1, and 2 is generated and stored in the variable ‘n’. Depending on the value of ‘n’, a string is populated with alphabets and digits. In the first iteration of the ‘for’ loop, ‘n’ is given a random value between 0 and 2. If value is picked 0, then, first element of the string would be a capital letter from A to Z. ASCII  value of A is 65, and number of alphabets is 26. Thus, (65 + a random number between 0 and 25) would give the ASCII value of a capital letter. The same way, if the value of ‘n’ is picked 1, then, the first element of the string would be an alphabet in lower case, because ASCII value of ‘a’ is 97. If the value of ‘n’ is picked 2, then, the first element of the string would be a digit between 0 and 9 (ASCII value of ‘0’ is 48). I have taken 3 random values for this purpose, because there are 3 types of characters are to be filled in a string of ‘captcha’ code, namely upper-case alphabets, lower-case alphabets, and numeric digits. You can give different order for these characters in the ‘if’ construct. After giving 8 characters by ‘for’ loop, a null character(‘\0’) has been inserted into the string. It is necessary to place a null character(‘\0’) into the string in the last to mark its end. Then the string is being displayed using function outtextxy().

for(i = 0; i < 8; i++)
{
           n = random(3);
           if(n == 0)
                      str[i] = 65 + random(26);
           else if(n == 1)
                       str[i] = 97 + random(26);
            else if(n == 2)
                       str[i] = 48 + random(10);
}
str[i] = '\0';
outtextxy(20, 60, str);

Then, user is being prompted to enter the ‘captcha’ code by using two string functions puts() and gets(). Function puts() displays the specified string, and function gets() takes the input from the keyboard into the specified string variable.

puts("Enter the captcha code:");
gets(str1);

After this, the two strings, ‘str’ and ‘str1’, having the program generated ‘captcha’ code and the user entered ‘captcha’ code, are compared. If both strings are same, message ‘Right Code!’ is displayed, otherwise message ‘Wrong Code!’ will appear on the screen.

if(strcmp(str, str1) == 0)
          outtextxy(20, 150, "Right code!");
else
          outtextxy(20, 150, "Wrong code!");

Therefore, this way, you can implement ‘captcha’ code in your program to check whether user of your application is a human or not.

So, this simple C language program is now well explained. For the functions and terms not explained in this post, please refer my previous posts.

OUTPUT: