Monday, December 13, 2010

C graphics


Your Screen For C graphics



C graphics.h tutorial
The most basic thing you have to learn before stepping in the C shore of graphics is about the monitor.
Loading The Header
#include<stdio.h>  
#include<graphics.h>  
void main()  
{  
}

#include<stdio.h>
#include<graphics.h>
void main()
{
}
C graphics.h
The C graphics.h is the header file which should be included to initalize your computer to start using grahipcs methods and also to initialize the monitor.These kinds of statements before the main program are called preprocessor dierctives.Its very simple as coded below.

Initializing  C graphics library
This initialization is done inside the main program.The method initgraph()  is used for this purpose there are three parameters for this , the first two are of integer type and the next is the path which you can leave blank in quoutes to take the default path.The integer parameters are initalized in this method for all the C graphics programs so you just need to memorize it and apply it for all C graphics programming from now on.

Initializing 'Graphics Driver' and 'Graphics Mode' from C graphics library
  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. #include<graphics.h>  
  4. void main()  
  5. {  
  6. int gdriver=DETECT,gmode;  
  7. initgraph(&gdriver,&gmode," ");  
  8. }  
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode," ");
}
Methods In C Graphics programming
1.      cleardevice()  
2.      gotoxy(x,y)  
3.      putpixel(x,y,WHITE)  
4.      outtextxy(x,y,"HELLO")  
5.      rectangle(x,y,int x_width,int y_height)  
6.      circle(x,y,radius)  
7.      line(x1,y1,x2,y2)  
8.        moveto(dx,dy)  
9.      lineto(x,y)  
10.  ellipse(x-centre,y-center,starting_angle,ending_angle,x_radius,y_radius)  
11.  drawpoly(num_of_points + 1, points)  
12.  settextstyle(DEFAULT_FONT,HORIZ_DIR,1)  
13.  setfillstyle(SOLID_FILL,RED)  
14.  setcolor(CYAN)  
15.  floodfill(x,y,getmaxcolor())  
16.  setviewport(int left,int top,int right,int bottom, int clip)  
17.  setviewport(10,10,630,470,1)  
18.    itoa(x1,st1,10)  
19.    delay(100)  
20.    closegraph()
putpixel(x,y,WHITE)
outtextxy(x,y,"HELLO")
rectangle(x,y,int x_width,int y_height)
circle(x,y,radius)
line(x1,y1,x2,y2)
moveto(dx,dy)
lineto(x,y)
ellipse(x-centre,y-center,starting_angle,ending_angle,x_radius,y_radius)
drawpoly(num_of_points + 1, points)
settextstyle(DEFAULT_FONT,HORIZ_DIR,1)
setfillstyle(SOLID_FILL,RED)
setcolor(CYAN)
floodfill(x,y,getmaxcolor())
setviewport(int left,int top,int right,int bottom, int clip)
setviewport(10,10,630,470,1)
itoa(x1,st1,10)
delay(100)
closegraph()
Some Common C Graphics Programming Methods
Well, these are some of the most popular C Graphics Methods used in while graphics programming soon after you learn these you can think of developing small games , puzzles and so on.I'll just give only a small overview on each methods.x,y,x1,y1,x2,y2 etc are all variables you'll have to substitute with numeric values to get working programs.Further clear-cut reference can be obtained from any of the C graphics book available from amazon or your local library(those books would be pretty old and dusty by now). If you find it difficult to view the long C graphics library functions code in the window because the code is too lengthy, then click on the 'view plain' written in small fonts at the top left of the codes box on the left side of this text.
Cleardevice()
Clears all previous graphical outputs generated by the previous programs.Its a good practice to include this method at the starting of each program.
gotoxy()
This will initialize the graphics cusor to the specified co-ordiante.In C gotoxy function is used very frequently to locate the cursor at different locations whenever as necessary.
putpixex()
It will colour the pixel specified by the co-ordinates.
outtextxy()
This method is used to display a text in any position on the screen.The numeric coordinates are substituted for x and y.
rectangle()
Draws a rectangle according to the given parameter x and y are the top-left corner co-ordinates.
circle()
Draws a circle with x,y as the center .
line()
Draws a line as per the given co-ordinates.
moveto()
Cursor is moved from the current location to the specified location dx,dy.These parameters can also be used as incremental values.
lineto()
Draws a line from its current location to the co-ordinate(x,y)
ellipse()
Draws the ellipse with the specified angles and coordinates.
drawpoly()
Draws a polygon with (num_of_points +1) edges.The array 'points'
int points[ ]=(x1,y1,x2,y2,x3,y3...)
settextstyle()
The fonts available are :TRIPLEX_FONT, SMALL_FONT, SANS_SERIE_FONT, GOTHIC_FONT
The direction can be changed as HORIZ_DIR or VERT_DIR
The charecter size increases from 1 to 10
setfillstyle()
The fill styles avaliable are SOLID_FILL, LINE_FILL, HATCH_FILL, SLASH_FILL etc.
setcolor()
Sets the color
floodfill()
The function fills the enclosed area about x,y with the highest value of the color returned by the getmaxcolor().
setviewport()
This marks a rectangle starting from (10,10) having widht 630 pixels height 470 pixels.The integer specifies this identified area may be clipped. clearviewport() reverse this function.
itoa()
Converts the integer x1into an alphabet, and puts it in st1, which is an array to hold 10 characters.10 is the buffer size.
delay()
Cause a pause in execution of the program 1000ms= 1 second
closegraph()
Terminates all graphics operations and revert the hardware back to the normal mode.


Wednesday, December 8, 2010

java - part 1


Java Data and Variables

Java Data and Variables
There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the eight primitive data types are:
byte
short
int
long
float
double
char
boolean
There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers. 
Integer Primitive Data Types
Type
Size
Range
byte
8 bits
-128 to +127
short
16 bits
-32,768 to +32,767
int
32 bits
(about)-2 billion to +2 billion
long
64 bits
(about)-10E18 to +10E18

Floating Point Primitive Data Types
Type
Size
Range
float
32 bits
-3.4E+38 to +3.4E+38
double
64 bits
-1.7E+308 to 1.7E+308
Examples
int yr = 2006;
double rats = 8912 ;
         For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes:
primitive type
Wrapper type
byte
Byte
short
Short
int
Int
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
 Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of as a little box made up of one or more bytes that can hold a value of a particular data type:
Syntax: variabletype variablename = data;
Source Code ( demonstrating declaration of a variable )
class example
{
  public static void main ( String[] args )
  {
    long x = 123;    //a declaration of a variable named x with a datatype of long

    System.out.println("The variable x has: " + x );
  }
}
Source Code
public class MaxDemo {
     public static void main(String args[]) {
     //integers
          byte largestByte = Byte.MAX_VALUE;
          short largestShort = Short.MAX_VALUE;
          int largestInteger = Integer.MAX_VALUE;
          long largestLong = Long.MAX_VALUE;

         //real numbers
         float largestFloat = Float.MAX_VALUE;
         double largestDouble = Double.MAX_VALUE;

         //other primitive types
        char aChar = 'S';
        boolean aBoolean = true;

        //Display them all.
        System.out.println("largest byte value is " + largestByte + ".");
        System.out.println("largest short value is " + largestShort + ".");
        System.out.println("largest integer value is " + largestInteger + ".");
        System.out.println("largest long value is " + largestLong + ".");
        System.out.println("largest float value is " + largestFloat + ".");
        System.out.println("largest double value is " + largestDouble + ".");
   }
}

Sample Run
The largest byte value is 127.
The largest short value is 32767.
The largest integer value is 2147483647.
The largest long value is 9223372036854775807.
The largest float value is 3.4028235E38.
The largest double value is 1.7976931348623157E308.
Class Definition Files
Files containing Java class definitions follow these guidelines;
  • A Java class definition must be fully enclosed within a single file.
  • The file name must match exactly, in upper and lower case, the name of a class definition in the file.
  • It's recommended to put each class definition into its own file except for small utility classes needed only by the primary class.
  • Only one public class is allowed per file (see Access/Visibility rules).
  • The compilation of a Java file will result in separate *.class bytecode files for each class definition in the file.
Packages
A package is the Java version of a library. A package refers simply to a group of related class files in the same directory and having in each class file a package directive (Java statements only occur within a class definition) with that directory name at the top of the file.
For example, say that we put the files TestA.java and TestB.java into the directory mypack, which is a subdirectory of myApps. So on a MS Windows platform the file path looks like
  c:\myApps\mypack\TestA.java
and
  c:\myApps\mypack\TestB.java.
At the top of each file we put the statement
  package mypack;
as shown in the following code:
package mypack;
public class TestA
{

  public int i;
  public TestA (int arg1) {
    i = arg1;
  }
}
package mypack;
public class TestB
{
  public double x;
  public TestB (double y) {
    x = y;
  }
}
We can illustrate how to use a package with TestAB.java which we put in the next directory above that of the package mypack.
myApps/TestABApplet.java
(Output goes to browser's Java console.)
public class TestABApplet extends java.applet.Applet
{
  public void init ()  {
    mypack.TestA testa = new mypack.TestA (4);
    mypack.TestB testb = new mypack.TestB (31.3);
    System.out.println("Prod = " + (testa.i * testb.x));
  }
  // Paint message in Applet window.
  public void paint(java.awt.Graphics g) {
     g.drawString ("TestABApplet",20,20);
  }
}


TestAB.java (application) 
From the command line in the directory myApps, the compilation of TestAB.java:
  myApps> javac TestAB.java
will also lead to the compilation of the files in mypack. The compiler looks for the TestA and TestB class definitions using the combination of the package and class names mypack.TestA testa and mypack.TestB. The "." acts in this case like the slash line directory name separator in DOS or Unix.
In this case the compiler will look for a sub-directory named mypack in the current directory holding TestAB.java. When the compiler finds the files and they have not yet been compiled, it will do the compilation.
You can also compile the package files directly but the compilation must occur from the higher directory, as in.
   myApps> javac mypack\TestAB.java
(If you try to compile from in the mypack directory, the compiler will say it cannot find the files.)
So a directory browser shows a file and directory organization as follows:


Just as a directory can contain sub-directories, a package can contain sub-packages. For example, here we create add extrapack as a sub-package of mypack


The class definition for TestC belongs to the package mypack.extrapack, as indicated here by the package statement at the top of the file:
package mypack.extrapack;

public class TestC
{
  public boolean flag;
  public TestC(boolean b) {
    flag = b;
  }
}
Note: By convention, package names begin with a lowercase letter, while classes begin with an uppercase letter.
Namespace
In addition to organizing classes in a clearly defined manner, packages also prevent name collisions. That is, if you use classes from other sources, it is inevitable that eventually duplicate class names will occur. If they are in different packages, however, this is not a problems since their full package names would differ.
Of course, it's also possible that two packages from different sources could also have the same names. An ingenious naming convention promulgated by Sun from the earliest days of Java is to name packages based on a company's internet domain name with the order of the names reversed. Since domain names are unique, package names based on domain names are completely under the control of the company that owns that domain name. Thus our companies ABC and XYZ would probably name their packages com.abc and com.xyz, respectively.
import
If a program needed to create an instance of TestC, it can explicitly give the full package path name, also referred to as the the "fully qualified" name:
    mypack.extrapack.TestC testc = new mypack.extrapack.TestC();
An exception to this rule holds for all the classes in the standard java.lang package. Thus, whenever we use the Float class, for instance, we merely use something like
  Float someFloat = new Float (3.14);
For all other classes, however, the fully qualified names must be specified in some way. There are nearly 3000 classes in the 135 packages in the J2SE 1.4.2 standard class library (over 3000 classes in 165 packages in J2SE 5.0). Commercial class libraries that you might use add many more packages.
Such long names obvious become unwieldy when a program involves many different classes from many different packages. The Java compiler allows instead for a short cut.
The import directive tells the compiler where to look for the class definitions when it comes upon a class that it cannot find in the default java.lang package. So, for example, in the class definition below for TestABC, the import statements
import mypack.*;
import mypack.extrapack.*;
import java.applet.*;
indicate that classes can be found in the mypack and mypack.extrapack packages and also that the Applet class can be found in the java.applet package.
myApps/TestABCApplet.java
(Output goes to browser's Java console.)
import java.applet.Applet;
import mypack.*;
import mypack.extrapack.*; public class TestABCApplet extends Applet
{
  public static void init (String [] arg) {
    TestA testa = new TestA (4);
    TestB testb = new TestB (31.3);
    if( testc.flag)
        System.out.println ("testa.i = "+testa.i);
    else
        System.out.println ("testa.x = "+testb.x);
  }
  // Paint message in Applet window.
  public void paint(java.awt.Graphics g) {
     g.drawString ("TestABACpplet",20,20);
  }
}
TestABC.java (application)
 The first import statement gives the full package path name for the Applet class in the packages included with the standard JVM. Then when the compiler sees just Applet in the class definition title, it will know where to find it.
In the next two import statements, we see the "*" wildcard character used for the classes in the mypack and mypack.extrapack packages. This indicates that these packages hold multiple classes and the compiler should look here if it cannot find a class in the core packages.
The wildcard only applies to classes, not to sub-packages. That is, mypack.* only refers to the classes in the package, not to the sub-directory extrapack. You must import each package name separately.
If the packages that you import happened to have two classes with the same name, to use one of them you will need to give the fully qualified name so that the compiler will know which of these classes you want to use.
Notes
Note 1: C/C++ programmers usually assume that an import statement brings code into the .class bytecode files in a similar manner as the include statements in C/C++. However, that is not the case. An import statement simply provides an address where the compiler can look for class definitions.
We will also point out that Java is a so-called late binding object language, which means that it does not load class definitions until they are needed during processing. In fact, while a program is running it can dynamically load a class that was never mentioned in the source code. (For example, the class name could be read in from a file.)
Note 2 : To insure the uniqueness of package names, Sun proposes that the package name include your domain name (if you own one). For example,
   com.mycompany.mypack.Test;
indicates that the Test class file belongs to the the mypack package owned by mycompany.com.



Access (Visibility) Rules
Access or visibility rules determine whether a method or a data variable can be accessed by another method in another class or subclass.
We have used the public modifier frequently in class definitions. It makes classes, methods, or data available to any other method in any other class or subclass.
Java provides for 4 access modifiers :
  1. public - access by any other class anywhere.
  2. protected - accessible by the package classes and any subclasses that are in other packages .
  3. Default - (also known as "package private") accessible to classes in the same package but not by classes in other packages, even if these are subclasses.
  4. private - accessible only within the class. Even methods in subclasses in the same package do not have access.
Note that a java file can have only one public class.
These access rules allow one to control the degree of encapsulation of your classes. For example, you may distribute your class files to other users who can make subclasses of them. By making some of your data and methods private, you can prevent the subclass code from interfering with the internal workings of your classes.
Also, if you distribute new versions of your classes at a later point, you can change or eliminate these private attributes and methods without worrying that these changes will affect the subclasses.
As we mentioned earlier, if you do not put your class into a package, it is placed into the "default unnamed package". For simple demonstration programs this usually suffices. However, with more serious programs you should use packages since otherwise any other class in the unnamed package has access to your class's fields and methods that are not set to private.
final Modifier & Constants
The final modifier indicates that a data field cannot be modified, as in
    final double PI = 3.14;
Any attempt to assigne PI to a new value will result in a runtime error. Thus final makes data useful as constants.
Often such constants are needed by other classes, so they are declared static as well, as in
  public class MyMath
  {
    public final static double TWO_PI = 6.28;
    ...
  }

Then other classes can then reference it, as in
    ...
    double y = theta / MyMath.TWO_PI;    ...

final Methods
The final modifier is also used with methods to indicate that they cannot be overriden by subclasses.
  public class MyMath
  {
    ...
    public final double MyFormula() {
      ...
    }
  }

This helps to improve their performance since the JVM will not need to check for overriding versions with the method is invoked.