Sunday, October 31, 2010

Preprocessor in C

Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line before the source code passes through the compiler it is examined by the preprocessor for any preprocessor directives. If there is any appropriate actions are taken then the source program is handed over to the compiler.


Preprocessor directives follow the special syntax rules and begin with the symbol #bin column1 and do not require any semicolon at the end. A set of commonly used preprocessor directives



Preprocessor directives:

Directive

Function

#define

Defines a macro substitution

#undef

Undefines a macro

#include

Specifies a file to be included

#ifdef

Tests for macro definition

#endif

Specifies the end of #if

#ifndef

Tests whether the macro is not def

#if

Tests a compile time condition

#else

Specifies alternatives when # if test fails




The preprocessor directives can be divided into three categories 
1. Macro substitution division 
2. File inclusion division 
3. Compiler control division


Macros:
Macro substitution is a process where an identifier in a program is replaced by a pre defined string composed of one or more tokens we can use the #define statement for the task.


It has the following form


#define identifier string
The preprocessor replaces every occurrence of the identifier int the source code by a string. The definition should start with the keyword #define and should follow on identifier and a string with at least one blank space between them. The string may be any text and identifier must be a valid c name.


There are different forms of macro substitution. The most common form is 
1. Simple macro substitution 
2. Argument macro substitution 
3. Nested macro substitution


Simple macro substitution:
Simple string replacement is commonly used to define constants example:


#define pi 3.1415926


Writing macro definition in capitals is a convention not a rule a macro definition can include more than a simple constant value it can include expressions as well. Following are valid examples:


#define AREA 12.36


Macros as arguments:
The preprocessor permits us to define more complex and more useful form of replacements it takes the following form.


# define identifier(f1,f2,f3…..fn) string.


Notice that there is no space between identifier and left parentheses and the identifier f1,f2,f3 …. Fn is analogous to formal arguments in a function definition.


There is a basic difference between simple replacement discussed above and replacement of macro arguments is known as a macro call


A simple example of a macro with arguments is


# define CUBE (x) (x*x*x)


If the following statements appears later in the program,


volume=CUBE(side);


The preprocessor would expand the statement to


volume =(side*side*side)


Nesting of macros:
We can also use one macro in the definition of another macro. That is macro definitions may be nested. Consider the following macro definitions


# define SQUARE(x)((x)*(x))


Undefining a macro:
A defined macro can be undefined using the statement


# undef identifier.


This is useful when we want to restrict the definition only to a particular part of the program.


File inclusion:
The preprocessor directive "#include file name” can be used to include any file in to your program if the function s or macro definitions are present in an external file they can be included in your file 
In the directive the filename is the name of the file containing the required definitions or functions alternatively the this directive can take the form


#include< filename >


Without double quotation marks. In this format the file will be searched in only standard directories. 


The c preprocessor also supports a more general form of test condition #if directive. This takes the following form 


#if constant expression 



statement-1; 
statemet2’ 
…. 
…. 

#endif 


the constant expression can be a logical expression such as test < = 3 etc If the result of the constant expression is true then all the statements between the #if and #endif are included for processing otherwise they are skipped. The names TEST LEVEL etc., may be defined as macros.

COMMAND LINE ARGUMENTS IN C

In C it is possible to accept command line arguments. Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, you must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.


(We should probably admit that command line user interfaces are a bit old-fashioned, and currently somewhat out of favor. If you've used Unix or MS-DOS, you know what a command line is, but if your experience is confined to the Macintosh or Microsoft Windows or some other Graphical User Interface, you may never have seen a command line. In fact, if you're learning C on a Mac or under Windows, it can be tricky to give your program a command line at all. Think C for the Macintosh provides a way; I'm not sure about other compilers. If your compilation environment doesn't provide an easy way of simulating an old-fashioned command line, you may skip this chapter.)
C's model of the command line is that it consists of a sequence of words, typically separated by whitespace. Your main program can receive these words as an array of strings, one word per string. In fact, the C run-time startup code is always willing to pass you this array, and all you have to do to receive it is to declare main as accepting two parameters, like this:
int main(int argc, char *argv[])
 {
 ...
 }
When main is called, argc will be a count of the number of command-line arguments, and argv will be an array (``vector'') of the arguments themselves. Since each word is a string which is represented as a pointer-to-charargv is an array-of-pointers-to-char. Since we are not defining the argv array, but merely declaring a parameter which references an array somewhere else (namely, in main's caller, the run-time startup code), we do not have to supply an array dimension for argv. (Actually, since functions never receive arrays as parameters in C, argv can also be thought of as a pointer-to-pointer-to-char, or char **. But multidimensional arrays and pointers to pointers can be confusing, and we haven't covered them, so we'll talk about argv as if it were an array.) (Also, there's nothing magic about the names argc and argv. You can give main's two parameters any names you like, as long as they have the appropriate types. The names argc and argv are traditional.)
The first program to write when playing with argc and argv is one which simply prints its arguments:
#include 

main(int argc, char *argv[])
{
int i;

for(i = 0; i < argc; i++)
 printf("arg %d: %s\n", i, argv[i]);
return 0;
}
(This program is essentially the Unix or MS-DOS echo command.)
If you run this program, you'll discover that the set of ``words'' making up the command line includes the command you typed to invoke your program (that is, the name of your program). In other words, argv[0] typically points to the name of your program, and argv[1] is the first argument.
There are no hard-and-fast rules for how a program should interpret its command line. There is one set of conventions for Unix, another for MS-DOS, another for VMS. Typically you'll loop over the arguments, perhaps treating some as option flags and others as actual arguments (input files, etc.), interpreting or acting on each one. Since each argument is a string, you'll have to use strcmp or the like to match arguments against any patterns you might be looking for. Remember that argc contains the number of words on the command line, and that argv[0] is the command name, so ifargc is 1, there are no arguments to inspect. (You'll never want to look at argv[i], for i >= argc, because it will be a null or invalid pointer.)
As another example, also illustrating fopen and the file I/O techniques of the previous chapter, here is a program which copies one or more input files to its standard output. Since ``standard output'' is usually the screen by default, this is therefore a useful program for displaying files. (It's analogous to the obscurely-named Unix cat command, and to the MS-DOS type command.) You might also want to compare this program to the character-copying program of section 6.2.
#include 

main(int argc, char *argv[])
{
int i;
FILE *fp;
int c;

for(i = 1; i < argc; i++)
 {
 fp = fopen(argv[i], "r");
 if(fp == NULL)
  {
  fprintf(stderr, "cat: can't open %s\n", argv[i]);
  continue;
  }

 while((c = getc(fp)) != EOF)
  putchar(c);

 fclose(fp);
 }

return 0;
}
As a historical note, the Unix cat program is so named because it can be used to concatenate two files together, like this:
cat a b > c
This illustrates why it's a good idea to print error messages to stderr, so that they don't get redirected. The ``can't open file'' message in this example also includes the name of the program as well as the name of the file.
Yet another piece of information which it's usually appropriate to include in error messages is the reason why the operation failed, if known. For operating system problems, such as inability to open a file, a code indicating the error is often stored in the global variable errno. The standard library function strerror will convert an errno value to a human-readable error message string. Therefore, an even more informative error message printout would be
fp = fopen(argv[i], "r");
 if(fp == NULL)
  fprintf(stderr, "cat: can't open %s: %s\n",
    argv[i], strerror(errno));
If you use code like this, you can #include  to get the declaration for errno, and  to get the declaration for strerror().

Ordered List program in C

The most common linear data structure used is the list. By now you are already pretty familiar with the idea of a list and at least one way of representing a list in the computer. Now we are going to look at a particular kind of list: an ordered list. Ordered lists are very similar to the alphabetical list of employee names for the ABC company. These lists keep items in a specific order such as alphabetical or numerical order. Whenever an item is added to the list, it is placed in the correct sorted position so that the entire list is always sorted.

Before we consider how to implement such a list, we need to consider the abstract view of an ordered list. Since the idea of an abstract view of a list may be a little confusing, let's think about a more familiar example. Consider the abstract view of a television. Regardless of who makes a television, we all expect certain basic things like the ability to change channels and adjust the volume. As long as these operations are available and the TV displays the shows we want to view, we really don't care about who made the TV or how they chose to construct it. The circuitry inside the TV set may be very different from one brand to the next, but the functionality remains the same. Similarly, when we consider the abstract view of an ordered list, we don't worry about the details of implementation. We are only concerned with what the list does, not how it does it.

Suppose we want a list that can hold the following group of sorted numbers: [2 4 6 7]. What are some things that we might want to do with our list? Well, since our list is in order, we will need some way of adding numbers to the list in the proper place, and we will need some way of deleting numbers we don't want from the list. To represent these operations, we will use the following notation:



Order List Program in C

Saturday, October 30, 2010

Introduction to C

What is C??
C is a structured and compiled programming language, which is developed by Dennis Ritchie. C supports rich set of functions that enables easy maintainability of code, by dividing large program into smaller modules.
Positive points about C:
1. C is high-level programming.However C contains features that are normally associated with low-level programming.
2. Speed and memory efficiency is very high.
3. C is a portable programming language.
Portability:executing the program on any sort of Operating system with or with out modifications.
4. C is basis and basic for C++ and Java.

All these features make C as powerful programming language.

Because of its memory efficiency and speed most of the operating systems like linux kernel,windows and games are developed in C.

I hope this introduction is enough to start Learning C programming.

Start programming:

By reading books and listening to lectures you can not C Programming. The best way to learn Programming is by just writing programs.
I Will show you how to write simple C programs, but before hand you must be able to open notepad :D :D.

Now open your notepad and type this

#include
main()
{
printf("Welcome to C Programming\n");
}

Save this file with ".c" extension. like first.c, now your C program is read. This program prints Welcome to C programming on the screen.

To see this Out put first we need to compile the program since C is compiled programming language.

to Compile C program open your terminal and type

>> cc first.c  after compiling the program you will get a.out file if you didn't make any mistakes. Then run a.out file

>> ./a.out
>> Welcome to C Programming.

Monday, October 25, 2010

Binary Search Program in C

/*
binary.c: binary search program.
Author : @f!z$
*/

#include


void main()
{
int array[10];
int i, j, N, temp, keynum;
int low,mid,high;
printf("Enter the value of N\n");
scanf("%d",&N);

printf("Enter the elements one by one\n");
for(i=0;i
{
scanf("%d",&array[i]);
}
printf("Input array elements\n");
for(i=0;i
{
printf("%d\n",array[i]);
}
/* Bubble sorting begins */
for(i=0; i< N ; i++)
{
for(j=0; j< (N-i-1) ; j++)
{
if(array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted array is...\n");
for(i=0;i
{
printf("%d\n",array[i]);
}

printf("Enter the element to be searched\n");
scanf("%d", &keynum);

/* Binary searching begins */

low=1;
high=N;

do
{
mid= (low + high) / 2;
if ( keynum < array[mid] )
high = mid - 1;
else if ( keynum > array[mid])
low = mid + 1;
} while( keynum!=array[mid] && low <= high); /* End of do- while */

if( keynum == array[mid] )
{
printf("SUCCESSFUL SEARCH\n");
}
else
{
printf("Search is FAILED\n");
}

} /* End of main*/

Matrix Multiplication Program in C

#include
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;


printf("Enter The Rows And Cloumns And Of The First Matrix:");
scanf("%d %d",&m,&n);
printf("\nEnter The Rows And Cloumns And Of The Second Matrix:");
scanf("%d %d",&p,&q);

printf("\nEnter Elements Of The First Matrix:\n");
arrayfill(a,m,n);

printf("\nEnter Elements Of The Second Matrix:\n");
arrayfill(b,p,q);

printf("The First Matrix Is:\n");
arrayprint(a,m,n);

printf("The Second Matrix Is:\n");
arrayprint(b,p,q);
if(n!=p)
{
printf("Aborting!!!!!!/nMultiplication Of The Above Matrices Not Possible.");
exit(0);
}
else
{
for(i=0;i< m;i++)
{
for(j=0;j< q;j++)
{
c[i][j] = 0;
for(k=0;k< n;k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf("\nMultiplication Of The Above Two Matrices Are:\n\n");
for(i=0;i< m;i++)
{
for(j=0;j< q;j++)
{
printf(" %d ",c[i][j]);
}
printf("\n");
}
}
}

arrayfill(int a[10][10],int m, int n )
{
    int i,j;
    for(i=0;i< m;i++)
    {
    for(j=0;j< n;j++)
    scanf("%d",&a[i][j]); //print the first matrix
    printf("\n");
    }
}


arrayprint(int a[10][10],int m,int n)
{
    int i,j;
    for(i=0;i< m;i++) // print the second matrix
    {
    for(j=0;j< n;j++)
    printf(" %d ",a[i][j]);
    printf("\n");
    }
}