Monday, June 6, 2011

Command Line Arguments

In environments that support C, there is a way to pass command-line arguments or parameters to a program when it begins executing. When main is called, it is called with two arguments. The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with; the second (argv, for argument vector) is a pointer to an array of character strings that contain the arguments, one per string. We customarily use multiple levels of pointers to manipulate these character strings.
The simplest illustration is the program echo, which echoes its command-line arguments on a single line, separated by blanks. That is, the command
echo hello, world
prints the output
hello, world
By convention, argv[0] is the name by which the program was invoked, so argc is at least 1. If argc is 1, there are no command-line arguments after the program name. In the example above, argc is 3, andargv[0]argv[1], and argv[2] are "echo""hello,", and "world" respectively. The first optional argument is argv[1] and the last is argv[argc-1]; additionally, the standard requires that argv[argc]be a null pointer.
The first version of echo treats argv as an array of character pointers:
#include <stdio.h>

   /* echo command-line arguments; 1st version */
   main(int argc, char *argv[])
   {
       int i;

       for (i = 1; i < argc; i++)
           printf("%s%s", argv[i], (i < argc-1) ? " " : "");
       printf("\n");
       return 0;
   }
Since argv is a pointer to an array of pointers, we can manipulate the pointer rather than index the array. This next variant is based on incrementing argv, which is a pointer to pointer to char, while argc is counted down:
#include <stdio.h>

   /* echo command-line arguments; 2nd version */
   main(int argc, char *argv[])
   {
       while (--argc > 0)
           printf("%s%s", *++argv, (argc > 1) ? " " : "");
       printf("\n");
       return 0;
   }
Since argv is a pointer to the beginning of the array of argument strings, incrementing it by 1 (++argv) makes it point at the original argv[1] instead of argv[0]. Each successive increment moves it along to the next argument; *argv is then the pointer to that argument. At the same time, argc is decremented; when it becomes zero, there are no arguments left to print.
Alternatively, we could write the printf statement as
printf((argc > 1) ? "%s " : "%s", *++argv);
This shows that the format argument of printf can be an expression too.
As a second example, let us make some enhancements to the pattern-finding program Following the lead of the UNIX program grep, let us enhance the program so the pattern to be matched is specified by the first argument on the command line.
#include <stdio.h>
   #include <string.h>
   #define MAXLINE 1000

   int getline(char *line, int max);

   /* find:  print lines that match pattern from 1st arg */
   main(int argc, char *argv[])
   {
       char line[MAXLINE];
       int found = 0;

       if (argc != 2)
           printf("Usage: find pattern\n");
       else
           while (getline(line, MAXLINE) > 0)
               if (strstr(line, argv[1]) != NULL) {
                   printf("%s", line);
                   found++;
               }
       return found;
   }
The standard library function strstr(s,t) returns a pointer to the first occurrence of the string t in the string s, or NULL if there is none. It is declared in <string.h>.
The model can now be elaborated to illustrate further pointer constructions. Suppose we want to allow two optional arguments. One says ``print all the lines except those that match the pattern;'' the second says ``precede each printed line by its line number.''
A common convention for C programs on UNIX systems is that an argument that begins with a minus sign introduces an optional flag or parameter. If we choose -x (for ``except'') to signal the inversion, and-n (``number'') to request line numbering, then the command
find -x -npattern
will print each line that doesn't match the pattern, preceded by its line number.
Optional arguments should be permitted in any order, and the rest of the program should be independent of the number of arguments that we present. Furthermore, it is convenient for users if option arguments can be combined, as in
find -nx pattern
Here is the program:
#include <stdio.h>
   #include <string.h>
   #define MAXLINE 1000

   int getline(char *line, int max);

   /* find: print lines that match pattern from 1st arg */
   main(int argc, char *argv[])
   {
       char line[MAXLINE];
       long lineno = 0;
       int c, except = 0, number = 0, found = 0;

       while (--argc > 0 && (*++argv)[0] == '-')
           while (c = *++argv[0])
               switch (c) {
               case 'x':
                   except = 1;
                   break;
               case 'n':
                   number = 1;
                   break;
               default:
                   printf("find: illegal option %c\n", c);
                   argc = 0;
                   found = -1;
                   break;
               }
       if (argc != 1)
           printf("Usage: find -x -n pattern\n");
       else
           while (getline(line, MAXLINE) > 0) {
               lineno++;
               if ((strstr(line, *argv) != NULL) != except) {
                   if (number)
                       printf("%ld:", lineno);
                   printf("%s", line);
                   found++;
               }
           }
       return found;
   }
argc is decremented and argv is incremented before each optional argument. At the end of the loop, if there are no errors, argc tells how many arguments remain unprocessed and argv points to the first of these. Thus argc should be 1 and *argv should point at the pattern. Notice that *++argv is a pointer to an argument string, so (*++argv)[0] is its first character. (An alternate valid form would be **++argv.) Because [] binds tighter than * and ++, the parentheses are necessary; without them the expression would be taken as *++(argv[0]). In fact, that is what we have used in the inner loop, where the task is to walk along a specific argument string. In the inner loop, the expression *++argv[0] increments the pointerargv[0]!
It is rare that one uses pointer expressions more complicated than these; in such cases, breaking them into two or three steps will be more intuitive.

Concept of Pixel in C Graphics


Concept of Pixel in C Graphics Wondering What a Pixel is!!!!!!!
            
Pixel is otherwise called as picture elements. These are nothing but small dots. Using these tiny dots or in other words pixels images especially graphics images are built on screen. 
If all pictures are built by concept of pixel then wondering how each picture differ that is how
some picture appear more brighter while some other have a shady effect. All this is by the
concept or technically terminology called as resolution.
So let’s have an insight on this important terminology.
Resolution is the number of rows that appear from top to bottom of a screen and in turn the
 number of pixels or pixel elements that appear from left to right on each scan line. Based on
 this resolution only the effect of picture appears on screen. In other words greater the
resolution
greater will be the clarity of picture. This is because greater the number of dots greater will
be sharpness of picture. That is resolution value is directly proportional to clarity of picture.
There are generally two modes available namely text and graphics. In a graphics mode we
have generally the following adapters namely CGA called as Color Graphics Adapter,
EGA and VGA. Each adapter differs in the way of generating colors and also in the number
of colors produced by each adapter. Pixel being a picture element when we consider the
graphics mode each pixel
 has a color associated with it. But the way these colors are used depends on adapters because
 each adapter differs in the way they handle colors and also in the number of colors supported.
Having known about adapters now let us start knowing on how to start switching to graphics
 mode from text mode in other words how to start using pixel and resolution concepts.
This is done by a function called intigraph ( ).This intigraph ( ) takes in it 2 main arguments as
input namely gd and gm.
In this gd has the number of mode which has the best resolution. This is very vital for graphics
 since the best resolution only gives a sharper picture as we have seen before. This value is
obtained by using the function called as getgraphmode ( ) in C graphics. The other argument
gm gives insight about the monitor used, the corresponding resolution of that, the colors that
are available since this varies based on adapters supported. This value is obtained by using
the function named as getmodename ( ) in C graphics.
Graphics function in C and Pixel concept in that
There are numerous graphics functions available in c. But let us see some to have an
understanding of how and where a pixel is placed in each when each of the graphics
function gets invoked.
Function:
putpixel(x, y, color) 
Purpose:
The functionality of this function is it put a pixel or in other words a dot at position x, y
given in inputted argument. Here one must understand that the whole screen is imagined
as a graph. In other words the pixel at the top left hand corner of the screen represents
the value (0, 0).
Here the color is the integer value associated with colors and when specified the picture
element or the dot is placed with the appropriate color associated with that integer value.

Function:
Line(x1, y1, x2, y2)
Purpose:
The functionality of this function is to draw a line from (x1,y1) to (x2,y2).Here also the
coordinates are passed taking the pixel (0,0) at the top left hand corner of the screen
as the origin. And also one must note that the line formed is by using number of pixels
placed near each other. 

Function:
getpixel(x, y)
Purpose:
This function when invoked gets the color of the pixel specified. The color got will be the
integer value associated with that color and hence the function gets an integer value as
return value.
So the smallest element on the graphics display screen is a pixel or a dot and the pixels
are used in this way to place images in graphics screen in C language.

Call by Value and Call by Reference


Call by Value and Call by Reference

In this tutorial you will learn about C Programming - What is difference between call by value and call by reference in function?

The arguments passed to function can be of two types namely

1. Values passed
2. Address passed
The first type refers to call by value and the second type refers to call by reference.

For instance consider program1

main()
{
int x=50, y=70;
interchange(x,y);
printf(“x=%d y=%d”,x,y);
}

interchange(x1,y1)
int x1,y1;
{
int z1;
z1=x1;
x1=y1;
y1=z1;
printf(“x1=%d y1=%d”,x1,y1);
}
Here the value to function interchange is passed by value.

Consider program2

main()
{
int x=50, y=70;
interchange(&x,&y);
printf(“x=%d y=%d”,x,y);
}

interchange(x1,y1)
int *x1,*y1;
{
int z1;
z1=*x1;
*x1=*y1;
*y1=z1;
printf(“*x=%d *y=%d”,x1,y1);
}
Here the function is called by reference. In other words address is passed by using symbol & and the value is accessed by using symbol *.

The main difference between them can be seen by analyzing the output of program1 and program2.

The output of program1 that is call by value is

x1=70 y1=50
x=50 y=70
But the output of program2 that is call by reference is

*x=70 *y=50
x=70 y=50
This is because in case of call by value the value is passed to function named as interchange and there the value got interchanged and got printed as

x1=70 y1=50
and again since no values are returned back and therefore original values of x and y as in main function namely

x=50 y=70 got printed.

But in case of call by reference address of the variable got passed and therefore what ever changes that happened in function interchange got reflected in the address location and therefore the got reflected in original function call in main also without explicit return value. So value got printed as *x=70 *y=50 andx=70 y=50



The Preprocessor


C Language - The Preprocessor

In this tutorial you will learn about C Language - The Preprocessor, Preprocessor directives, Macros, #define identifier string, Simple macro substitution, Macros as arguments, Nesting of macros, Undefining a macro and File inclusion.

The Preprocessor

A unique feature of c language is the preprocessor. A program can use the tools provided by preprocessor to make his program easy to read, modify, portable and more efficient.

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.