MY mENU


Tuesday 20 March 2012

Leap Year Programme in C

Leap Year Programme in C:


#include  
   main() {
       int year; 
            printf("Enter a year to check if it is a leap year\n"); 
              scanf("%d", &year); 
                  if ( year%400 == 0)
                     printf("%d is a leap year.\n", year);
                        else if ( year%100 == 0) 
                             printf("%d is not a leap year.\n", year); 
                                else if ( year%4 == 0 )
                                    printf("%d is a leap year.\n", year); 
                                      else 
                                        printf("%d is not a leap year.\n", year); 
                                             return 0;
                                               }

Factorial Example in Java

Factorial Example:

public class NumberFactorial {
        public static void main(String[] args) {
                int number = 5;
                    int factorial = number;
                       for(int i =(number - 1); i > 1; i--)
                         {
                         factorial = factorial * i;
                         }
             System.out.println("Factorial of a number is " + factorial);
         }
     }


Java Factorial Using Recursion Example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaFactorialUsingRecursion {

public static void main(String args[]) throws NumberFormatException,IOException{

System.out.println("Enter the number: ");
                                            //get input from the user
BufferedReader br=new BufferedReader(newInputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
                                          //call the recursive function to generate factorial
int result= fact(a);
System.out.println("Factorial of the number is: " + result);
}

static int fact(int b)
{
if(b <= 1)
                                            //if the number is 1 then return 1
return 1;
else
                                             //else call the same function with the value - 1
return b * fact(b-1);
}
}

Add Two Matrices And Store the Values

Add Two Matrices And Store the Values:

#include
#include
void main()
{
  int a[3][3],b[3][3],c[3][3],i,j;
   clrscr();
     printf("Enter the elements into matrix A\n");
      for(i=0;i<3;i++)
        for(j=0;j<3;j++)
          scanf("%d",&a[i][j]);
   

    printf("\nEnter the elements into matrix B\n");
      for(i=0;i<3;i++)
        for(j=0;j<3;j++)
          scanf("%d",&b[i][j]);


        for(i=0;i<3;i++)
          for(j=0;j<3;j++)
              c[i][j]=a[i][j]+b[i][j];

      for(i=0;i<3;i++)
       {
         printf("\t\t");
           for(j=0;j<3;j++)
             printf("%d\t",c[i][j]);
               printf("\n\a");
               }
      getch();
   }

Convert Decimal into Hexa Decimal

Convert Decimal into Hexa Decimal:

#include
#include
#include
void main()
{
Int x, y=30, z;
 clrscr();
  printf(“Enter the number:”);
    scanf(“%d”, &x);
       printf(“\n conversion of decimal to hexadecimal number\n”);
         for(;;)
          {
           if(x= =0)
             exit(1);
               z=x%16;
                   x=x/16;
                      gotoxy(y--,5);
           switch(z)
            {
              Case 10:
                Printf(“A”); Break;
             Case 11:
                Printf(“%c”, „B?); Break;
             Case 12:
                Printf(%c”, „C”); Break;
            Case 13:
                Printf(“D”);  Break;
           Case 14:
               Printf(“E”); Break;
           Case 15:
              Printf(“F”);
           Default:
              Printf(“%d”, z);
           }
        }
    getch();
}

Output:
Enter the number: 31
Conversion of decimal to Hexa decimal number 1F

To Add Two Numbers Repeatedly

To Add Two Numbers Repeatedly:

#include 
 main()
 { 
int a, b, c; char ch; 
   while(1) {
         printf("Enter values of a and b\n");
         scanf("%d%d",&a,&b);
               c = a + b; 
                     printf("a + b = %d\n", c);
                       printf("Do you wish to add more numbers(y/n)\n"); 
                          scanf(" %c",&ch);
                                 if ( ch == 'y' || ch == 'Y' ) 
                                      continue; 
                                            else 
                                           break; 
                           }
           return 0;
    }

Adding Two Numbers Using Functions:

#include
  long addition(long, long); 
     main() { 
             long first, second, sum;
                scanf("%ld%ld", &first, &second); 
                        sum = addition(first, second);
                           printf("%ld\n", sum); 
                             return 0;
                         } 
 long addition(long a, long b) { 
                long result;
                result = a + b; 
                  return result; 
            }

Find Maximum of 2 nos. in Java

Find Maximum of 2 nos.

class Maxof2{

public static void main(String args[]){

//taking value as command line argument.

//Converting String format to Integer value

int i = Integer.parseInt(args[0]);

int j = Integer.parseInt(args[1]);

if(i > j)

System.out.println(i+" is greater than "+j);

else

System.out.println(j+" is greater than "+i);

}

}

Read Numbers and Strings in Java

package corejava;

/**An easy interface to read numbers and strings from standard input */

public class Console
{
           /**print a prompt on the console but don|t print a newline
          @param prompt the prompt string to display */

public static void printPrompt(String prompt)
{
 System.out.print(prompt + " ");
System.out.flush();
}
       /**read a string from the console. The string is terminated by a newline
           @return the input string (without the newline)*/

public static String readLine()
int ch;
String r = "";
boolean done = false;
while (!done){ 
try { 
ch = System.in.read();
if (ch < 0 || (char)ch == |\n|)
done = true;
else if ((char)ch != |\r|)                  // weird--it used to do \r\n translation
r = r + (char) ch;
}
catch(java.io.IOException e){ 
done = true;
}}
return r;
}
           /**read a string from the console. The string is terminated by a newline
                 @param prompt the prompt string to display
                 @return the input string (without the newline) */

public static String readLine(String prompt)
printPrompt(prompt);
return readLine();
}
                   /**read an integer from the console. The input is terminated by a newline
                        @param prompt the prompt string to display
                        @return the input value as an int
                        @exception NumberFormatException if bad input */
public static int readInt(String prompt)
while(true){ 
printPrompt(prompt);
try
{
 return Integer.valueOf (readLine().trim()).intValue();
} catch(NumberFormatException e) { 
System.out.println("Not an integer. Please try again!");
}
}
}

/**read a floating point number from the console. The input is terminated by a newline
@param prompt the prompt string to display
@return the input value as a double
@exception NumberFormatException if bad input */

public static double readDouble(String prompt)
while(true) { 
printPrompt(prompt);
try
{
 return Double.parseDouble(readLine().trim());
} catch(NumberFormatException e){
 System.out.println("Not a floating point number. Please try again!");
}}}}

Random Number Generator in Java

package corejava;


/**An improved random number generator .Gives a set of random integers that does not exhibit
as much correlation as the method used by the Java random number generator.*/

public class RandomIntGenerator
{
 /**Constructs an object that generates random integers in a given range
@param l the lowest integer in the range
@param h the highest integer in the range */

public RandomIntGenerator(int l, int h)
low = l;
high = h;
}
/**Generates a random integer in a range of integers
@return a random integer */

public int draw()
int r = low + (int)((high - low + 1) * nextRandom());
return r;
}

/**test stub for the class*/

public static void main(String[] args)
{
 RandomIntGenerator r1 = new RandomIntGenerator(1, 10);
RandomIntGenerator r2 = new RandomIntGenerator(0, 1);
int i;
for (i = 1; i <= 100; i++)
System.out.println(r1.draw() + " " + r2.draw());
}

private static double nextRandom()
{ int pos = (int)(java.lang.Math.random() * BUFFER_SIZE);
if (pos == BUFFER_SIZE) pos = BUFFER_SIZE - 1;
double r = buffer[pos];
buffer[pos] = java.lang.Math.random();
return r;
}

private static final int BUFFER_SIZE = 101;
private static double[] buffer = new double[BUFFER_SIZE];
static { 
int i;
for (i = 0; i < BUFFER_SIZE; i++)
buffer[i] = java.lang.Math.random();
}

private int low;
private int high;
}

Logout of System In PHP


session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it|s desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), ||, time()-42000, |/|);
}

// Finally, destroy the session.
session_destroy();
header("location:index.php");
?>

Log Visitors IP Address in PHP

OK start up MySQL and then enter the following to create the database .

CREATE DATABASE ipvisits;

USE ipvisits;

mysql> CREATE TABLE visitorsips(
-> ip VARCHAR(50),
-> date VARCHAR(50));

Now we will insert our visitors IP addresses into the database with the following code

                                    //get the visitors ip address
$ip_address = $REMOTE_ADDR;
                                           //get the date
$the_date = date("Y-m-d");
                                     //connect to MySQL using your details
$conn = @mysql_connect("localhost","username","password") or die("cannot connect to MySQL");
                                          //select the database
@mysql_select_db("ipvisits") or die("cannot connect to the database");
                                         //execute the query
@mysql_query("INSERT INTO visitorsips(ip,date) VALUES (,|$ip_address,|,,|$the_date,|)");
                                               //close the connection
mysql_close($conn);
?>

Now you have got a system for logging peoples IP addresses that visit your site .

Random Ad Rotator in PHP

This is a simple random image script which is ideal for displaying basic images from a text file.
The first step that you need to do is to create your file for storing your images and then insert the names of the images. In the example here I called the file images1.txt . Each one of the entries is on a seperate line and in this case because I stored the files in a sub-directory I inserted that also . the structure of the file was like this

image/banner1.gif
image/banner2.gif
image/banner3.gif

and so on. Now we get to the script that will display a random image and again this is straight forward enough.

#random images example
#this is your file
$file = "images1.txt";
#open the file
$fp = file($file);
#generate a random number
srand((double)microtime()*1000000);
#get one of the entries in the file
$random_image = $fp[array_rand($fp)];
#display the entry
echo "";
?>

Nothing ground breaking here , we open a file , we then generate a randomnumber, we then get a random entry from the file and store this in the variable $random_image and then we output this as some HTML.

Note that in this example we have saved this as a seperate file and included it on the page . If the file was called random.php then we put the following code where we want the image to appear

CounterHit Code for PHP

A common feature on most websites is a counter to show how many visitors have been to your site.  This example is very basic and far from ideal if you want an accurate count of your visitors because if you press refresh your counter will always increment by 1. This example does show some useful techniques such as opening and closing files .

Lets go through the process one step at a time . Firstly you have to create a simpletext file and enter the number you wish the counter to start at , note this does not have to be 1 it can be any number you wish. The next task will be to upload this to your server , if you have a Unix server this is where you have to watch because you have to set the permissions for your text fileso the script can read and write to the file . To change this you CHMOD your text file to 755. Refer to the help file or documentation of your FTP program to see how to achieve this.

Now for the script , call this something like counter.php

    //this is our text file if you create a different named file change the script below to reflect this

$counter_file = ("counter.txt");
                                                     //now we open the file
$visits = file($counter_file);
                                             //this increments the counter value by 1
$visits[0]++;
                                                 //now we will open the counter file for writing "w"
$fp = fopen($counter_file , "w");
                                              //put the new count value into the counter file
fputs($fp , "$visits[0]");
                                               //close the file
fclose($fp);
                                                //display the count
echo "There have been $visits[0] visitors so far";
?>

Now add the following to your page where you wish the counter to appear

RandomPassWord Creation in PHP

This is a simple random password example , you could generate this for a visitor to use and store it in a database.

function random_password ()
{
$seed = (integer) md5(microtime());
mt_srand($seed);
$password = mt_rand(1,99999999);
$password = substr(md5($password), mt_rand(0, 19), mt_rand(6, 12));
return $password;
}
?>
$msg = random_password();
echo $msg;
?>

FileTable HTML Programme

import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.Date;

/**
* This class implements a simple directory browser using the HTML
* display capabilities of the JEditorPane component.
**/

public class FileTableHTML {

public static void main(String[] args) throws IOException {

// Get the name of the directory to display

String dirname = (args.length>0)?args[0]:System.getProperty("user.home");

// Create something to display it in.

final JEditorPane editor = new JEditorPane();
editor.setEditable(false);                                    // we|re browsing not editing
editor.setContentType("text/html");                   // must specify HTML text
editor.setText(makeHTMLTable(dirname));     // specify the text to display

// Set up the JEditorPane to handle clicks on hyperlinks

editor.addHyperlinkListener(new HyperlinkListener() {

public void hyperlinkUpdate(HyperlinkEvent e) {

// Handle clicks; ignore mouseovers and other link-related events

if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                                                 // Get the HREF of the link and display it.
editor.setText(makeHTMLTable(e.getDescription()));
}
}
});

                                             // Put the JEditorPane in a scrolling window and display it.
JFrame frame = new JFrame("FileTableHTML");
frame.getContentPane().add(new JScrollPane(editor));
frame.setSize(650, 500);
frame.setVisible(true);
}

                                        // This method returns an HTML table representing the specified directory
public static String makeHTMLTable(String dirname) {
                                          // Look up the contents of the directory
File dir = new File(dirname);
String[] entries = dir.list();
                              // Set up an output stream we can print the table to.
                             // This is easier than concatenating strings all the time.
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout);
                             // Print the directory name as the page title
out.println(" " + dirname + " ");
                            // Print an "up" link, unless we|re already at the root
String parent = dir.getParent();
if ((parent != null) && (parent.length() > 0))
out.println("Up to parent directory ");
                                         // Print out the table
out.print("");
out.print("");
out.println("");
for(int i=0; i < entries.length; i++) {
File f = new File(dir, entries[i]);
out.println("");
}
out.println("NameSizeModifiedReadable?Writable?" + (f.isDirectory() ?"" + entries[i] + "" : entries[i]) +" " + f.length() +" " + new Date(f.lastModified()) + " " + (f.canRead()?"x":" ") +" " + (f.canWrite()?"x":" ") +"");
out.close();
                                       // Get the string of HTML from the StringWriter and return it.
return sout.toString();
}
}

Cloning In Java


Cloning:  Cloning means creating duplicate copy with current object state is called cloning.

Requirement: If we create objects with new keyword and constructor always objects are created with default initial state. If we want to create second object with first object current modified state, we must used cloning.

For Example  consider below example;:
Consider a bikes manufacturing factory, here all bikes has same state except few properties like engine number, model number etc.
          To develop this factory application it is recommended to use cloning approach. because once we create object, in all other objects we need to change only the specific properties.

        To perform cloning we must use Object's class clone Method.

Rule:
       To clone an object, its class must be subclass of java.lang.Cloneable interface. It is a marker interface. It means only Cloneable objects are cloned by JVM . If object is not of type Cloneable  JVM throws exception java.lang.CloneNotSupprotedEception. Below application shows performing cloning.

//Factory.java
class Bike implements Cloneable{
int bikeNumber;
int engineNumber;
int modelNumber;
String type;

Bike(int bikeNumber; int engineNumber; int modelNumber; String type;){
     this.engineNumber=engineNumber;
         this.modelNumber=modelNumber;     
         this.type=type;
}
public Object clone() throws CloneNotSupportedException
{
    //current bike object is cloned
    Bike b1=(Bike)super.clone();

//changing individual property
  b1.engineNumber=  b1.engineNumber+10;

//returning cloned bike
return b1;
}}
class factory
public static void main(String[] args) throws CloneNotSupportedException{
       Bike b1= new Bike(4221,5673,"Pulsar 180cc");
     
        //cloning first bike object
    Bike b2=(Bike)b1.clone();

//clone method create new object , so == returns false
  System.out.println(b1==b2);

     System.out.println("b1 object state");
      System.out.println("b1.engineNumber:"+b1.engineNumber);
           System.out.println("b1.modelNumber:"+b1.modelNumber);
                   System.out.println("b1.type:"+b1.type);

 System.out.println();
     System.out.println("b2 object state");
      System.out.println("b2.engineNumber:"+b2.engineNumber);
           System.out.println("b2.modelNumber:"+b2.modelNumber);
                   System.out.println("b2.type:"+b2.type);
}}