Showing posts with label source code. Show all posts
Showing posts with label source code. Show all posts

Tuesday, November 11, 2014

SOME SIMPLE SOURCE CODES THAT I DEVELOPED IN C#.NET AFTER REFERRING FEW BOOKS FEEL FREE TO POINT OUT ERRORS IF ANY

SOURCE CODE #1
using System;
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello C#");
        }
    }

OUTPUT OF SOURCE CODE #1



SOURCE CODE #2:
using System;
namespace ConsoleApplication2
{
    public class Fraction
    {
        public Fraction(int numerator, int denominator)
        {
            this.numerator = numerator;
            this.denominator = denominator;
        }
        public void Add(Fraction rhs)   
        {
            if(rhs.denominator != this.denominator)
            {
                throw new ArgumentException("Denominators must match");
            }
            //return new Fraction(this.numerator+rhs.numerator, this.denominator);
            Console.WriteLine("The sum of the two fractions is " + (this.numerator + rhs.numerator) + " / " + this.denominator);
        }
        public override string ToString()
        {
            return numerator + "/" + denominator;
        }
        private int numerator;
        private int denominator;
        public static void Main (String []args)
        {
            Fraction frac = new Fraction(2,3);
            Fraction frac1 = new Fraction(4,3);
            frac1.Add(frac);
        }
    }
}

OUTPUT FOR SOURCE CODE #2:




Monday, November 10, 2014

Merge Sort Part- 3 REFERENCE : PANIMALAR ENGINEERING COLLEGE NOTES

The most common algorithm used is the merge sort. This algorithm follows divide and conquer strategy. In dividing phase the problem is divided into smaller problem and solved recursively.In conquering phase, the partitioned array is merged together recursively. Merge sort is applied to the first half and second half of the array. This gives two sorted halves which can then be recursively merged together using the merging algorithm.
The basic merging algorithm takes two input arrays A and B and an output array C. The first element of A array and B array are compared, then the smaller element is stored in the output array C and the corresponding pointer is increment. When either input array is exhausted the remainder of the other array is copied to an output array C.

void MSort (ElementType A[ ] , ElementType TmpArray[ ] , int left, int right)
{
int center;
if(left{
center = (left + right) / 2;
msort(A, TmpArray, left,center);
msort(A,TmpArray, center+1,right);
merge(A, TmpArray, left, center+1, right);
}
}

void merge(int A[ ], int TmpArray[ ], int lpos, int rpos, int rightend)
{
int i, num, leftend, tmpos;
leftend = rpos - 1;
tmpos = lpos;
num = rightend - lpos + 1;
while(lpos<=leftend) &&(rpos<=rightend)
if(A[lpos]<=A[rpos])
TmpArray[tmpos++]=A[lpos++];
else
TmpArray[tmpos++]=A[rpos++];
while(lpos<=leftend)
TmpArray[tmpos++]=A[lpos++];
while(rpos<=rightend)
TmpArray[tmpos++] = A[rpos++];
for(i=0;i<=num; i++, rightend--)
A[rightend]=TmpArray[rightend];
}

void MergeSort(ElementType A[ ], int N)
{
ElementType TmpArray[MAX];
MSort (A,TmpArray,0,N-1)
}

The merge sort algorithm is therefore easy to describe. If N-1, there is only one element to sort and the answer is at hand. Otherwise, recursively merge sort the first half and second half. This gives two sorted halves, which can then be merged together using merging algorithm.

For example to sort the eight element array 24, 23, 26, 1, 2, 27, 38, 15. We recursively sort the first four and the last four elements, obtaining 1, 13, 14, 26, 2, 15, 27, 38. Then we merge the two halves as above, obtaining the final list 1, 2, 13, 15, 24, 26, 27, 38.


Analysis of Merge Sort

                   Worst Case Analysis       --  O(NlogN)
                    Best Case Analysis         -- O(NlogN)
                    Average Case Analysis   -- O(NlogN)

Advantages of Merge Sort
It is efficient for sorting large number of elements.
It is simple than Heap sort.
It has better cache performance.
It has the advantages of worst case O(NlogN) running time.

Limitations

It requires more memory space.
It requires more processing time.

Saturday, November 8, 2014

Data Structures ---- Sorting (Part - 2 Shell Sort)

Shell Sort

reference: PANIMALAR ENGINEERING COLLEGE NOTES
                 Shell sort was invented by Donald Shell. It improves upon bubble sort and insertion sort by moving out of order elements more than one position at a time.
                 In this sort the whole array is first fragment into K segments, where K is preferably a prime number. After first pass, the whole array is partially sorted. In the next pass, the value of K is reduced which increases the size of the segment and reduces the number of segments.
                 The next K value is chosen as relatively prime to its previous value. The process is repeated until k=1 at which the array is sorted. The insertion sort is applied to each segment, so each successive segment is partially sorted.The shell sort is also called as Diminishing Increment Sort, because the value of K decreases continuously.

Algorithm

void ShellSort (ElementType A[ ], int N)
{
int i,j,Increment;
ElementType temp;
for(Increment = N/2; Increment>0; Increment = Increment/2)
for(i=Increment;i{
temp=A[i];
for(j=i;j>=Increment;j=j-Increment)
if(tempA[j] = A[j- Increment];
else
break;
A[j] = temp;
}
}

Example

Consider an Unsorted array

81      94       11         96        12       35        17        95        28         58

Here N = 10, the first Pass as K = 5 (10/2)


After First Pass

35        17          11           28           12            81             94            95           96           58

In second pass, K is reduced to 3


After Second Pass

28        12         11           35           17                81               58            95             96            94

In third pass, K is reduced to 1


The final sorted array is

11           12          17          28          35            58            81           94            95           96

Analysis of Shell Sort

Worst Case Analysis                          - O(N2)
Best Case Analysis                             - O(N log N)
Average Case Analysis                       - O(N2)

Advantages of Shell Sort

It is one of the fastest algorithm for sorting small number of elements.

It requires relatively small amounts of memory.

(contd)

Thursday, November 6, 2014

SOME VERY SIMPLE AND BASIC JAVA SOURCE CODES THAT I DEVELOPED. FEEL FREE TO POINT OUT ERRORS IF ANY.(PART-3)

SOURCE CODE #8
//A Simple java program to find the number of characters present in a String.
import java.util.*;
import java.io.*;
public class NumberOfCharactersInAString
{
public static void main(String args[]) throws IOException
{
int chara;
System.out.println("Enter a String");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
for(chara=0; chara {}
System.out.println("The total number of characters present in the String is " + chara);
}

}

OUTPUT FOR SOURCE CODE #8
Enter a String
Hemapriyagopal
The total number of characters present in the String is 14

SOURCE CODE #9
//How to input a string from the monitor and print the reverse of the string on the screen
import java.io.*;
public class StringReverse {
public static void main(String args[]) throws IOException
{
String name;
String revname;
System.out.println("Enter a string");
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
name = br.readLine();
revname = new StringBuilder(name).reverse().toString();

System.out.println("The reversed string is " + revname);
}
}

OUTPUT FOR SOURCE CODE #9
Enter a string
Hemapriyagopal
The reversed string is lapogayirpameH

OUTPUT-2
Enter a string
as df
The reversed string is fd sa

SOME VERY SIMPLE AND BASIC JAVA SOURCE CODES THAT I DEVELOPED. FEEL FREE TO POINT OUT ERRORS IF ANY.(PART-2)

SOURCE CODE #6
//A SIMPLE JAVA PROGRAM THAT EXPLAINS HIERARCHIAL INHERITANCE
/* HERE InheritanceOne is the base calss, Truck, Airplane & Boat are all derived classes.
 * constructor is used in all the classes.
 * The keyword "extends" is used to show that Inheritance concept is used here.
 * Every method prints a simple line on the screen.
 * The output shows the flow of control throughtout the source code.
 * I hope this explains the concept of hierarchial inheritance very well.
 * Author - Hemapriya Gopal
 */

public class InheritanceOne
{
 float position;
 float speed;
 float fuellevel;
 public InheritanceOne()
 {
        System.out.println("Inside the constructor of the base class");
 }
 public void move()
 {
        System.out.println("Inside the InheritanceOne class move() method ");
 }
 public void addPassenger()
 {
        System.out.println("Inside the InheritanceOne class addPassenger() method ");
 }
 public void displayPosition()
 {
        System.out.println("The position of the vehicle is 45' NE ");
 }
 public void displaySpeed()
 {
        System.out.println("The vehicle is moving at the speed of 60km/hr ");
 }
 public void displayFuellevel()
 {
        System.out.println("The fuel tank in the vehicle is half-full");
 }
 public static void main(String args[])
 {
        InheritanceOne io = new InheritanceOne();
        io.move();
        io.addPassenger();
        Airplane a = new Airplane();
        a.operateUnderCarriage();
        a.displayFuellevel();
        Truck t = new Truck();
        t.getTyrePressure();
        t.displaySpeed();
        Boat b = new Boat();
        b.displayPosition();
        b.dock();
 }
/* InheritanceOne()
{
       System.out.println("Inside the destructor of the base class");
}
*/
}
class Airplane extends InheritanceOne
{
       float heightfromGround;
       public Airplane()
       {
              //super();
              System.out.println("Inside the constructor of the derived class Airplane");
       }
       public void operateUnderCarriage()
       {
              System.out.println("Inside the derived class Airplane in the method operateUndercarriage");
       }
}
class Truck extends InheritanceOne
{
       public void getTyrePressure()
       {
              System.out.println("Inside the method getTyrePressure() of the class Truck");
       }
       public Truck()
       {
              System.out.println("Inside the constructor of the derived class Truck");
       }
}
class Boat extends InheritanceOne
{
       public void dock()
       {
              System.out.println("Inside the method dock() of the derived class Boat");
       }
       public Boat()
       {
              System.out.println("Inside the constructor of the derived class Boat");
       }
}

HIERARCHIAL INHERITANCE


OUTPUT:
Inside the constructor of the base class
Inside the InheritanceOne class move() method
Inside the InheritanceOne class addPassenger() method
Inside the constructor of the base class
Inside the constructor of the derived class Airplane
Inside the derived class Airplane in the method operateUndercarriage
The fuel tank in the vehicle is half-full
Inside the constructor of the base class
Inside the constructor of the derived class Truck
Inside the method getTyrePressure() of the class Truck
The vehicle is moving at the speed of 60km/hr
Inside the constructor of the base class
Inside the constructor of the derived class Boat
The position of the vehicle is 45' NE
Inside the method dock() of the derived class Boat


SOURCE CODE #7

/*A very simple program implementing all the basic concepts of javax.swing
 * Reference - 1.The Complete Refernce 5th Edition --Herbert Schildt
 *          2.NUS - ISS S.E Notes for OOP
 *         3.http://www.wattpad.com/6660884-java-swing-gui-development-chapter-two-your-first
 * Author - Hemapriya Gopal
 */
import java.awt.*;
import javax.swing.*;
public class SwingHelloWorldForPractice
{
       public void FrameOne()
       {
              JFrame frame = new JFrame ("Hello World Application");
              frame.setSize(270,70);
              frame.setLayout(new FlowLayout());
             
              JLabel label = new JLabel ("Hello world");
              JButton button = new JButton ("OK");
              frame.add(label);
              frame.add(button);
             
              frame.setVisible(true);
       }
       public void OddOrEvenUsingGUI()
       {
              String num = JOptionPane.showInputDialog (null,"Enter a number");
              int num1=Integer.parseInt(num);
              if(num1==0)
              {
                     JOptionPane.showMessageDialog (null, "The number entered is zero");
              }
              else if(num1 %2 ==0)
              {
                     JOptionPane.showMessageDialog(null, "The number entered is an even number");
              }
              else
              {
                     JOptionPane.showMessageDialog(null, "The number entered is a odd number");
              }
       }
       public void HelloWorldGUI()
       {
              JOptionPane.showMessageDialog(null,"Hello World!", "Hello",JOptionPane.PLAIN_MESSAGE);
       }
public static void main(String args[])
{
       SwingHelloWorldForPractice shwfp = new SwingHelloWorldForPractice();
       shwfp.HelloWorldGUI();
       shwfp.OddOrEvenUsingGUI();
       shwfp.FrameOne();   
}}

OUTPUT:





Wednesday, November 5, 2014

SOME VERY SIMPLE AND BASIC JAVA SOURCE CODES THAT I DEVELOPED. FEEL FREE TO POINT OUT ERRORS IF ANY.

SOURCE CODE #1
//A simple program to find the sum of all natural numbers till 100 (0,100)
public class SumTillHundred
{
public static void main(String args[])
{
int i;
int digit;
for (i=1 , digit = 0; i<=100;i++)
{
digit=digit+i;
}
System.out.println("The sum of natural numbers till 100 = " + digit);
}
}

OUTPUT FOR SOURCE CODE #1
The sum of natural numbers till 100 = 5050

SOURCE CODE #2
//A simple program to find the product of all even positive numbers less than ten
public class ProdEvenLessThanTen 
{
public static void main(String args[])
{
int n;
int digit=1;
for(n=2;n<10 n="" p="">
if(n%2==0)
digit=digit*n;
System.out.println("The product of all even numbers less than 10 is " + digit);
}
}

OUTPUT FOR SOURCE CODE #2
The product of all even numbers less than 10 is 384

SOURCE CODE #3
//A Simple java program that reads a line from keyboard and outputs "Hello"+name
import java.io.*;
public class HelloPlusName 
{
public static void main(String args[]) throws java.lang.Exception
{
System.out.println("Enter your name");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
System.out.println("Hello " + name);
}
}

OUTPUT FOR SOURCE CODE #3
Enter your name
Hemapriya
Hello Hemapriya

SOURCE CODE #4
//A simple program that appends firstname with surname and prints the output as "welcome + fullname"
import java.io.*;
import java.lang.String;
public class SurnamePlusFirstname {
public static void main (String args[])throws Exception
{
System.out.println("Enter your firstname \n");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String firstname = br.readLine();
System.out.println("Enter your surname \n");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String lastname = br2.readLine();
StringBuilder fullname = new StringBuilder();
fullname.append(firstname); 
fullname.append(lastname);
System.out.println("Welcome " + fullname + "!");
}
}

OUTPUT FOR SOURCE CODE #4
Enter your firstname 

Hemapriya
Enter your surname 

Gopal
Welcome HemapriyaGopal!

SOURCE CODE #5
//Program to find the slope of a straight line in XY- axes when the equation is given
//Assumption: THE SIMPLE CASE THAT THE STRAIGHT LINE INTERSECTS BOTH THE AXES
import java.io.*;
public class SlopeOfStraightLine {
public static void main(String args[]) throws Exception 
{
System.out.println("Enter the equation of the straight line in the two dimensional axes");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String eqn = br.readLine();
System.out.println("Enter the co-efficient of x \n");
BufferedReader br1 = new BufferedReader(new InputStreamReader (System.in));
String str1 = br1.readLine();
float coex = Integer.parseInt(str1);
System.out.println("Enter the co-efficient of y \n");
BufferedReader br2 = new BufferedReader(new InputStreamReader (System.in));
String str2 = br2.readLine();
float coey = Integer.parseInt(str2);
float slope = -(coey/coex);
System.out.println("The straight line having the equation " + eqn + " has the slope value of " + slope + "\n");
}
}

OUTPUT FOR SOURCE CODE #5
Enter the equation of the straight line in the two dimensional axes
2X-3Y+6=0
Enter the co-efficient of x 

2
Enter the co-efficient of y 

-3
The straight line having the equation 2X-3Y+6=0 has the slope value of 1.5