Wednesday, April 17, 2013

Create and search record of student details using structure

Record is collection of data items of different data types.In this program,a record is created using structure.Structure stud is created which stores student details such as roll no,name and marks.The structure stud can save 50 records.In the search functionality,specific record can be searched using roll no.

#include < stdio.h >
#include < conio.h >
struct stud
{
int roll;
char name[15];
int marks;
};
void main()
{
    struct stud a[50];
    int n,reply,sroll,option,i;   
    clrscr();
    do
    {
        printf("\n 1. Create records");
        printf("\n 2. Search record");
        printf("\n 3. exit");
        printf("\n\n Select proper option :");
        scanf("%d",&option);
        switch(option)
        {
        case 1 : // create
            printf("\nEnter n : ");
            scanf("%d",&n);
            read_data(a,n);
            break;       
        case 2 : // search
            printf("\nEnter sroll : ");
            scanf("%d",&sroll);
            reply = search_data(a,n,sroll);
            if( reply == -1)
                printf("\n Not found");
            else
            {
                printf("\nRoll\tName\tMarks");
                printf("\n%d\t%s\t%d",a[reply].roll,a[reply].name,a[reply].marks);
            }
            break;
        case 3 : exit(0);
        } //swith
    }while(1);
} // main

int read_data(struct stud a[], int n)
{
    int i;
    printf("\nEnter %d records\n",n);
    for(i=0;i < n;i++)
    {
        printf("\nRoll : "); scanf("%d",&a[i].roll);
        printf("\nName : "); flushall(); scanf("%s",a[i].name);
        printf("\nMarks : "); scanf("%d",&a[i].marks);
    } // for
    return;
} // read data

int search_data( struct stud a[], int n , int sroll)
{
    int i;
    for(i=0;i < n;i++)
    {
        if( a[i].roll == sroll)
        return(i);
    }//for
    return(-1);
}

Check binary tree

A tree is called binary tree if each node contains zero,one or two sub-trees.In this program,tree is first created.Then the function check_complete,checks every node recursively.Each node is parsed till it reaches NULL.If both the left child and right child are NULL then it is called binary tree.

#include < stdio.h >
#include < conio.h >
#include < alloc.h >
#define new_node (struct node*)malloc(sizeof (struct node))

struct node
{
    int data;
    struct node *lc;
    struct node *rc;
};
struct node *create_bin_pre_rec();

void main()
{
    struct node *r;
    int reply;   
    clrscr();
    printf("\nCreate a binary tree \n");
    r = create_bin_pre_rec();   
    printf("\n The binary tree is \n");
    print_bin_pre_rec(r);
    reply = check_complete(r);
    if( reply == 1 )
        printf("\n Complete tree ");
    else
        printf("\n Not complete tree ");
}

struct node *create_bin_pre_rec()
{
    struct node *c;
    int data;
    printf("\nData : ");
    scanf("%d",&data);
    if( data == -1)
        return(NULL);
    else
    {
        c = new_node;
        c->data = data;
        c->lc = create_bin_pre_rec();
        c->rc = create_bin_pre_rec();
        return(c);
    }
} // create

int print_bin_pre_rec(struct node *t)
{
    if( t != NULL)
    {
        printf("%4d",t->data);
        print_bin_pre_rec(t->lc);
        print_bin_pre_rec(t->rc);
    }//if
    return;
} // print

int check_complete(struct node *t)
{
    int reply;
    if( t == NULL)
        return(1);
    else
        if( t->lc == NULL && t->rc == NULL)
            return(1);
        else
            if( t->lc != NULL && t->rc == NULL)
                return(0);
            else
            if( t->lc == NULL && t->rc != NULL)
                return(0);
            else
            {
                reply = check_complete(t->lc);
                if ( reply == 1 )
                    reply = check_complete(t->rc);
                    return(reply);
    } // else
} // check complete

Sort n values using quick sort method

Suppose n different values are stored in numeric array a from the location 0 to n-1.Consider a dummy value which is largest among all input values. Place this dummy value at the n+1 location i.e. logical position a[n].In short place this dummy value after the last input value.The dummy value is used for sorting as follows -
1. a[n]=dummy value
2. Consider two indices l(low) and h(high).Initialize l to 0 and h to n-1.
3. If the lower limit is less than the higher limit then do the following -
    a. Consider temporary variable k.Copy the content of the position l i.e. a[l] into k.Here k acts as a reference value for creating two partitions.
    b. Consider two indices i and j.Initialize i to lower limit l and j to higher limit h+1.
    c. While i < j do the following
        i. While value of a[i] is less than or equal to k and i is less than h,increment i.
        ii. While value of a[j] is greater than or equal to k and j is greater than l ,decrement j.
        iii. If i is less than j ,then swap the values of a[i] and a[j].
    d. If j is not equal to l ,then swap the values of a[j] and a[l].
    e. After swapping a[l] and a[j],two partitions are created.First partition is from l to j-1 and second partition is from j+1 to h.
4. Use the steps from 2 to 3 for each partition till no more partition is possible.
5. After creating all the partitions , the input values are sorted automatically.

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

void main()
{
    int a[50];
    int n;
    clrscr();
    printf("\nEnter n: ");
    scanf("%d",&n);
    read_data(a,n);
    a[n]=9999;
    printf("\nBefore sort :");
    print_data(a,n);
    qsort(a,0,n-1,n);
    printf("\nAfter sort :");
    print_data(a,n);
}

int read_data(int a[],int max)
{
    int i;
    printf("\nEnter %d values \n",max);
    for(i=0; i < max; i++)
    {
        scanf("%d",&a[i]);
    }
    return;
}

int print_data(int a[],int max)
{
    int i;
    for(i=0; i < max; i++)
    {
        printf("%4d",a[i]);
    }
    return;
}

int quick_sort(int a[],int l,int h,int n)
{
    int i,j,k,t;
    if(l < h)
    {
        k=a[l];
        i=l;
        j=h+1;
        while( i < j)
        {
            while( i < h && a[i] <= k)
                i++;

            while( j > l && a[j] > =k)
                j--;

            if( i < j)
            {
                  t=a[i];
                  a[i]=a[j];
                  a[j]=t;
            }
        }
        if( l != j)
        {
            t=a[l];
            a[l]=a[j];
            a[j]=t;
        }
        printf("\nOutput :");
        print_data(a,n);
        qsort(a,l,j-1,n);
        qsort(a,j+1,h,n);
    }
    //print_data(a,n);
    return;
}

Sort structure type array using bubble sort

This program sorts the structure type array using bubble sort method.In bubble sorting,every value of the array is compared sequentially and temporary variable t is used for sorting the values.Here the student details are stored in the struture type array and it is sorted by percentage using bubble sort method.The percentage value is used in bubble sort method for sorting the structure type array.
-Initially,n different values are placed in constant array with sufficient large size.
-Here,the comparison starts from bottom position(0) and in each iteration the smallest bubble is shifted upward..
-Each comparison starts from bottom position by using the values from 2 positions (0 and 1). After comparision the smallest value is placed in position 1.Then the values from next 2 positions (1 and 2) are used.After comparison the smallest value is placed in position 2.This process continous in upward direction.
-In first iteration,the smallest value is placed in position (n-1).
-In second iteration,the smallest value is placed in position (n-2).
-In third iteration,the smallest value is placed in position (n-3).
-In last iteration,the last smallest value is placed at n th position i.e. at the bottom.
//... C Language Program to Sort a Struct type Array by using a Bubble Sort method
#include < stdio.h >
#include < conio.h >

struct stud
{
    int roll;
    char name[15];
    float per;
};

void main()
{
    struct stud a[50], t;
    int i, j, n;

    clrscr();

    printf("\n C Language Program to Sort Struct type Array by using a Bubble Sort method ");
    printf("\n To sort the Student Records in Dercreasing Order of % (Percentage) \n");
    printf("\n Enter How Many Records [ i.e. Size of Array (n) ] : ");
    scanf("%d", &n);
    read_data(a, n);

    printf("\n %d Records Before Sorting are \n", n);
    print_data(a, n);

    bbl_sort(a, n);

    printf("\n %d Values After Sorting are \n", n);
    print_data(a, n);

} // main

int read_data( struct stud a[], int n )
{
    int i;
    float t;

    printf("\n Enter %d Records \n", n);
    for(i = 0; i < n; i++)
    {
        printf("\n Roll No. : ");
        scanf("%d", &a[i].roll);
        printf("\n Name : ");
        flushall();
        gets(a[i].name);
        printf("\n Percentage (%) : ");
        scanf("%f", &t);
        a[i].per = t;
    } // for
    return;
} // read_data

int print_data( struct stud a[], int n )
{
    int i;
    float t;

    printf("\n Roll No. \t Name \t Percentage (%) \n");
    for(i = 0; i < n; i++)
    {
        printf("\n \t %d \t %s \t %.2f", a[i].roll, a[i].name, a[i].per);
    } // for
    return;
} // print_data

int bbl_sort( struct stud a[], int n )
{
    int i,j, k;
    struct stud t;

    for(k = n - 1; k >= 1; k--)
    {
        for(i = 0,j = 1; j <= k; i++,j++)
        {
            if( a[i].per > a[j].per)
            {
                t = a[i];
                a[i] = a[j];
                a[j] = t;
            } // if
        } // for
    } // for
    return;
} // bbl_sort

Sort structure type using insertion sort method

In this case,the input is sorted while reading and placing it in the array.In all other methods,all input values are placed in array before applying the actual sorting procedure.But here ,the values are sorted while reading them from console.Here the student details are accepted as input and stored in structure type array.Then it is sorted as per the value of the percentage.
Basic steps are as follows -
-Read a value form console.
-In order to place it in given array find its position in such a way that after its insertion the resultant data must be in sorted order.
-For this purpose,start shifting the values from bottom of the array downward by one position till getting a proper position.
-Insert a new value after getting its proper position.


//... C Language Program to sort the Student Records by using an Insertion Sort method

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

struct stud
{
    int roll;
    char name[15];
    float per;
};

void main()
{
    struct stud a[50], t;
    int n;

    clrscr();

    printf("\n C Language Program to sort the Student Records by using Insertion Sort method ");
    printf("\n To sort the Student Records in Dercreasing Order of % (Percentage) \n");

    printf("\n Enter How Many Records [ i.e. Size of Array (n) ] : ");
    scanf("%d", &n);

    insrtn_srt(a, n);

    printf("\n %d Values After Sorting are \n", n);
    print_data(a, n);

} // main

int print_data( struct stud a[], int n )
{
    int i;

    printf("\n Roll No. \t Name \t Percentage (%) \n");
    for(i = n - 1; i >= 0; i--)
            printf("\n \t %d \t %s \t %0.2f", a[i].roll, a[i].name, a[i].per);
    return;
} // print_data

int insrtn_srt( struct stud a[], int n )
{
    int i, j, bottom;
    struct stud t;

    bottom = -1;
    for(j = 0; j < n; j++)
    {
        printf("\n Roll Number : ");
        scanf("%d", &t.roll);
        printf("\n Name : ");
        flushall();
        scanf("%s", t.name);
        printf("\n Percentage (%) : ");
        scanf("%f", &t.per);
        i = bottom;
        while( a[i].per > t.per && i != -1)
        {
            a[i+1] = a[i];
            i--;
        } // while
        a[i+1] = t;
        bottom++;
    } // for
    return;
} // insrtn_srt

Draw shapes using graphics

This program shows how to draw different shapes using graphics.First the graphics is initialized.Then the generic functions are used to draw different shapes.

#include < graphics.h >
#include < stdlib.h >
#include < stdio.h >
#include < conio.h >

void main()
{
    /* initialization of graphics */
    InitGraphics();
   
    outtextxy(200, 10, "* Draw Shapes using Graphics *");
   
    /* draw circle */
    // DrawShape(1);
   
    /* draw arc */
    DrawShape(2);
   
    /* draw rectangle */
    DrawShape(3);
   
    /* draw pie slice */
    DrawShape(4);
   
    outtextxy(200, 400, "* Press any key to exit *");
   
    /* clean up */
    getch();
    closegraph();
    }
   
    /* This function initialize graphics */
    InitGraphics()
    {
    /* request auto detection */
    int gdriver = DETECT, gmode, errorcode;
   
    /* initialize graphics and local variables */
    initgraph(&gdriver, &gmode, "");
   
    /* read result of initialization */
    errorcode = graphresult();
   
    /* an error occurred */
    if (errorcode != grOk)
    {
    printf("Graphics error: %s\n", grapherrormsg(errorcode));
    printf("Press any key to halt:");
    getch();
    exit(1);/* terminate with an error code */
    }
    }
   
    /* This is generic function which draws different shapes */
    DrawShape(int shape)
    {
    switch(shape)
    {
    case 1:
    /* draw the circle */
    outtextxy(75, 40, "Circle");
    circle(100, 100, 50);
    break;
   
    case 2:
    /* draw arc */
    outtextxy(235, 40, "Arc");
    arc(250, 100, 0, 180, 50);
    break;
   
    case 3:
    /* draw a rectangle */
    outtextxy(350, 40, "Rectangle");
    rectangle(350,50,450,150);
    break;
   
    case 4:
    /* set fill style and draw a pie slice */
    outtextxy(100, 190, "Pie Slice");
    setfillstyle(EMPTY_FILL, getmaxcolor());
    pieslice(100, 250, 0, 0, 50);
    break;
    }
}

Find the occurrence of given substring in given string

This program is executed from the dos shell.Input is given in the form of parameter.Two parameters are accepted as input and stored in argv.These values are then passed to variables m,c and i. The location of the substring is searched and then printed.

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

void main(int argc,char *argv[])
{
    char *i,*m,*c;
    clrscr();
    if ( argc != 3)
    {
        printf("\n Invalid arguments ");
        exit(0);
    }
    else
    {
        m=c=argv[1];
        i=argv[2];
        while(*c!='\0')
        {
            if (*m == *i)
            {
                m++;
                i++;
                if (*i=='\0')
                {
                    printf("%4d",c-argv[1] +1);
                    c=m;
                    i=argv[2];
                }
            }
            else
            {
                c++;
                m=c;
                i=argv[2];
            }
        }
    }
} // main

Convert an infix expression to postfix expression

This program shows how to convert an infix expression to postfix expression.An infix expression is accepted as input.The expression is pushed into the stack character by character.While pushing the expression,it is pushed as per the priority of the operants.Finally,when the expression is poped out of the stack,it gets converted into postfix expression.

#include
#include
#define max 50

void main()
{
   char exp[100],opt_stk[max],ch;
   int opt_top,i;
   clrscr();
   opt_top=-1;
   printf("\nEnter an infix exp \n");
   gets(exp);
   //Process the expression by taking one token(symbol) at a time
   for(i=0;exp[i]!='\0';i++)
   {
    if (exp[i]=='(')
    {
        push_opt(opt_stk,&opt_top,&exp[i]);
    }
    else if (exp[i]==')')
    {
        //while opt stk top operator is not an openeing
        //bracket pop an operator and print it on screen
        while(opt_stk[opt_top]!= '(')
        {
            pop_opt(opt_stk,&opt_top,&ch);
            printf("%c",ch);
        }
        pop_opt(opt_stk,&opt_top,&ch); //skip '('
    }
    else
    if (chk_opt(exp[i])==0) //current token is an operand
        printf("%c",exp[i]);
    else //current token is an operator
    {
        if(opt_top==-1)  //opt stack is empty
        {
            push_opt(opt_stk,&opt_top,&exp[i]);
        }
        else
        if (priority(exp[i]) > priority(opt_stk[opt_top]))
        {
            push_opt(opt_stk,&opt_top,&exp[i]);
        }
        else
        {
            while (priority (exp[i])<=priority(opt_stk[opt_top]))
            {
                if (opt_top == -1)
                    break;
                pop_opt(opt_stk,&opt_top,&ch);
                printf("%c",ch);
            }//while
            push_opt(opt_stk,&opt_top,&exp[i]);
        }//else
    }//else
   }//for
   while(opt_top!=-1)
   {
    pop_opt(opt_stk,&opt_top,&ch);
    printf("%c",ch);
   }//while
}//main

//check whether given character is an operator or not
//Return 1 if an operator else return 0
int chk_opt(char ch)
{
    switch(ch)
    {
        case '^':
        case '*':
        case '/':
        case '%':
        case '+':
        case '-': return(1);
        default : return(0);
    }//switch
}//chk_opt

//Return a priority of specific operator if a valid operator elese return 0
int priority (char opt)
{
    switch(opt)
    {
        case '^' : return(4);
        case '*' :
        case '/' :
        case '%' : return(3);
        case '+' :
        case '-' :return(2);
        case '(' : return(1);
        default : return (0);
    }//switch
}//priority

//Push an operator(ch) in opt_stack
int push_opt(char opt_stk[max],int *opt_top,char *ch)
{
    if(*opt_top==max-1)
    {
        return(-1);
    }
    else
    {
        (*opt_top)++;
        opt_stk[*opt_top]=*ch;
        return(1);
    }
}
//Pop an operator(ch) in opt_stack
int pop_opt(char opt_stk[max],int *opt_top,char *ch)
{
    if (*opt_top==-1)
    {
        return(-1);
    }
    else
    {
        *ch=opt_stk[*opt_top];
        (*opt_top)--;
        return(1);
    }

www.cprograms.in
www.cprograms.in

Saturday, April 6, 2013

cos in c - math.h

Cos function returns cosine of an angle(in radian).
1 radian = 57.2958(approximately).
Declaration: double cos(double);

C programming code

#include <stdio.h>
#include <math.h>
 
int main()
{
  double result, x = 1.0471;
 
  result = cos(x);
 
  printf("cos(%.4lf) = %.2lf\n", x, result);
 
  return 0;
}
Compiler used: 
GCC
Output of program: 
cos

abs c - math.h

abs is not a function but is a macro and is used for calculating absolute value of a number.

C programming code for abs

#include <stdio.h>
#include <math.h>
 
int main()
{
  int n, result;
 
  printf("Enter an integer to calculate it's absolute value\n");
  scanf("%d", &n);
 
  result = abs(n);
 
  printf("Absolute value of %d = %d\n", n, result);
 
  return 0;
}
You can implement you own function as follows:
long absolute(long value) {
  if (value < 0) {
    return -value;
  }
  else {
    return value;  
  }
}

sqrt function

sqrt function returns square root of a number.
Declaration :- double sqrt(double);

C programming code for sqrt

#include <stdio.h>
#include <math.h>
 
int main()
{
 
  double n, result;
 
  printf("Enter a number to calculate it's square root\n");
  scanf("%lf", &n);
 
  result = sqrt(n);
 
  printf("Square root of %.2lf = %.2lf\n", n, result);
 
  return 0;
}
Compiler used: 
GCC
AttachmentSize
sqrt.png4.53 KB

log10

log10 function returns common logarithm (base is 10) of a number.
Declaration :- double log10(double number);

C programming code for log10

#include <stdio.h>
#include <math.h>
 
int main()
{
  double n, result;
 
  printf("Enter a number to calculate it's log(base is 10)\n");
  scanf("%lf", &n);
 
  result = log10(n);
 
  printf("Common log of %.2lf = %.2lf\n", n, result);
 
  return 0;
}
Compiler used: 
GCC
Output of program:

pow10 function

#include<stdio.h>
#include<math.h>
 
main()
{
   int x = 5;
   double result;
 
   result = pow10(x);
 
   printf("Ten raised to %d is %lf\n", x, result);
 
   return 0;
}

sin function in c

Sin function returns sine of an angle(in radian).
Declaration: double sin(double);

C programming code

#include <stdio.h>
#include <math.h>
 
int main()
{
  double result, x = M_PI/6;
 
  result = sin(x);
 
  printf("The sin(%lf) = %.2lf\n", x, result);
 
  return 0;
}
Compiler used: 
GCC
Output of program:

textbackground in c

textbackground function is used to change of current background color in text mode. See available colors.
Declaration : void textbackground(int color);

C programming code for textbackground

#include<stdio.h>
#include<conio.h>
 
main()
{
   textbackground(RED);
 
   cprintf("C program to change background color.");
 
   getch();
   return 0;
}
Output: 
background color

textcolor in c

textcolor function is used to change the color of drawing text in c programs.
Declaration :- void textcolor(int color);
where color is an integer variable. For example 0 means BLACK color, 1 means BLUE, 2 means GREEN and soon. You can also use write appropriate color instead of integer. For example you can write textcolor(YELLOW); to change text color to YELLOW. But use colors in capital letters only.

C programming code to change text color

#include<stdio.h>
#include<conio.h>
 
main()
{
   textcolor(RED);
   cprintf("C programming");
 
   getch();
   return 0;
}

C programming code for blinking text

#include<stdio.h>
#include<conio.h>
 
main()
{
   textcolor(MAGENTA+BLINK);
   cprintf("C programming");
 
   getch();
   return 0;
}
Note that we have used cprintf function instead of printf. This is because cprintf send formatted output to text window on screen and printf sends it to stdin.

wherey in c

wherey function return current vertical cursor position.
Declaration :- int wherey();

C programming code for wherey

#include<stdio.h>
#include<conio.h>
 
main()
{
   int y;
 
   printf("Hello\n");
 
   y = wherey();
 
   printf("Vertical cursor position from where this text appears = %d",y);
 
   getch();
   return 0;
}

wherex in c

wherex function return current horizontal cursor position.
Declaration :- int wherex();

C programming code for wherex

#include<stdio.h>
#include<conio.h>
 
main()
{
   int x;
 
   printf("Hello");
 
   x = wherex();
 
   printf("Horizontal cursor position from where this text appears = %d\n",x);
 
   getch();
   return 0;
}

kbhit in c

kbhit in c: kbhit function is used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file "conio.h". If a key has been pressed then it returns a non zero value otherwise returns zero.
Declaration : int kbhit();

C programming code for kbhit

#include <stdio.h>
#include <conio.h>
 
main()
{
   while (!kbhit())
      printf("You haven't pressed a key.\n");
 
   return 0;
}
As long as in the above program user doesn't presses a key kbhit() return zero and (!0) i.e. 1 the condition in while loop is true and "You haven't pressed a key." will be printed again and again. As a key is pressed from the keyboard the condition in while loop become false as now kbhit() will return a non-zero value and ( !(non-zero) = 0), so the control will come out of the while loop.

gotoxy in c

gotoxy in c: gotoxy function places cursor at a desired location on screen i.e. we can change cursor position using gotoxy function.
Declaration : void gotoxy( int x, int y);
where (x, y) is the position where we want to place the cursor.

C programming code for gotoxy

#include<stdio.h>
#include<conio.h>
 
main()
{
   int x, y;
 
   x = 10;
   y = 10;
 
   gotoxy(x, y);
 
   printf("C program to change cursor position.");
 
   getch();
   return 0;
}
Output:
gotoxy function code output
AttachmentSize
gotoxy.png4.17 KB

getche in c

getche function prompts the user to press a character and that character is printed on screen.

C code for getche

#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Waiting for a character to be pressed from the keyboard to exit.");
 
   getche();
   return 0;
}
Run this program and press a character. Then view the user screen (Alt+F5) if using turbo c. You will find the character printed on the screen if you pressed a printable character. Try pressing enter or tab key (non printable) characters also.

getch in c

getch in c language: getch function prompts the user to press a character and that character is not printed on screen, getch header file is conio.h.

C programming code for getch

/* getch in c example */
#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Waiting for a character to be pressed from the keyboard to exit.\n");
 
   getch();
   return 0;
}
When you will run this program, the program will exit only when you press a character, note that we are talking about a character so try pressing numlock, shift key etc (program will not exit if you press these keys) as these are not characters. Also try the above program by removing getch(), in this case program will exit without waiting for a character being pressed from keyboard.

How to use getch in c++

#include<iostream.h>
#include<conio.h>
 
main()
{
   cout << "Enter a character";
   getch();
}

getch in Dev C++ compiler

getch library function works in dev c++ compiler, also note that it doesn't support all functions of conio.h as turbo c does.

getchar in c

#include<stdio.h>
 
main()
{
   int c;
 
   c = getchar();
 
   putchar(c);
 
   return 0;
}
Common use of getch is that you can view the output (if any) of your program without having to open the output window if you are using turbo c compiler or if you are not running your program from command prompt.

delline

delline function deletes the line containing the cursor and move all lines below it one line up.

C programming code for delline

#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("This line will be deleted when you press a key.");
 
   getch();
   delline();
 
   printf("Line deleted successfully.");
 
   getch();
   return 0;
}

clrscr in c

clrscr function clears the screen amd move the cursor to upper left hand corner of screen.

C programming code for clrscr

#include<stdio.h>
#include<conio.h>
 
main()
{
   printf("Press any key to clear the screen.\n");
 
   getch();
 
   clrscr();
 
   printf("This appears after clearing the screen.\n");
   printf("Press any key to exit...\n");
 
   getch();
   return 0;
}
In the above program first we display the message "Press any key to clear the screen." using printf and then ask the user to press a key. When user will press a key screen will be cleared and another message will be printed. clrscr function does not work in Dev C++ compiler. Also do not use clrscr in graphics mode instead use cleardevice.

sound c

Sound function produces the sound of a specified frequency. Used for adding music to c program, try to use some random values in loop, vary delay and enjoy.
Declaration:- void sound(unsigned frequency);

C programming code for sound

#include<dos.h>
 
main()
{
   int a;
 
   for ( a = 200 ; a <= 1000 ; a = a + 20 )
   {
      sound(a);
      delay(25);
   }
   nosound();
 
   return 0;
}

sleep c

Sleep function delays program execution for a given number of seconds.
Declaration: void sleep(unsigned seconds);

C programming code for sleep

#include<stdio.h>
#include<dos.h>
 
main()
{
   printf("Wait for 5 seconds to exit.\n");
   sleep(5);
   return 0;
}

setdate c

setdate function is used to change system date.

C programming code for setdate

#include<stdio.h>
#include<conio.h>
#include<dos.h>
 
main()
{
   struct date d;
 
   printf("Enter the new date ( day, month and year ) as integers ");
   scanf("%d%d%d",&d.da_day,&d.da_mon,&d.da_year);
 
   setdate(&d);
 
   printf("Current system date is %d/%d/%d\n",d.da_day,d.da_mon,d.da_year);
 
   getch();
   return 0;
}
Output: 
change system date

nosound c

nosound function turn off the PC speaker.
Declaration : void nosound();

C programming code for nosound

#include<dos.h>
 
main()
{
   sound(400);
   delay(1000);
   nosound();
 
   return 0;
}

gettime c

gettime in c: gettime function is used to find current system time. We pass address of a structure varibale of type ( struct time ).

C programming code for gettime

#include<stdio.h>
#include<dos.h>
 
main()
{
   struct time t;
 
   gettime(&t);
 
   printf("Current system time is %d : %d : %d\n",t.ti_hour,t.ti_min,t.ti_sec);
 
   return 0;
}
Output: 
system time

getdate c

Program to print the current system date, getdate c code below explain how to use this function to print computer date.

Getdate example

C programming code to print date
#include<stdio.h>
#include<dos.h>
 
main()
{
   struct date d;
 
   getdate(&d);
 
   printf("Current system date is %d/%d/%d\n",d.da_day,d.da_mon,d.da_year);
 
   return 0;
}

delay function in c

Delay in c: delay function is used to suspend execution of a program for a particular time.
Declaration :- void delay(unsigned int);
Here unsigned int is the number of milliseconds ( remember 1 second = 1000 milliseconds ). To use delay function in your program you should include the dos.h header file.

C programming code for delay

#include<stdio.h>
#include<stdlib.h>
 
main()
{
    printf("This c program will exit in 10 seconds.\n");        
 
    delay(10000);                         
 
    return 0;
}
Above c program exits in ten seconds, after the printf function is executed the program waits for 10000 milliseconds or 10 seconds and then program termination occurs.

Delay in c program

: If you don't wish to use delay function then you can use loops to produce delay in c program.
#include<stdio.h>
 
main()
{
   int c = 1, d = 1;
 
   for ( c = 1 ; c <= 32767 ; c++ )
       for ( d = 1 ; d <= 32767 ; d++ )
       {}
 
   return 0;
}
We don't write any statement in the loop body.

c program countdown

This c graphics program performs countdown for 30 seconds.

C program countdown code

#include<graphics.h>
#include<dos.h>
#include<conio.h>
 
main()
{
   int gd = DETECT, gm, i;
   char a[5];
 
   initgraph( &gd, &gm, "C:\\TC\\BGI");
 
   settextjustify( CENTER_TEXT, CENTER_TEXT );
   settextstyle(DEFAULT_FONT,HORIZ_DIR,3);
   setcolor(RED);
 
   for(i = 30 ; i >=0 ; i--)
   {
      sprintf(a,"%d",i);
      outtextxy(getmaxx()/2, getmaxy()/2, a);
      delay(1000);
 
      if ( i == 0 )
         break;
      cleardevice();
   }
 
   getch();
   closegraph();
   return 0;
}

c program to draw circles in circles

This program draws circles in circles in two different colors.

C programming code

#include<graphics.h>
#include<conio.h>
#include<dos.h>
 
main()
{
   int gd = DETECT, gm, x, y, color, angle = 0;
   struct arccoordstype a, b;
 
   initgraph(&gd, &gm, "C:\\TC\\BGI");
   delay(2000);
 
   while(angle<=360)
   {
      setcolor(BLACK);
      arc(getmaxx()/2,getmaxy()/2,angle,angle+2,100);
      setcolor(RED);
      getarccoords(&a);
      circle(a.xstart,a.ystart,25);
      setcolor(BLACK);
      arc(getmaxx()/2,getmaxy()/2,angle,angle+2,150);
      getarccoords(&a);
      setcolor(GREEN);
      circle(a.xstart,a.ystart,25);
      angle = angle+5;
      delay(50);
   }
 
   getch();
   closegraph();
   return 0;
}
Output of program:
circles in circles
AttachmentSize
circles in circles.png18.11 KB

c smiling face animation

This animation using c draws a smiling face which appears at random position on screen. See output below the code, it will help you in understanding the code easily.

C programming code

#include<graphics.h>
#include<conio.h>
#include<stdlib.h>
 
main()
{
   int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75;
   void *p;
 
   initgraph(&gd,&gm,"C:\\TC\\BGI");
 
   setcolor(YELLOW);
   circle(50,100,25);
   setfillstyle(SOLID_FILL,YELLOW);
   floodfill(50,100,YELLOW);
 
   setcolor(BLACK);
   setfillstyle(SOLID_FILL,BLACK);
   fillellipse(44,85,2,6);
   fillellipse(56,85,2,6);
 
   ellipse(50,100,205,335,20,9);
   ellipse(50,100,205,335,20,10);
   ellipse(50,100,205,335,20,11);
 
   area = imagesize(left, top, left + 50, top + 50);
   p = malloc(area);
 
   setcolor(WHITE);
   settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
   outtextxy(155,451,"Smiling Face Animation");
 
   setcolor(BLUE);
   rectangle(0,0,639,449);
 
   while(!kbhit())
   {
      temp1 = 1 + random ( 588 );
      temp2 = 1 + random ( 380 );
 
      getimage(left, top, left + 50, top + 50, p);
      putimage(left, top, p, XOR_PUT);
      putimage(temp1 , temp2, p, XOR_PUT);
      delay(100);
      left = temp1;
      top = temp2;
   }
 
   getch();
   closegraph();
   return 0;
}
Output of program:
smiling face
AttachmentSize
smiling face.png2.79 KB