Thursday, September 30, 2010

Multidimensional Arrays

Arrays in Methods

Array Elements as Counters




thank you for watching this tutorial. i hope you learn about java programming...

Summing Elements of Arrays




enjoy watching video and learn in my blog... thank you readers...

Summing Elements of Arrays




enjoy watching video about java programming... thank you

Summing Elements of Arrays




enjoy watching video about java programming... thank you

Summing Elements of Arrays




enjoy watching video about java programming... thank you

Summing Elements of Arrays




enjoy watching video about java programming... thank you

Constractor



enjoy..............

Table for Multi Arrays

Random Number Generator

Creating an Array Table

Arrays

Graphical User Interface GUI



enjoy learning in my blog.. thank you

Reading from files




learn and enjoy watching java programming video

Reading from files




learn and enjoy watching java programming video

Tuesday, September 28, 2010

Multiplication table using Array

public class sample

{
public static void main(String args[])
{
int arr[][]=new int[10][10];
int x,y;
for(x=1;x<=arr.length-1; x++)
{
for(y=1;y<=arr.length-1; y++)
{
System.out.print(" \t");
System.out.print(arr[x][y]=x*y );
}
System.out.print("\n");

}
}
}

Sunday, September 26, 2010

Password PUK

import java.io.*;
import java.util.Scanner;
 public class PUK
 {
  public static void main(String args[])
  {
   Scanner input=new Scanner(System.in);
  
   int P=0;
  
   for(int d=1;d<=3;d++)
   {
    System.out.println("Enter PUK Code:");
    P=input.nextInt();
   
    if(P==1010)
    {
     System.out.println("Successfully Opened!!");
     d=d+3;
    }
    else
    {
     System.out.println("Try Another Password");
    }
   }
   if(P!=1010)
   {
    System.out.println("SIM Block");
   
   }
  
  }
 }


learn and enjoy reading my blogs...

Tuesday, September 21, 2010

Java Tutorial

please visit this website to advance learning .....http://www.kodejava.org

next time i will be post another java programs..

Sunday, September 12, 2010

Java Applet sample program ( simple rectangles in loop)


// Applet to print a group of rectangles
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;

public class Applet1 extends JApplet

{
public void paint(Graphics g)
{
int a = 3;
do
{
g.drawRect(a,a,100,100);
a=a+100;
}
while ( a < 370);
}
}
Programming Fundamentals
Step by Step Guide To Learn How To Program
  1. Different programming languages each have their own syntax and appearance, but my concern here is to acquaint you with the basic nature of programs and how to write and understand them. These concepts are pretty much the same  in all languages. (C++, Java etc.)
  2. In my illustrations below, I will follow the Java syntax
  3. Make up variable names to hold values in the program
  4. Use Variable names that are easy to identify
  5. These variables will take on values when the program executes  -- plan ahead
    so you can create variables that you will need to make the program function.
    This is a hard task because you need to be able to envision the program executing.
    You have to write the commands or steps for this execution. Different tools such as flowcharts can help in this task but basically you have to be able to see the solution to the problem and write the steps to make it happen. -- HARDEST THING FOR STUDENTS TO LEARN.
  6. Beginning programmers will normally be told WHAT THE PROGRAM IS EXPECTED TO PRODUCE and WHAT THINGS OR DATA THE PROGRAM HAS TO WORK WITH.
  7. In essence, program will process data and produce output results. Keep this in mind
    as you review all the code that follows.
  8. I will use // for comments in all the code examples that follow Comments are for documentation purposes only and do not affect a program's execution.
  9. The programmer then starts to create variables and uses the commands for the specific language to solve the problem.
  10. Data that is to be processed is normally put into variables in one of two ways:
    ... ASSIGNED           denoted by an = sign.
    ... INPUTTED    from the keyboard or from a file
  11. Remember that a variable can hold only one thing at a time for example someone's age, weight, name, address  etc.
  12. We have different types of variables based upon the type of data that they can hold.
  13. Common types are integer, float, Char, String, Boolean.
  14. Integers hold whole numbers
    Floats hold numbers involving decimal points
    Char holds one character like 'M'  or 'F'
    Strings hold groups of characters like people's names
    Boolean holds true or false state  not "true" but value true.
  15. The actual commands in a programming language are simple to understand
    and there are not very many of them
  16. Command in a language can t\really be broken down into 4 types
    Commands for assigning data to variables
    commands for inputting data into variables
    Commands for outputting the data that is in variables
    Commands for controlling the order of processing the above three Command types
  17. In short, the actual commands in a programming language are easy to understand.
    It is truly understanding the concept of variables and how to use them, that is difficult for the beginning programmer.
  18. Students must accept the fact that the computer only does one thing at a time.
    It just does it extremely fast. (Like millions of commands in a split second)
  19. You must know how to solve a problem in your mind or you cannot program the computer to do it for you.
  20. You must learn to break down the solution to a problem that exists in your mind
    into small steps because remember the computer only does one thing at a time.
  21. A good example is as follows:
    Look at 3 number and tell me the largest. Anyone can do this if you ask them to.
    But in writing a program to do this, you must be able to breakdown the little steps that your mind went through in solving the problem. You might say I just looked at the 3 numbers and spotted the largest and the rest is history.  To program the computer to solve this problem, you must be a whole lot more specific and detailed.
    FOR EXAMPLE:
    ... which number did you look at first
    ,,, is the first one looked at automatically the highest to start
    ... how is your mind comparing the numbers
    ... how do you know when to quit
    ... etc.
  22. Remember that understanding variables are the key to programming and DO NOT FORGET that a variables can only hold one value at a time. That does not mean that a variable cannot be reused or added to etc. It just means that at any instant in time
    a variable will only have one specific value in it.
  23. Remember that beginning programmers will normally be told what is their input for the program and what is expected as output.
  24. In the above problem, a teacher might say:
    INPUT the 3 number one at a time, and find the largest  or
    he might say ASSIGN the 3 number to 3 different variables and go from there
    to find the largest.
  25. You can see from this that a programmer must be aware of how the 3 numbers are going to get into the program for processing.
  26. Next the programmer needs to know how to compare things (to find the largest)
    The program does not just look and it knows (like we think our mind does because
    we have done such a task millions of times)
  27. An "if" statement is used by the programmer to compare things. It is really the same as the one that our mind uses in comparing things.
  28. The "if" statement is an important control statement in all programming languages.
  29. The "if" statement is what allows programs to make decisions and in the above example aren't we trying to decide which number is the largest.
  30. To reiterate some important points:
    Data is assigned or input into variables
    Programs can compare the data that is in variables , knowing that a variable can only hold one value at a time, by using "if" statements.
  31. One more important point to note here:  Programs refer to variables in all their
    commands. But remember that it is the data that is in the variable that is actually being referred to. Put another way, variables are symbolic names for data that has been put into the variable.
  32. Some schools of thought will teach students to write programs by organizing their logic using different approaches --  flowcharting or breaking the  program down into smaller pieces. These approaches are right but I am taking this to a simpler level.
    We will analyze variables and commands to a point that we totally understand them -- then we can talk about organizing our logic according to a more sophisticated scheme.
  33. Variables are what the program actually manipulates or plays with.
  34. Variables will always be created with an exact purpose in mind.
  35. If you do not know why you are creating a variable then you probably do not need it or you do not know the real nature of the problem or how to solve it.
  36. Some variables will be reused by the programmer. They will take on a value by
    assignment or inputting and  after the commands have dealt with the variable (its value), THE VARIABLE CAN BE REUSED. Variables used for this purpose are normally associated with inputting data (from keyboard or file) into our program.
  37. Other variables will take on values (usually by assignment) and these variables
    will not be reused because these values are to be maintained until the program has completed execution. Counters are good examples of these types.
  38. Remember that when declaring or creating variables, use names easy to identify and make sure that the TYPE of variable your choose is appropriate for the values or data that it will contain.
  39. I need to explain the following 5 commands before we can start writing programs:
    ... assignment statement
    ... input statements and output statements
    ... if statements
    ... do  while   statements
  40. Assignment statements are use whenever you want to put a value directly into a variable.    SYNTAX is   variable = expression;
    Only one variable on the left of = sign. The = sign means "is assigned the value of".
    On the right of the = sign, you can have variables, constants, or a combination of these separated by arithmetic operators.
    e.g..   count = 0;                                      // used for comments  initialize count to 0
            total = num1 + num2;
            avg = (n1+n2+n3+n4)/4;
            counter = counter +1;                     // add 1 to counter
  41. In the above notice how commands end in a semi colon and notice how comments are used to help describe the actions
  42. I recommend that you declare all your variables at the top of the program, prior to|
    their usage. In that case the variable declarations listed below would precede the commands demonstrated in step 41 above.

       // declare all your variables at top of program
           int count;
           float n1,n2.n3.n4,avg;
           int num1,num2,total;
           int counter;
  43. By the way variable names are made up of letters, numbers, and underscore character. Capital and small letters are allowed.
    EXAMPLES  
                   bb                                   // okay but too short for identification purposes
                   male_counter                                     // good name
                   counter_for_males_whoi_are_heavy     // okay but too much typing
  44. INPUT and OUTPUT statements can take many forms in java but for simplicity
    I will use the         
                                System.out.print          // to print results to the screen
                                System.out.println        // print results to screen and
                                                                     advance to the next line
                                File.read...                  // to input data or values from a file
             the ...  will be substituted by Int, Char, Float, UTF(string data)
  45. Remember that when you are inputting data you normally input logical units
    not isolated characters or numbers. For example MARY not M and A and R and Y
    or 212 as someone's weight not 2 and 1 and 2. I think you see my point.
  46. When inputting more than one thing in the input stream, a space normally is used to separate the logical units noted above.
  47. The actual use of the 2 commands noted above for input and output will become obvious in the examples that follow.
  48. IF statements are used for decision making within the program.
    A simple if statement takes the following form
          if ( condition)
           {
                  // any statements that you want to do if the condition is true
            }
              else
            {
                  // any statements that you want to do if the condition is false
             }
  49. In the above example
    1...  the else is optional
    2...  the brackets can be deleted if you only want to do one statement
           in the block
    3...  the condition is any valid expression or comparison that can be
                evaluated to true or false
  50. Condition normally involve relational symbols like > < ==  != etc. which stand for less than   greater than   equal to     not equal to. I think you imagine what some other might be.
  51. Last I will describe the do  while  command sequence
          do
            {
                                            // in English -- perform the statements in the brackets
                                            // as long as the condition is true

            }
              while(condition);
  52. All java programs have a weird set of statements called a shell. I will not deal with them because that will only confuse the issue. They are required   and most advanced programmers know their purpose. .
Understand all the examples that follow and you are on the way to programming
In order to show many examples and not confuse students with the
inputting of values from the keyboard or from a file, I will not get into some of the technical issues concerning input of data.  In all my examples I will use a 

file.read...  command.  Depending on the type of data being read, I will substitute a Chr, Int, Float, UTF ( for strings data )  in place of the ...   Therefore we can concentrate on logic development and not dwell on one slightly technical issue.
1
// assign a value to num1 and num2 and compute the total

int num1,num2,total;            // declare 3 integer variables
num1=10;
num2=33;
total = num1 + num2;          // get the sum into total
System.exit(0);
2
// input an integer and print it 3 times

int number;
file.readInt(number);
System.out.print(number);       // print the data 3 times on same line
System.out.print(number);
System.out.print(number);
System.exit(0);
3
// input an integer and print 3 times on separate lines using loop int number,counter;                         // declare variables
counter=0;                                        // initialize loop counter
number=file.readInt();                      // input aan integer number   
do
  {
     System.out.println(number);       // print the number and go to next line
     counter = counter + 1;                 // increment counter
  }
   while(counter < 3);
System.exit(0);
4   simple if and else but only one command in each branch
// input 2 integer numbers and print the largest int number1,number2;
number1=file.readInt(); 
number2=file.readInt(); 
if(number1 > number2)
      System.out.print(number1);
    else
       System.out.print(number2);
Sysatem.exit(0);
5   simple if with no else
// input 2 integer numbers and print "hello" only if first number beats second int number1,number2;
number1=file.readInt(); 
number2=file.readInt(); 
if(number1 > number2)
    System.out.println("hello");
System.exit(0);

6   reading a string
// input a person's name, then their age and print the name one time
// for each year in their age String name;
int age,count;
count=0;
name=file.readUTF();         // how strings are read like people's names
age=file.readInt();
do
   {
     System.out.println(name);
     count=count+1;
   }
    while(count
    System.exit(0);

7   concatenation
// inpu someone's age and tell how many tines a 5 wil divide evenly the age

Int age,number _of_times;
number_of_times=0;
age=file.readInt();
if(age>=5)
   {
      do
         {
             age=age-5;
             number_of_times=number_of_times+1;
         }
            while(age>=5);
   }
// example of printing a heading along with a result in output to screen
// also demonstrates concatenation   sticking things together  using +
System.out.println("number 5 went into age variable " + number_of_times);
System.exit(0);
8   truncation involving integers
// same program as #7 but demonstrates truncation which occurs when
// two integers are divided (all fractions are dropped)

Int age,number _of_times;
number_of_times=0;
age=file.readInt();
number_of_times = age / 5;
System.out.println("number 5 went into age variable " + number_of_times);
System.exit(0);
9   ++ shortcut operator
// print the number 1 thru 20 on separate lines in output int num=1;          // declaring aan int variable and initializing at same time
do
   {
      Syste.out.println("number is "+num);
      num ++;             // another way of adding 1 to a variable
   }
     while ( num <= 20);
System.exit(0);
10   if      with multiple items in true branch
// print number 1 thru 100 such that only 10 values will appear on each
// output line int num=1;     
int line_count=0;
do
   {
      Syste.out.print(num+" ");
      num ++;             // another way of adding 1 to a variable
      line_count ++;
      if(line_count = 10)
         {
            Syste.out.println();
            line_count = 0;
         }    
   }
     while ( num <= 100);
System.exit(0);
11   nested  if  statements
// input 3 integer numbers and print only the largest int number1,number2,number3;
number1=file.readInt(); 
number2=file.readInt(); 
number3=file.readInt();

if(number1 > number2)
  {
     if(number1 > number3)
           System.out.println("largest one is "+number1);
       else
            System.out.println("largest one is "+number3);
   }
   else
   { 
    if(number2 > number3)
           System.out.println("largest one is "+number2;
        else
           System.out.println("largest one is "+number3;
    }
System.exit(0);
12
// student took 4 courses enter hours credit and letter grade
// and comput his/her grade point average

int count=0;
char letter;
int hours;
float gpa;
float tot_hours=0;
float tot_quality_points=0;
do
  {
    letter=file.readChar();
    hours=file.readInt();
    if(letter == 'A') tot_quality_points=tot_quality_points +( 4 * hours);
    if(letter == 'B') tot_quality_points=tot_quality_points +( 3 * hours);
    if(letter == 'C') tot_quality_points=tot_quality_points +( 2 * hours);
    if(letter == 'D') tot_quality_points=tot_quality_points +( 1 * hours);
    if(letter == 'F') tot_quality_points=tot_quality_points +( 0 * hours);
    tot_hours = tot_hours + hours;
    count ++;
  }    while ( count < 4);
   gpa =  tot_quality_points / tot_hours;
   System.out.println("gpa for this student is "+gpa)'
   System.exit(0);
13   use of  %  (remainder)  and   continue (stay in loop but skip to the while
// add up the numbers between 1 and 1000 but skip and number that
// is evenly divisable by 7

int count=0;
int total=0;
int rem;
do
   {
     count ++;
     rem = count % 7;   // perform division but assign remainder to 'rem'
     if (rem == 0)
          continue;
        else
           total = total + count;
   } while (count < 1000);
System.out.println("the total is "+total);
System.exit(0);
SLIGHTLY MORE ADVANCED...
ARRAYS and using FOR LOOPS
Arrays are simply multiple storage locations under one Variable name !!  All the rules concerning variables apply to arrays. The only
thing different is that we must indicate which element in the array
that we are referring to when a specific Java command is executed.
Specific elements or locations are referred to by means of a subscript. One dimensional arrays will have 1 subscript and two
dimensional arrays will have 2 subscripts. The following examples will demonstrate the use of arrays and how to refer to the various elements.   FOR loops are similar to 'do   while'  loops as noted in many of the examples above. They however provide for simplicity
because in one command they specify
     1... starting value of a variable
     2... test condition for doing the loop
     3... what to do to the variable each time thru the loop
 
14  simple one dimensional array example  --  also using 'fof'  loop structure
// declare 1 dimensional integer array, input 10 numbers into the array, and
// print them out in the opposit order as they were read in (as data)
int num[] = new int[10];        // declare 1 dimensional integer array with
                                              //  10 locations.. automatically numbered 0 thru 9
int cnt;
for ( a = 0 ; a <= 9 ; a = a + 1 )
  {
     num[a] = file.readInt();              // read values into the array
  }
for ( a = 9 ; a >= 0 ; a = a - 1 )
  {
    System.out.println( num[a] );     // print values in the array starting with last
  }
System.exit(0);

15
// declare an integer array (one dimensional) and assign the number 1000 thru 10000 to locations 0 thru 9

int num[] = new int[10];
int count = 1000;
int a;
for ( a=0;a<10;a++)
  {
     num[a] = count;
     cpount = count + 1000;
   }
16
// double each value in the array declared in #15 (above)
// and then concatenate all 10 values to a string called  out
// such that when printed, each value and its position in the array
// will be printed on separate lines

String out=" ";
for (a=0;a<10;a++)
  num[a]=num[a] * 2;               // no brackets needed when only 1 statement
for (a=0;a<10;a++)
  out = out + a + num[a] + "/n" );
System.out.println(out);
system.exit(0);
17
// declare a 2 dimensional array called num that is integer and has
// 10 rows and 10 columns. Then put the number 1 thru 100 into the array
// row wise (going accross)

int num[][] = new int[10][10];
int a,b,count;
count = 1;
for (a=0; a<10;a++)         // a is used as the row pointer
  {
     for (b=0;b<10;b++)     // b is used as column pointer
      {                                   // b is the inner loop so it varies quicker
          num[a][b] = count;
          count = count +1;
      }
  }
18
// given the task accomplished in #17 (above)
// add the respective values found in row 0 thru 2 to the respectine values
// found in row 7 thru 9 for (a=0;a<=2;a++)
   {
     for (b=0;b<=9;b++)
       num[a+7][b] = num[a+7][b] + num[a][b];
   }
19   sort
// sort a one dimensional integer array (100elements) high to low
// assume the array already contains data -- array name is num
int a,b,c;
for (a=0; a<=98; a=a+1)
   {
      for (b=a+1; b<=99; b=b+1)
        {
            if ( num[a] < num[b] )
                {
                    c=num[a];                         3 statements to swap values
                    num[a] = num[b};
                    num[b] = c;

                }
         }
   }
20
// a cool way to merely assign values to a 2 dimensional float array
the array dimension are set implicitly by the assignment
// assognment takes place row wise  (accross columns)
// The code below places 15 values into an array that is implicitly
// declared as having 3 rows and 5 columns
float avg[][]={
      {1.5, 2.3, 2.1,9.2,3.3},      
      {2.4,7.9,11.2,9.3,1,7},
      {4.3,4.9,2.8,1.2,33.4)  } ;
21
// add the total of the odd numbered elements in an int one dimensional
// array to each even numbered position ... Assume the array already
// contains values

int n[] = new int [100];
int a,b,t=0;
for(a =1;a<100;a+=2)
  t = t + n{a];
for (b=0;b<100;b=b+2)
  n[b] += t;          // shortcut for n[b] = n[b] + t;
Organizing Your Logic  Into An Executable Program
...3 Different Approaches...
1....Put all your variables and instructions, one after another, and have them execute
2....Organize your logic into smaller pieces called Functions, whereas each Function will perform specific tasks ... more organized approach than number 1
3....Use true Object oriented design where you will create classes which contain their own instance variables and methods (or functions) that allow use and access to the variables
Before discussing the 3 approaches it is important to understand one more thing.  All JAVA programs have a series of IMPORT statements above the program. These statements basically allow the program to have access to different features and capabilities that are inherent in the JAVA language. To keep it simple, think of these statements as allowing your program to use things (code already written)  that will perform a task for you. Saves you having to reinvent the wheel every time you write a program. In the examples below, I will use the word IMPORT at the top of a program to signify this feature. I will not get into specifics as to what different things we are importing. (This is more technical and does not need to be dealt with at this point). As you start to write more sophisticated programs in JAVA, you will see the importance of IMPORTS because you will want to do something  special and you will realize that the feature is available for you if you import a package that will allow you to use the feature.
APPROACH 1
import ......
public class Application1
{
  public static void main(String args[])
       {
        DECLARE ALL VARIABLES
        WRITE ALL JAVA COMMANDS
        System.exit(0);
       }
}
APPROACH 2
import....
public class Application1
{
   public static void main(String args[])
    {
         DECLARE VARIABLES
         function1();     // call function1
         function2();     // call function2      
         System.exit(0);
    }                     // end main method

    public static void function1 () 
    {
       // code to perform operations
    }
   
    public static void function2 ()
    {
       // code to perform other operations
    }
  
}  // end class
APPROACH 3
import .....
public class Application1
{
   public static void main(String args[])
   {
    Budget app = new Budget(); 
// create object of Budget class
    app.EnterName();
    app.EnterAge();
    System.exit(0);
   }
}
public class Budget
{
 private String Name;       // instance variable
  public Budget()           // class constructor
  {
     ......
  }
  public void EnterName()   // method available in the class
  {
     .....
  }
  public void EnterAge()    // another method in the class
  {
     .....
  }
}                           // end of class

Java simplified




Java programs are either Applets or Applications. The first one runs under an
HTML environment in a browser window, the later runs standalone like we
are used to thinking about how programs run. Most of the commands and
features available to one are available to the other. Obviously Applets, since
they are running on someone's computer anywhere in the world must have
some restrictions (e.g.. cannot modify files on someone's computer)

Most of the standard commands and control statements in Java are quite
similar to those of other languages. Assignment statements, if statements,
for-next statements, Do - While statements, etc. are easy to understand and
pretty similar in most languages. However , using these statements to
accomplish some logical end is the first stumbling block that beginning
programmers need to overcome.

Understanding the various data types both primitive and non primitive is
of major importance to Java programmers. Primitive types are pretty obvious
and used in most languages on an everyday basis. Such types are :
int long short double float char Boolean etc.

Non primitive types are referred to as reference variables because they point
to memory locations that contain the values. Strings etc.

In addition to the above another important learning step is how to organize
our program so that it will work. Concepts such as top-down, or styles
that use a modular approach are quite popular. Modular means to divide
the logic into sections of code and then call each section as it is needed.
Think of modules are being small programs. These small programs can
also be called function or even METHODS. Remember that when you use
them , their purpose is to perform some task. Understanding the concept of
Methods is critical to appreciating the power of Java. In addition to Methods
performing tasks (just like a program, they can receive values (to play with)
and return results (if needed).

So in short programs are groups of Methods and variables interacting. In Java
we will refer to this grouping as CLASSES. So instead of writing programs
we are really writing CLASSES. And each of our Classes contains
METHODS (or member function) to perform specific tasks.

Now the real power explained. People have written many CLASSES already.
These CLASSES perform a wide range of tasks for you , so you in essence
do not have to reinvent the wheel every time you need something. These
CLASSES are bundled together into PACKAGES , which you import into
your program (at the top). Common packages are java.awt or java.lang or
java.applet etc. New CLASSES are being developed all the time. Bundled
into packages and made available to the programmer. (java.swing is an
example from our textbook). So in short you are not writing programs, you
are writing classes that can use existing classes to help them achieve their goals

When your class needs something that another class has to offer you can
normally do one of two things after the import of the package containing
the class:
1.. directly refer to a member function in that class to perform the task
String name = JOptionPane.showInputDialog("enter your name " )
2.. create an OBJECT of that class and then refer to the object along
with the member function so the task can be performed
Button red = new Button();
.... red.setBounds (1,2,44,23);

In summary the full power of java and object oriented programming is
realized when our class creates objects of existing classes which were
created from other classes. Classes can inherit the capabilities and power
of the classes from which they were derived and so on and so on.
So not only are we not reinventing the wheel , we are pulling a wheel of
the shelf that is already fine tuned and using that to go forward to design
yet even better classes to solve problems.

When designing our own classes there are way to allow access to certain
methods and variables and not allow access to others. In other words we
allow enough access to realize its power but not enough to mess it up.
I will spend more time on these and other concepts later.

Sorting Arrays

// Interchange sort high to low
// assume n[] is 10 big and it contains 10 numbers and is 'int'
// compares each element with each one under it
// visualize it as 9 sorts on an array that is getting smaller
int g,r,c;
for ( r=0; r <=8; r++)
   {
     for ( g=r+1;g<=9;g++)
        {
            if ( n[r]  < n[g] )
               {
                   c=n[r];                // these 3 statements swap values
                   n[r] = n[g];          // in the 2 cells being compared 
                   n[g] = c;
                }
        }  
   } 

// bubble sort on the same array above
// compares pairs of elements during a pass
// an element can only move up one spot each pass
// finished if nothing was swapped or at most n-1 passes

int sw,r,c,g;
do
   {
   sw = 0; 
   for ( r=0; r <=8; r++)
      {
        g=r+1;
        if (n[r] <  n[g] )
          {
             c=n[r];              // next 3 statements swap 2 values
             n[r] = n[g];
             n[g] = c;
             sw=1;
          }
      }
    }  while ( sw = 1 }

// QUICK SORT is coming soon
// Sorting using pointer technique is coming

Variable Types

Variable Types

Since Variables stand for items that the program is manipulating
or playing with,  such as:
                        whole numbers       (small  normal   large)
                        fractional numbers        (small   large)
                        single characters
                        groups of characters as a unit
                         true / false conditions
 it is only logical to assume that JAVA gives the programmer  the

 capability to declare and use Variables that can hold each of the

above data types.  Remember that values ( or data ) being put into
Variables is the heart or basis of programming. 

Variables MUST be declared before they can be used in a program.

Common Variable types are as follows:
   short                     ... small integers
   int                          ... normal integers
   long                       ... big integers
   float                       ... small fractional numbers
   double                   ... big fractional numbers 
   char                       ... single character values   e.g.,     M    or   F
   string                     ... groups of characters viewed as a unit
   Boolean                 ... logical  TRUE  or  FALSE  values 

In object oriented and more sophisticated programs today, the
programmer can declare his or her own data type ( later )

Specifics concerning Java Data TYpes
NUMERIC (all numbers are signed)

short integer (16 bit number) --> i.e. 32,768
int integer (32 bit number) --> i.e. 2 billion or 2 x 109
long integer (64 bit number) --> i.e. 9 x 1018
float real (32 bit decimal) --> i.e. 1.4 x 10-45 to 3.4 x 1038
double real (64 bit decimal) --> i.e. 4.9 x 10-324 to 1.7 x 10308
  CHARACTER / STRING

char a unicode (2-byte) char
the String class handles multi-character strings (strings are unicode, as well). Strings are said to be immutable: updates to a String cause the new string to be created in memory (and pointed to by the String class). However the old string is not actually "updated", rather, its reference is lost (and it becomes available for garbage collection).  
BOOLEAN

boolean (with values true, false)  
DATE

the Date class measures the milliseconds since Jan 1, 1970 and provides supporting functions to interpret and manipulate date/times  
ARRAYS

arrays hold multiple instances of a data type or object

Programming Tuturials

visit this website :Programming Tutorial

click this for advance learning

Sorting an Array

Hello programmers.. my students.. i want to create a program in java that sort a number in descending order.

here is a sample program...
public class Sorting
{
    public static void main(String args[])
    {
        int arr[]={0,1,2,3,4,5,6,7,8,9,10};
        int temp=0;
       
        for(int i=0; i<10;i++)
        {
            for(int j=0; j<10; j++)
            {
                if(arr[j]
                {
                    temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
        }
       
        for(int x=0; x<10; x++)
        {
            System.out.println(arr[x]+ " ");
        }
    }
}


i hope you learn more in my blog,.... Think it Code it

Programming Tuturials

hello programmers.... hello students... java programmers.. visit this website to study advannce.

http://webpages.shepherd.edu/JROMANO/arrays.htm

Array Definition and samples

An array is multiple storage locations under one name. For now
we will talk about one and two dimensional arrays.

All the primitive data types that we have learned and used concerning
regular variables also apply to arrays.

int num = new int; // declare / initialize an integer variable

int nums[] = new int [10]; // declare and allocate space for 10 integer
// numbers. The 10 elements have the same
// name but each one will be referred to
// with a different subscript or position
// in the array. Thos array contains 10
// integer locations, number 0 thru 9

Anything that you can do with an integer variable, you can do with
each element of an integer array. But you must indicate which element
you are referring to.

e.g.. nums[0]=100;
nums[5]=200; etc.
JOptionPane.showMessageDialog(null,"answer is "+nums[2]);

Loops make working with arrays very easy.

for example:
int tot=100;
int n=0;
do
{
nums[n] = tot;
n=n+1;
} while (n <= 9 );

Remember that all rules that apply to variables of a specific type
also apply to each element of an array of that type.

Two dimensional arrays adhere to all the rules noted above, except
any reference to a two dimensional array must have 2 subscripts.

int numbers[] [] = new int [5] [10];

The above array has 5 rows and 10 columns.
The rows are numbered 0 thru 4, and the columns are numbered 0 thru 9.


Any reference to the array will have 2 subscripts and the first one will be
the row and the second one will be the column.

e.g.. numbers[1][3] = 100;

Loops are very useful with two dimensional arrays just like one
dimensional arrays, but a lot of the times nested loops are used
because of the nature of two dimensional arrays.

e.g.. int tot=10;
for(int a=0;a<=4;a++)
{
for(int b=0;b<=9;b++)
{
numbers[a][b] = tot;
tot=tot+10;
}
}

.
arrays can be declared but still need to be explicitly initialized
int [] dataPoints; // declares the array of integer
dataPoints = new int[10] ; // allocates array size (now usable)
dataPoints = new int[numPoints]; // allocates array size with size specified by a run-time variable
an array can be re-initialized (with the same data type) at runtime, at which point old array entries are discarded
Java standard arrays cannot are not dynamically resizable like arrays in Visual Basic or PowerBuilder (i.e. where the language can dynamically extend the array, if needed). Java throws an exception if an out-of-bounds array index is referenced. Java.util's Vector class provides dynamic array-like capability (a Vector can store a collection of any type of object). The standard Vector class does not, however, limit data to a specific data type (data type limitation capability has to be built in a Vector extension).

Wednesday, September 8, 2010

Array sample program

hello world.. hello programmers... i want to share to you how to make a sample program array using java..

I hope you learn and enjoy reading my blog...

import java.io.*;

public class javaarray
{
public static void main(String args[])
{
int x[]=new int[3];

x[0]=100;
x[1]=200;
x[2]=300;

//display result

System.out.println("The array[0]=" + x[0]);
System.out.println("The array[1]=" + x[1]);
System.out.println("The array[2]=" + x[2]);

}
}

next time i will post another sample program using array. using loop to print the array element.

Array in java

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

An array of ten elements

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.

class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers

anArray = new int[10]; // allocates memory for 10 integers

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
System.out.println("Element at index 6: " + anArray[6]);
System.out.println("Element at index 7: " + anArray[7]);
System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
}
}

The output from this program is:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000

In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. You'll learn about the various looping constructs (for, while, and do-while) in the Control Flow section.
Declaring a Variable to Refer to an Array
The above program declares anArray with the following line of code:

int[] anArray; // declares an array of integers

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array — it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

You can also place the square brackets after the array's name:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable.

anArray = new int[10]; // create an array of integers

If this statement were missing, the compiler would print an error like the following, and compilation would fail:

ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.

Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Here the length of the array is determined by the number of values provided between { and }.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}

The output from this program is:

Mr. Smith
Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The code

System.out.println(anArray.length);

will print the array's size to standard output.
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:

class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

The output from this program is:

caffein


next time i will post another exam program using java.

Wednesday, September 1, 2010

While Loop get even numbers

hello programmers.... i want to share to you how to create a program that get the even numbers using modulo operator and while loop.

here is the program:

import java.util.Scanner;

public class evennumbers
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int num;
int x=1;
System.out.print("How many numbers you want to print:");
num=input.nextInt();

while(x<=num)
{
if(x%2==0)
{
System.out.println(x);
}
x++;
}

}
}