Saturday, 7 April 2012

Funny C Program


Here is one more tricky code, its so simple and funny.
Compile and then give anything in input and see if its funny or not.


Code:

#include<stdio.h>
#include<conio.h>
void main()
{
char ch[]="I AM AN IDIOT.";
char c='A';
int i=0;
while(c)
{
c=getch();
printf("%c\a",ch[i]);
i++;
if(i==14)
{
printf(" "); i=0;
}
}
}



Friday, 24 February 2012

Graphics in C


Graphics mode Initialization
initgraph() function is used to load the graphics drivers and initialize the graphics system. For every function, that uses graphics mode, graphics mode must be initialized before using that function.

void far initgraph(int far *driver, int far *mode, char far *path)

Function detectgraph
Detectgraph function determines the graphics hardware in the system, if the function finds a graphics adapter then it returns the highest graphics mode that the adapter supports.
void far detectgraph(int far *driver, int far *mode)

Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.

Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.


Function closegraph
This function shutdown the graphics mode and returns to the position it was before the initgraph function was called.
void far closegraph(void)
Example 1:
#include
#include

void main()
{
int gd=DETECT, gm;

initgraph(&gd, &gm, "c:\\turboc\\bgi");
circle(200,100,150);

getch();
closegraph();
}


Example 2:
#include
#include
void main()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, " c:\\turboc\\bgi");

circle(100,100,50);
outtextxy(75,170, "Circle");
rectangle(200,50,350,150);
outtextxy(240, 170, "Rectangle");
ellipse(500, 100,0,360, 100,50);
outtextxy(480, 170, "Ellipse");
line(100,250,540,250);
outtextxy(300,260,"Line");

getch();
closegraph();
}


Some Useful Graphics.h Functions:
int getdisplaycolor( int color );
int converttorgb( int color );
void delay( int msec );
void getarccoords( arccoordstype *arccoords );
int getbkcolor( );
int getcolor( );
int getmaxcolor( );
int getmaxheight( );
int getmaxwidth( );
int getmaxx( );
int getmaxy( );
void getfillpattern( char *pattern );
void getfillsettings( fillsettingstype *fillinfo );
void getlinesettings( linesettingstype *lineinfo );
bool getrefreshingbgi( );
int getwindowheight( );
int getwindowwidth( );
int getpixel( int x, int y );
void getviewsettings( viewporttype *viewport );
int getx( );
int gety( );
void setcolor( int color );
void setfillpattern( char *upattern, int color );
void setfillstyle( int pattern, int color );
void setlinestyle( int linestyle, unsigned upattern, int thickness );
void setrefreshingbgi(bool value);
void setviewport( int left, int top, int right, int bottom, int clip );
void setwritemode( int mode );
void moverel( int dx, int dy );
void moveto( int x, int y );
void refreshbgi(int left, int top, int right, int bottom);
void refreshallbgi( );
void setbkcolor( int color );

File Handling in C

A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characetrs, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. There are two kinds of files that programmers deal with text files and binary files.

Text Files

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.
Binary Files
A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.

Opening a file:
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);


The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. fopen() contain the file name and mode (the purpose of opening the file).

r is used to open the file for read only.
w is used to open the file for writing only.
a is used to open the file for appending data to it.

Closing a File

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. The input output library supports the function to close a file.

Syntax to close file

fclose(filepointer);


Example
#include
void main(void)
{
FILE *myfile;
char c;
myfile = fopen("firstfile.txt", "r");
if (myfile == NULL) printf("File doesn't exist\n");
else {
do {
c = getc(myfile);

putchar(c);

} while (c != EOF);

}
fclose(myfile);

}


File operation functions in C:
Function NameOperation
fopen()Creates a new file. Opens an existing file.
fcloseCloses a file which has been opened for use
getc()Reads a character from a file
putc()Writes a character to a file
fprintf()Writes a set of data values to a file
fscanf()Reads a set of data values from a file
getw()Reads a integer from a file
putw()Writes an integer to the file
fseek()Sets the position to a desired point in the file
ftell()Gives the current position in the file
rewind()Sets the position to the beginning of the file

Structures and Unions in C

A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.

struct mystruct
{
int numb;
char ch;
}

Structure has name mystruct and it contains two variables: an integer named numb and a character named ch.

struct mystruct s1;

Accessing Member Variables

s1.numb=12;

s1.ch=’b’;

printf(“\ns1.numb=%d”,s1.numb);

printf(“\ns1.ch=%c”,s1.ch);


typedef can also be used with structures. The following creates a new type sb which is of type struct chk and can be initialised as usual:
typedef struct chk
{
char name[50];
int magazinesize;
float calibre;
} sb;

ab arnies={"adam",30,7};

Unions:
A union is an object that can hold any one of a set of named members. The members of the named set can be of any data type. Members are overlaid in storage. The storage allocated for a union is the storage required for the largest member of the union, plus any padding required for the union to end at a natural boundary of its strictest member.

union {
char n;
int age;
float weight;
} people;

people.n='g';
people.age=26;
people.weight=64;

Strings in C

Character type array is called string. All strings end with the NULL character. Use the %s placeholder in the printf() function to display string values.

Declaration:
char name[50];
Example
#include
void main (void )
{
char *st1 = "abcd";
char st2[] = "efgh";
printf( "%s\n", s1);
printf( "%s\n", s2);

}

void main(void){

char myname[] = { 'S', 't', 'e', 'v', 'e' };

printf("%s \n",myname);
}

String input and output:
The gets function relieves the string from standard input device while put S outputs the string to the standard output device.

The function gets accepts the name of the string as a parameter, and fills the string with characters that are input from the keyboard till newline character is encountered.
The puts function displays the contents stored in its parameter on the standard screen.
The syntax of the gets function is
gets (str_var);

The syntax of the puts character is
puts (str_var);
Example:

# include <>
Void main ( )
{
char myname [40];
printf (“Type your Name :”);
gets (myname);
printf (“Your name is :”);
puts(myname);
}
Some String Functions:
FunctionDescription
strcpy(string1, string2)Copy string2 into string1
strcat(string1, string2)Concatenate string2 onto the end of string1
length = strlen(string)Get the length of a string
strcmp(string1, string2)Return 0 if string1 equals string2, otherwise nonzero
strchr(string1, chr);will find the first matching character in a string.

Arrays in C


An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

An array is a data structure of multiple elements with the same data type. Array elements are accessed using subscript. The valid range of subscript is 0 to size -1.

Declaration of Array

int arr[10];


Example:


#include
void main(void)
{
int a[5];
int i;
for(i = 0;i<5;i++)
{
a[i]=i;
}

for(i = 0;i<5;i++)
{
printf("%d value of I is = %d\n",i,a[i]);
}
}


Output

1 value of I is = 0

2 value of I is = 1

3 value of I is = 2

4 value of I is = 3

5 value of I is = 4


Multidimensional Arrays
A multi-dimensional array of dimension n (i.e., an n-dimensional array or simply n-D array) is a collection of items which is accessed via n subscript expressions. Multidimensional arrays can be described as "arrays of arrays".
Example:



#include

void main(void){
int a[3][2];
int i,j;
for(i = 0;i<3;i++){
for(j=0;j<2 ;j++) {
scanf(“%d”,&a[i][j]); }
}

for(i = 0;i<3;i++){
for(j=0;j<2;j++) {
printf("value in array %d\n",a[i][j]);
}
}

}

Pointers in C

A pointer is a variable suitable for keeping memory addresses of other variables; the values you assign to a pointer are memory addresses of other variables or other pointers.

C pointers are characterized by their value and data-type. The value is the address of the memory location the pointer points to, the type determines how the pointer will be incremented/decremented in pointer or subscript arithmetic.
Pointers are used to manipulate arrays and they can be used to return more than one value from a function.

Pointers are declared by using the asterisk(*).

int *p;

Each variable has two attributes: address and value. The address is the location in memory. In that location, the value is stored. During the lifetime of the variable, the address is not changed but the value may change.

#include

void main (void)
{
int i;
int * a;
i = 10;
a = &i;
printf (" The address of i is %8u \n", a);
printf (" The value at that location is %d\n", i);
printf (" The value at that location is %d\n", *a);
}
Output:
The address of i is 631672
The value at that location is 10
The value at that location is 10
Arrays and Pointers:
An array is actually a pointer to the 0th element of the array. Dereferencing the array name will give the 0th element. This gives us a range of equivalent notations for array access. In the following examples, arr is an array.







ArrayPointer
arr[0]*arr
arr[1]*(arr+1)
arr[n]*(arr+n)