Advanced C Programming an Introduction


Hi.,
                                     This is an introduction about the advance of c. Normally, most of the students are known only basic of c language. But C programming language contains lot of things. The C Programs used not only mathematical calcuation. It is used Embedded Systems, Hardware process, Gaming technologoy..etc.
Ok.,Now we discuss about Advance of C programming.

Introduction:

                                      “C” seems a strange name for a structured programming language. C was evolved from ALGOL, BCPL and B by Dennis Ritchie at Bell Laboratories in 1972. During the 1970s the C programming language became increasingly popular. Many universities and organizations began creating their own variations of the language for their own projects. By the beginning of the 1980s compatibility problems between the various C implementations became apparent. In 1983 the American National Standards Institute (ANSI) formed a committee to establish a standard specification of C known as "ANSI C". This work culminated in the creation of the so-called C89 standard in 1989. C operators and built-in functions can be used to write any complex program. The C language used to writing both system software and business packages.
Programs written in C are efficient and fast. This is due to its variety of data types and powerful operators. It is many times faster than BASIC. For example, a program to increment a variable from 0 to 15000 takes about one second in C while it takes more than 50 seconds in an interpreter BASIC.
There are only 32 keywords and its strength lies in its built-in function. Several standard functions are available which can be used for developing programs. A C program is basically a collection of function that are supported by the C library. We can continuously add our own functions to C library. With the availability of a large number of functions, the programming task becomes simple.
This topic describe the advance of C programs such as how to create graphics programs using graphics functions, bitwise operators, purpose of delay() and gotoxy() functions.
                                       
     The advanced c programs includes following contents:

1. C Compilers
2. C Library Functions
3. What are Bitwise Operators?
            3.1 AND OR and XOR
            3.2 1’s Complement
            3.3 Bit shift
            3.4 Mask
4. Graphics and Animation
        4.1 Some Methods used in Graphics Programs
        4.2 Programs


  1. C compilers:

A C program cannot be run by the computer directly. This is because a computer can understand and execute only those programs that are written in machine language.
                     The machine language of a computer consists of a set of instruction, each of which corresponds to a relatively simple operation such as add two numbers, go to a particular instruction and so on. All these instruction are encoded in binary, and they can be executed by the computer directly. Assembly language is one step higher than machine language.
                        A C program on the other hand, is easier to write and does not vary much from computer to computer. But a C program has to be converted into the machine language before execution. A C compiler translates a C program into a machine language program. There are many C compilers available, and each compiler is used in specific way. The C compiler available in a particular system depends to a certain extent on the operating system that runs the system. The commands translate a C source program into an executable program. This process actually takes place in two stages; compiling and linking.
                        The compiler performs the basic translation from C statement into machine language instructions. The output of the compiler is called the object file. In addition to the machine language instruction, the object file has information to aid the linker. The linker combines different object files to produce the actual executable file.

 
2. C library functions:                 The C standard library is a standardized collection of header file's and library routines used to implement common operations, such as input/output and character string handling, in the C programming language. Unlike other languages such as COBOL, FORTRAN, and PL/I, C does not include built-in keywords for these tasks, so nearly all C programs rely on the standard library to function.
                        Part of the resulting standard was a set of software libraries called the ANSI C standard library.
Later revisions of the C standard have added several new required header files to the library. Support for these new extensions varies between implementations.
The C language is accompanied by a number of library functions that perform various tasks. The ANSI C standard library consists of 24 C header files which can be included into a programmer's project with a single directive. Each header file contains one or more function declarations, data type definitions and macros. The contents of these header files follows:
Header file
What It Does
<stdio.h>
Standard I/O functions
<stdlib.h>
Utility functions such as string  conversion ,memory allocation, random number generator, etc.
<ctype.h>
Character testing & conversion functions.
<math.h>
Mathematical functions.
                 <string.h>
String manipulation
                 <conio.h>
Declares various functions used in calling DOS console I/O routine.
                 <alloc.h>
Declares memory management functions.
                <graphics.h>
Declares prototypes for the graphics functions.
                  <dos.h>
Declares various constants & gives declaration needed for DOS.
                <malloc.h>
Memory management functions & variables.
                              <time.h>

Time manipulation functions
                <float.h>

Constants related to floating point arithmetic

 
3. What are bitwise operators?:
                C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bit, or shifting them right or left. Bitwise operators may not be applied to float or double. The following table lists the bitwise operators and their meanings.
Bitwise operators include:
Table 1-1 Bitwise Operators



3.1 AND OR and XOR

These require two operands and will perform bit comparisons.
AND & will copy a bit to the result if it exists in both operands.
  
  main()
  {
    unsigned int a = 60;       /* 60 = 0011 1100 */  
    unsigned int b = 13;       /* 13 = 0000 1101 */
    unsigned int c = 0;           
 
    c = a & b;                  /* 12 = 0000 1100 */ 
  }
 


OR | will copy a bit if it exists in eather operand.
  
  main()
  {
    unsigned int a = 60;       /* 60 = 0011 1100 */  
    unsigned int b = 13;       /* 13 = 0000 1101 */
    unsigned int c = 0;           
 
    c = a | b;                  /* 61 = 0011 1101 */ 
  }
 
XOR ^ copies the bit if it is set in one operand (but not both).
  
  main()
  {
    unsigned int a = 60;       /* 60 = 0011 1100 */  
    unsigned int b = 13;       /* 13 = 0000 1101 */
    unsigned int c = 0;           
 
    c = a ^ b;                  /* 49 = 0011 0001 */ 
  }
 



 

3.2 Ones Complement (called tilde ~)

This operator is unary (requires one operand) and has the effect of 'flipping' bits. Change 1’s into 0’s and vice versa in the binary representation of an integer. Suppose an into ‘a’ is 6. Then its binary representation (with 8 bits) is 0000 0110. So, ‘~a’ will be 1111 1001.

 
  main()
  {
    unsigned int Value=4;          /*   4 = 0000 0100 */  
 
    Value = ~ Value;               /* 251 = 1111 1011 */  
 
  }
 


 The following example program,

#include<stdio.h>
void main()
{
int a;
printf(“Enter the integer:”);
scanf(“%d”,&a);
printf(“a=%d”,a);
printf(“~a=%d”,~a);
}

 









Output:
            Enter the integer: 25
                                    a= 25
                                  ~a= -26
Here a= 0001 1001(25)
So, ~a= 1110 0110(-26)         

3.3 Bit shift.

The following operators can be used for shifting bits left or right.

<<
>>
<<=
>>=
The left operands value is moved left or right by the number of bits specified by the right operand. For example:
 
  main()
  {
    unsigned int Value=4;          /*  4 = 0000 0100 */  
    unsigned int Shift=2;
 
    Value = Value << Shift;        /* 16 = 0001 0000 */  
 
    Value <<= Shift;               /* 64 = 0100 0000 */  
 
    printf("%d\n", Value);         /* Prints 64      */  
  }
 
Usually, the resulting 'empty' bit is assigned ZERO. Please use unsigned variables with these operators to avoid unpredictable results.

3.4 Mask:
                    We can apply the concept of mask to selectively set or clear any bit. Now let us see how to set the 4th bit of a variable “a” to true value by applying the mask.
Let       a  →                0 0 0 0 1 1 0 1
Mask   b →                 0 0 0 0 1 0 0 0
Result a OR b                         0 0 0 0 1 1 0 1
You will note that we are interested in setting the 4th bit to true value without affecting others. This has been achieved with the help of mask b, which is actually the OR operation.
            b →                 0 0 0 0 1 0 0 0
This can be represented in hexadecimal (base 16) as 0x08. The above OR-ing operation can be expressed using the updating assignment operator as
            A |= 0x08;
With means a = a | 0x08;
To help you understand how this hexadecimal notation was arrived at, consider the following bit pattern.
                        1 1 0 1             0 1 0 1
To express in hex notation, group 4 bits and express in equivalent numbers, such as:
                        D =1 1 0 1       5 = 0 1 0 1
Where this is written in shorthand notation as 0xD5 (in hex). It is easy to convert a number in hex to octal and vice versa. Now to set the 4th and the 1st bits, the mask is applied as follows:
                        a |= 0x09;
“clear”operation of single bit can be done with bitwise “&” operator.
                        a &= 0xDF;    
   which means:                       a = a & 0xDF

            a →     0 0 1 0 1 1 0 1
       0xDF →   1 1 0 1 1 1 1 1
                       
                        0 0 0 0 1 1 0 1
Notice that the 6th bit has been cleared.  To cleared more than one bit the mask must contain clear bits(0) in corresponding positions. Bitwise operators may be applied directly to constants also, instead of variables.For example of the following program :



#include<stdio.h>
void main()
{
unsigned n;
int i,j,mask,k=0;
printf(“Enter the integer:”);
scanf(“%u”,&n);
printf(“It’s binary equivalent is:”);
for(i=15;i>=0;i--)
{
mask=1<<i;
j=n&mask;
if(j= =0)
printf(“0”);
else
printf(“1”);
k++;
if(k%4= =0)
printf(“  “);
}
}
Output:
 Enter the integer: 1 2 3 4 5
It’s binary equivalent is: 0011 0000 0011 1001.




4. Graphics and Animation:
                Handling graphics in c is a challenge to programmers. The header file of this function is “#include<graphics.h>”. Two important hardware settings must be properly selected to get the best results. One is the graphics driver, herein named the gdriver, and the second one is the graphics mode, called gmode.
During the initialization process, we incorporate necessary instruction to select the best driver and mode. The instruction is
                        gdriver=DETECT;
                        This selects the best resolution of the video display unit, so that the graphics can be completely represented. The mode deals with the ability of the display screen to display text or graphics. Here again we have necessary instruction to select the correct mode to display the graphics in the best possible manner.
                        The initialization is done by the following statement                                                                         initgraph(&gdriver,&gmode,”c:\\tc\\bgi ”);
The last argument “c:\\tc\\bgi” is the path name where the bgi(Borland Graphics Interface) files can be found. These are a series of files stored to handle all graphics manipulations. The files must be present in the c:driver for any graphics program to run. The initialization process also gives the address where the driver and mode operations are available. After executing the above statement, the computer hardware is made ready to run and execute any graphics program.
                        The various driver and mode options are listed for reference:
Common display adapters:

           
Display adapters
Constant for initgraph()
CGA
CGA
EGA
EGA
VGA
VGA

Common mode for adapters:
Driver
Mode constant
Display mode
CGA
CGAHI
640 X 200, 2 colors
EGA
EGALO
EGAHI
640 X 200,16 colors
640 X 350,16 colors
VGA
VGALO
VGAMED
VGAHI
640 X 200, 16 colors
640 X 350, 16 colors
640 X 480, 16 colors

 
4.1 Some methods used in graphics programs:
                        C language use many graphics functions. The following some graphics functions are:
*      Cleardevice()
*      putpixel()
*      outtextxy()
*      itoa()
*      rectangle()
*      circle()
*      line()
*      moveto()
*      lineto()
*      delay()
*      setviewport()
*      Clearviewport()
*      settextstyle()
*      setfillstyle()
*      floodfill()
*      textcolor()
*      textbackground()
*      closegraph()


There are standard methods developed in C language to make things happen while dealing with graphics.
                        cleardevice()
This simple method clears all display of previous contents and prepares it for the new display. The method does not take any arguments.
                        putpixel(x,y,WHITE)
The method takes 3 arguments. x,y specify the coordinates of the location of the particular pixel. WHITE is the color of the dot which the pixel is painted.
                        outtextxy(x,y,”LINE”)
This method places the text within double quotes in graph, starting from location x,y.
                        itoa(x1,st1,10)
The method converts the integer x1 into an alphabet, and puts it in st1, which is an array to hold 10 characters. The integer 10 represents the buffer size of the array.
            rectangle(x,y,int x_width,int y_height)
This method draws a rectangle starting from location x,y. the rectangle has horizontal width x_width pixel and vertical height y_height pixels. The rectangle is shown below:

 
                                       Figure: Rectangle
            x_width
 
                x,y

                                                                                   
                                                                                        y_height




             circle(x,y,radius)
This method draws a circle of radius specified with the center at coordinates x,y

                            line(x1,y1,x2,y2)
Draws a line starting from location(x1,y1) to location(x2,y2)
 
moveto(dx,dy)
The cursor is moved from current location to the specified location dx,dy. The parameters dx,dy may also be used as incremental values to modify x,y coordinates.
                        lineto(x,y)
The method draws a line from its current location to the coordinate point(x,y).
                        delay(1000)
The method causes a pause in execution of the program for 1000 ms which is 1 sec.
During animation we may introduce such delays to display an image before switching over to another image.
setviewport(int left,int top,int right,int bottom,int clip)
This method is best explained with a typical example. setviewport(10,10,630,470,1).
The method marks a rectangle starting from location (10,10), having horizontal width of 630 pixels and vertical height of 470 pixels. The integer 1 specifies that the image within this identified area may be clipped. Any non-zero integer may be used. Putting a 0 would imply that clipping is not allowed.
                        clearviewport()
This method generally follows after setviewport() methods. All images within the marked rectangle are erased toaccommodate a new image. This method does not take any argument.
                        closegraph()
This method terminates all graphics operations and reverts the hardware back to its default normal mode, which may be in text mode.
            settextstyle(DEFAULT_FONT,HORIZ_DIR,1)
This library function sets three characteristics of the text: the font, the direction and the character size. These are specified as 3 integer arguments.
The Fonts available are:
*      DEFAULT_FONT,
*      TRIPLEX_FONT,
*      SMALL_FONT,
*      SANS_SERIF_FONT, and
*      GOTHIC_FONT

The direction may be HORIZ_DIR or VERT_DIR
The last argument specifies the character size ranging from 1 for smallest to 10 for largest.

                  setfillstyle(SOLID_FILL,RED)
This function specifies the mode of filling can be changed depending on our fancy. A few are given below without comments:
*      EMPTY_FILL
*      SOLID_FILL
*      LINE_FILL
*      LTSLASH_FILL
*      SLASH_FILL
*      BKSLASH_FILL
*      HATCH_FILL
*      WIDE_DOT_FILL
*      CLOSE_DOT_FILL

floodfill(x,y,getmaxcolor())
This function fills the enclosed area about x,y with the highest value of the color returned by the getmaxcolor() function. In the setfillstyle() function, we have already specified the color. This function which follows it, selects the highest color intensity value for this color.
                        setcolor(CYAN)
This function uses the specified color for all drawing events that occur after executing this statement.
                        detectgraph()
This function used to identify which type of monitor.
                     gotoxy():
 This function’s header file is <conio.h>.
This function is used to find the positions cursor in text window
 Declaration: 
                  The following syntex is :
                                    void gotoxy(int x, int y);
 Remarks:
                  gotoxy moves the cursor to the given position in the current text window.
If the coordinates are invalid, the call to gotoxy is ignored.
Example of invalid coordinates:
  gotoxy(40,30)  /* (35,25) = window's bottom right position */
Return Value:  None
 Example:
 #include <conio.h>
 int main(void)
 {
    clrscr();
    gotoxy(35, 12);
    printf(“graphics world");
    line
    getch();
    return 0; 
 }
delay() :
This function’s header file is <dos.h>.

This function is used to suspends execution for interval (milliseconds).

 Declaration: 
                  The following syntex is. 
void delay(unsigned milliseconds);
 Remarks:
With a call to delay, the current program is suspended from execution for
the time specified by the argument milliseconds.
It is not necessary to make a calibration call to delay before using it.
delay is accurate to one millisecond.
 Return Value:  None
  Example:
 /* Emits a 40-Hz tone for 1000 milliseconds */
 #include <dos.h>
 int main(void)
 {
    sound(440);
    delay(1000);
    nosound();
    return 0;
 }
The above program is create a 440-Hz sound until the 1000 milliseconds.
What is sound or nosound?:
                  The sound, nosound are the function’s header file<dos.h>.
Purposes:
                   sound turns the PC speaker on at the specified frequency
                   nosound turns the PC speaker off          
 Declaration:
                  The following syntax is declare the sound():
                   void sound(unsigned frequency);
                        The following syntax is declare the nosuond():
                   void nosound(void);
 Remarks:
sound turns on the PC's speaker at a given frequency.
 nosound turns the speaker off after it has been turned on by a call to
sound.
frequency specifies the frequency of the sound in hertz (cycles per second).
 Return Value:  None
 Example (for both functions):
 /* Emits a 7-Hz tone for 10 seconds.
      True story: 7 Hz is the resonant
      frequency of a chicken's skull cavity.
      This was determined empirically in
      Australia, where a new factory
      generating 7-Hz tones was located too
      close to a chicken ranch: When the
      factory started up, all the chickens
      died.
      Your PC may not be able to emit a 7-Hz tone. */
 #include <dos.h>
 int main(void)
 {
sound(7);
    delay(10000);
    nosound();
    return 0;
 }
This function create a sound 7Hz until the delay 10000 milliseconds.

How to create the textcolor()?:
<CONIO.H>
  
textcolor selects a new character color in text mode

 Declaration:

      void textcolor(int newcolor);
  Remarks:
These functions work for functions that produce text-mode output directly to
the screen (console output functions).
textcolor selects the foreground character color.

These functions do not affect any characters currently on the screen. Once
you have called one of these three functions, all subsequent functions using
direct video output (such as cprintf) will use the new attributes or colors.

If you use symbolic color constants, the following limitations apply to the
background colors you select:
  1.You can only select one of the first eight colors (0--7).
 
NOTE: If you use the symbolic color constants, you must include CONIO.H.

To make the characters blink in a call to textcolor, you add 128 to the
foreground color. The predefined constant BLINK exists for this purpose; for
example,

  textcolor(CYAN + BLINK);
 Light colors
Some monitors do not recognize the intensity signal used to create the eight
"light" colors (8-15). On such monitors, the light colors are displayed as
their "dark" equivalents (0-7).
Also, systems that do not display in color can treat these numbers as shades
of one color, special patterns, or special attributes (such as underlined,
bold, italics, etc.).

Exactly what you'll see on such systems depends on your hardware.

 Return Value:  None
#include <conio.h>
int main(void)
{
   int i, j;
   clrscr();
   for (i=0; i<9; i++)
   {
       for (j=0; j<80; j++)
              cprintf("C");
       cprintf("\r\n");
       textcolor(i+1);
       textbackground(i);
   }
   return 0;
}

Programs:

                The following program is to display the different type of font names.

 
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,””);
settextstyle(GOTHIC_FONT,HORIZ_DIR,15);
outtextxy(300,250,”graphics in c”);
closegraph();
getch();
}
 
Reference:

1.      “Programming with C”- Byron Gottfried
2.      “Programming with C” – K.R. Venugopal & Sudeep R Prasad
3.      “C programming Made Easy” – R. Rajaram
4.      “C software engineering approach” – Peter A Darnell &
Philip E. Margotesh
5.      “Depth of C” – Shaikh Nazneen Akther
6.      “Programming in C” – Dr. P. pandiyaraja






Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE