Thứ Sáu, 26 tháng 12, 2014

Constructing Bridges Problem

Constructing Bridges: 
A River that cuts through a set of cities above and below it. Each city above the river is matched with a city below the river. 
Construct as many Non-Crossing Bridges as possible. 
Input: 
Above Bank >> 7 4 3 6 2 1 5 
Below Bank >> 5 3 2 4 6 1 7 
are given in pairs: (7,5) (4,3) (3,2) (6,4) (2,6) (1,1) (5,7) 
Output: 
(1,1) (3,2) (4,3) (6,4) (7,5)



Solution
------------


import java.util.HashMap;
import java.util.Map;


/**
 * @author shashi
 *
 **/
public class RiverBridge {

public static void main(String []args)
{
//get the above and below banks
int aboveBank[]={7 ,4, 3, 6, 2, 1, 5};
int belowBank[]={ 5, 3, 2, 4, 6, 1, 7};

//now create a Map for storing Pairs
Map<Integer, Integer> myMap=new HashMap<Integer, Integer>();
//base condition
if(aboveBank.length !=belowBank.length)
{
//River flow is not correct way
System.out.print("Your river is not flowing in correct way");
}
//if not
for(int i=0;i<aboveBank.length-1;i++)//you can also use below.length
{
if(aboveBank[i]>=belowBank[i])
{
//pair for bridge is founded so add to map
myMap.put(aboveBank[i], belowBank[i]);
}
}
//now print map elements
for(Map.Entry<Integer, Integer> entry:myMap.entrySet())
{
int key=entry.getKey();
int val=entry.getValue();
System.out.print("("+key+","+val+")"+"  " );
}

}
}


output:
-----------
(1,1)  (3,2)  (4,3)  (6,4)  (7,5)  

Thứ Tư, 24 tháng 12, 2014

Watch Indian Cricket Sports HD Legally in USA



Cricket Fever is always on high. In USA getting a HD cricket telecast is not so easy. Few of the matches are available on ESPN/Cricinfo if you have AT&T Uverse or Comcast services but not always. If you need a cheap, reliable and high quality option then this article is for you. Read on for details.




Willow TV has rights to telecast most of the cricket matches. Willow TV is available for $

Thứ Sáu, 19 tháng 12, 2014

MergeSort

MergeSort program in java

/* Program written by shashi kumar*/
package sortingPackag;

public class MergeSort {

public static void main(String []args)
{

//get The elements for merge sort
int ele[]={11,4,55,6,99,78,0,99,-99};
int re[]=new int[ele.length];
re=merge_sort(ele);
//print res
for(int i=0;i<re.length;i++)
{
System.out.print(re[i]+" ");
}


}
public static int [] merge_sort(int data[])
{
if(data.length<=1)
{
return data;
}
int midpoint=data.length/2;

int left[]=new int[midpoint];
int right[];
int res[]=new int[data.length];
if(data.length%2==0)
{
//even so
right=new int[midpoint];

}
else
{
right=new int[midpoint+1];
}
//copy data values form data to left and right
for(int i=0;i<midpoint;i++)
{
left[i]=data[i];
}
//copy to right
int x=0;
for(int j=midpoint;j<data.length;j++)
{
if(x<data.length)
{
right[x]=data[j];
x=x+1;
}
}
left=merge_sort(left);
right=merge_sort(right);
res=merge(left,right);
return res;
}
public static int [] merge(int left[],int right[])
{
int result[]=new  int[left.length+right.length];
int l=0,r=0,k=0;
while(l<left.length && r<right.length)
{
if(left[l]<right[r])
{
//get minimum from both arrays
result[k]=left[l];
k=k+1;
l=l+1;

}
else
{
result[k]=right[r];
r=r+1;
k=k+1;
}
}
//if not both
while(l<left.length)
{
result[k]=left[l];
l=l+1;
k=k+1;

}
while(r<right.length)
{
result[k]=right[r];
k=k+1;
r=r+1;
}
return result;
}
}


output:
---------------------------

-99 0 4 6 11 55 78 99 99

Thứ Năm, 18 tháng 12, 2014

Algorithm:

write an algorithm or a java program to complete the given task.

problem:

          for example consider an array of elements 1,4,3,8,22,10 .Now  you have to sort the array in a way that its even postioned values will be in decreasing order ,its odd positined values must be in increasing order .For given problem the solution will be 1 22 3 10 4 8 .


solution:

//algoritm written by shashi kumar

import java.util.Arrays;


public class TecnicsProgram {

public static void main(String args[])
{

//given data  is 1,4,3,8,22,10
int givenData[]={1,4,3,8,22,10};
//sort the data next from given arry of data
Arrays.sort(givenData);

//check weather data is sorted or not
/*for(int i=0;i<givenData.length;i++)
{
System.out.print(givenData[i]+" ");
}
*/
//now take first index and last index values of givenData
int firstIndex=0,lastIndex=givenData.length-1;
//define a new arry for result

int res[]=new int[givenData.length];
for(int index=0;index<givenData.length;index++)
{
//loop through each and every element of given array
if(index%2==0)
{
//even position so put min element
if(firstIndex>lastIndex)
break;
res[index]=givenData[firstIndex];
firstIndex++;
}
else
{
//it is an even index so put max element
if(lastIndex<firstIndex)
break;
res[index]=givenData[lastIndex];
lastIndex--;
}
}

//now print res array
for(int x=0;x<res.length;x++)
{
System.out.print(res[x]+" ");
}
}


}

output:
1 22 3 10 4 8 

Thứ Bảy, 1 tháng 11, 2014

Make Free First Minute call to INDIA & 25 countries



We all use Google Hangout to make free video and voice calls over internet. Google is offering free calls to US from a long time now. Well offer is gone little better till end of 2014. Now you can make free first minute calls to 25 countries including INDIA. Read on for details.







Details about the offer

It will be mentioned on the screen if first minute of call is free. 
There is no

Thứ Tư, 1 tháng 10, 2014

java Programing problem.

problem:


 You have an array of 0's and 1's. Determine a window [L,R], such that if you flip the bits in that window, you will have maximum number of 1's in your array, and then output this number of 1's.


For eg:
Input array: 1 0 0 1 0 0 1
Output: 6
Explanation:
If you choose a window [1,5], your array becomes,
1 1 1 0 1 1 1
which gives the total number of 1's now 6. So, your program should output the number 6, i.e. the maximum number of 1's after choosing a window.

solution:
package com.shashi;
class Array
{
 private int arr[];
 public Array()
 {
  //if you are not specifing any size
  arr=new int[10];
 }
 public Array(int s)
 {
  arr=new int[s];
 }
 public void fill(int arr1[])
 {
  for(int i=0;i<arr1.length;i++)
   arr[i]=arr1[i];
 }
 public void getNoOnes(int wl,int wr)
 {
  for(int i=wl;i<=wr;i++)
  {
   if(arr[i]==0)
    arr[i]=1;
   else if(arr[i]==1)
    arr[i]=0;
  }
 }

 public int getCount()
 {
  int count=0;
  for(int i=0;i<arr.length;i++)
  {
   if(arr[i]==1)
    count+=1;
  }
  return count;
 }
}
public class ArrayWindow {
 public static void main(String []args)
 {
  Array a=new Array(7);
  int data[]={1,0,0,1,0,0,1};
  a.fill(data);
  a.getNoOnes(1, 5);
  System.out.print(a.getCount());
 
 }
}
output
------------------
6
 
 
 

Thứ Bảy, 27 tháng 9, 2014

Thread Demo

question:

There are three threads in a process. The first thread prints 1 1 1 …, the second one prints 2 2
2 …, and the third one prints 3 3 3 … endlessly. How do you schedule these three threads in order to print 1 2 3 1 2 3 …?

solution:

package com.shashi;

class ThreadDemo1 extends Thread
{
   
private int val;
public ThreadDemo1(int val)
{
    this.val=val;
    start();
}
public void run()
{
    while(true)
    {
        synchronized(this)
        {
        try
        {
            wait();
        }
        catch(Exception e)
            {System.out.print(e.getLocalizedMessage());}
            System.out.print(val+" ");
        }
    }
}
   
}

public class ThreadDemo
{
    public static void main(String []args)
    {
        ThreadDemo1 arr[]=new ThreadDemo1[3];
        for(int i=0;i<3;i++)
        {
            arr[i]=new ThreadDemo1(i+1);
        }
        int index=0;
        while(true)
        {
            synchronized(arr[index])
            {
                arr[index].notify();
            }
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e){System.out.print(e.getLocalizedMessage());}
            index=(++index)%3;
        }
    }
}



output:

------------------------------
1 2 3 1 2 3 1 2 3 1 2 3 .................so on!!!!!
------------------------------


Explanation:

1.first create three threads ,here i created array of three threads.
2.now in order to print format like 1 2 3 1 2 3 ...........,you have to create locks .Here i created locks by using synchronized block.

logic:

if(any thread is avilable)
call wait();
repeat above step;
//next step is to wake up your thread
call notify();

 


Thứ Tư, 17 tháng 9, 2014

Programming Problem



You are given an unsorted array of n^2 arbitrary numbers, and we must output an n x n matrix of all the inputs such that all the rows and columns are sorted. For example, suppose n=3, n^2=9, and the 9 numbers are just the integers {1,2,...,9}
Possible ouput include:

1 4 7       


2 5 8      


3 6 9       


Am giving solution for this problem ...
Note:
to use this program in your machine you need to add my com.shashi.jcore package.you can download that by clicking link:download


program:

=============================================================

import java.util.Arrays;
 

import com.shashi.jcore.Matrix;
import com.shashi.jcore.SException;
public class ArrayClass {
 
 
public static void main(String []args) throws SException
 
{
int arr[]={2,1,4,3,6,5,8,7,9};
Arrays.sort(arr);
passArray(arr);
 
}
public static void passArray(int a[]) throws SException
 
{
int len=(int)Math.ceil(Math.sqrt(a.length));
int index=-1,row=0,col;
int arr[][]=new int[len][len];
for(;;)
 
{
for(col=0;col<len;col++)
 
{
arr[row][col]=a[++index];
 
}
row++;
if(row==len)
break;
 
}
//trnspose matrix now/*
Matrix m=new Matrix();
m.printMatTranspose(arr);
 
}
}
============================================
output:

1 4 7

2 5 8

3 6 9
 

Chủ Nhật, 14 tháng 9, 2014

C program with out main

Can You Write a C program with out main ????


If any one asks you this question from now say yes!!!!!Of course you can create a Cprogram and run it with out giving any main() function.

see below code snippet ..written by me


#include<stdio.h>
#include<conio.h>
#define code(s,h,a,v,r,c,e)e##v##s##c
#define decode code(i,h,u,a,r,n,m)
int decode()
{
clrscr();
printf("hello shashi kumar");
return 0;
}


output :

hello shashi kumar

------------------------------------------------
You might have confused by seeing above code .But it works fine(copy the code and run it on your own machine).

note:we are not calling main() in our  program but internally it calls.

How does the  above code works???

Its simple. We all know that C preprocessors  were compiled before actual program starts compiling, so I created two simple preprocessors here, namely

#define code(s,h,a,v,r,c,e)e##v##s##c ,#define decode code(i,h,u,a,r,n,m).

First one have arguments(),followed by e##v##s##c.Here #(pond[hash])  appends each character with its previous characters so whole statements treated as evsc .

The character e in evsc presented at 7th position of argument list of code(.....e),v presented at 4th position ,s presented at 1st position ,c presented at 6th position .

Next second preprocessor with a name decode  is calling code() of arguments i'e the positions of each character of code is substituted by positions of evsc.
i'e  e substituted by m
       v substituted by a
       s substituted by i
       c substituted by n










 

Thứ Sáu, 12 tháng 9, 2014

Problem:

Given a string , find if it is a palindrome or not. This string can contain special characters like comma hypen colon space semicolon etc. The program should ignore these special characters and find if the rest of the string is palindrome or not. Examples: 1. If the input string is "zapqa", the program should return "Not a Palindrome" 2. If the input string is "a,b-c;b^a ", the program should return "Palindrome" as it would ignore the special characters and the rest of the string abcba is a palindrome. The list of special characters that the program should ignore are `~!@#$%^&*()-_+={[}],<>?


solution:




package com.shashi;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
class stack1
{
private char mystack[],temp[];
private int length;
stack1(int length)
{
this.length=length;
mystack=new char[length];
}
private int top=-1;
void push(char ele)throws Exception
{
if(top==mystack.length-1)
{
  
temp=new char[mystack.length*2];
for(int i:mystack)
temp[i]=mystack[i];
mystack=temp;
mystack[++top]=ele;
}
else
mystack[++top]=ele;
}
public char pop()throws Exception
{

  if(top==-1)
  return ' ';
  else
  
return mystack[top--];
}
}

public class Polyndrome {

public static void main(String []args)throws Exception
{
boolean ispoly=false;
char che;
System.out.print("Enter your string:");
Scanner sc=new Scanner(System.in);
String data=sc.next();
ArrayList<Character>list=new ArrayList<Character>();
stack1 st=new stack1(data.length());
for(int i=0;i<data.length();i++)
{
if(isChar(data.charAt(i)))

list.add(data.charAt(i));

}
//copy all data from list to stack1
Iterator<Character > ite=list.iterator();
while(ite.hasNext())
{
st.push(ite.next());
}


for(int i=0;i<list.size();i++)
{
   che=list.get(i);
if(che==st.pop())
ispoly=true;
else
ispoly=false;
}

if(ispoly)
System.out.println("String is polyndrom");
else
System.out.print("String is not a palindrome");
}

public static boolean isChar(char c)
{
if((c>='a'&& c<='z') || (c>='A' && c<='Z'))
return true;
else
return false;

}

}

output:1

Enter your string:a,b-c;b^a
String is polyndrom

output 2:
Enter your string:shashi
String is not a palindrome

output:3
Enter your string:zapqa
String is not a palindrome


Thứ Năm, 11 tháng 9, 2014

Creating Stored Procedures in MYSQL.

A Stored procedure is a set of SQL statements are executed with a single call.(Something like similar to your c program calls).

Syntax:

CREATE PROCEDURE  your_procedure_name(parameters list...)

parameters list were those you specify while calling your procedure.Mysql procedure accept three type of parameters IN,OUT,INOUT.

IN-means your procedure accepting an input parameter.
OUT-means your procedure sends a value as a parameter to the calling one.
INOUT-means combination of in,out.

example:

First I will create a table called country to demonstrate procedures.

MySQL>create table country(name varchar(100),id int(40));

now insert some values in the above table.

MySQL>insert into country values('INDIA',1);
 
MySQL>insert into country values('USA',2);
 
MySQL>insert into country values('AUS',3);
 
MySQL>insert into country values('PAK',1);
 
MySQL>insert into country values('UK',1);
 
MySQL>insert into country values('BAN',1);  

lets create a  procedure for retrieving names of country with id 1 by crating procedure.

MySQL>delimiter //
MySQL>

CREATE PROCEDURE  country_procedure(IN cid  int(10))
BEGIN
             select name from country where id=cid;
END  //
MySQL>delimiter ;
Now call the procedure....
MySQL>call country_procedure(1);
****************
    INDIA                  
    PAK                     
    UK                       
    BAN                     
*****************


 

Thứ Bảy, 6 tháng 9, 2014

Write a recursive method to get the multiplication of two numbers such that there are minimum number of addition operations.....

Solution..


package com.shashikumar.com;

public class multiplication {
    public static void main(String []args)
    {
       
       
multiplication t=new multiplication();
        int a=10,b=88;//should give 880 when we multiply.
        System.out.print(t.multiply(a,b));
       
       
    }
    public  int multiply(int x,int y)
    {
        if(y==1)
            return x;
        else
            return (sumNumbers(x,y));
       
    }
    public  int sumNumbers(int m,int n)
    {
   
        if(n==1)
            return m;
        else
           
            return m+sumNumbers(m,n-1);
           
    }

}

output:
---------------------------
880

Thứ Sáu, 5 tháng 9, 2014

Creating custom tags in jsp.

custom tag means user defined tags.JSP allows you to define your own tags .

To create your own tags You have to create three things
1.A java class
2..tld file
3.a simple jsp file to access information

I will Crate a simple jsp tag that give simple information like who created that tag.
note:
In order to create custom tags definition in java class you have to extend or implement some interfaces/classes of javax.servlet.jsp.tagext.* package.

1.customTag.java

This class will implement SimpleTagSupport class of  javax.servlet.jsp.tagext.* package

package com.shashikumar;
import java.io.IOException;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
public class customTag extends SimpleTagSupport {

   
    public void doTag() throws JspException, IOException {
        JspWriter writer=getJspContext().getOut();
        writer.print("This is a custom tag defined by shashikumar .l");
    }


}


In above doTag() is a overloaded method of SimpleTagSupport class.







2.Message.tlb



<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My first custom tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>com.shashikumar.customTag</tag-class>>
<body-content>empty</body-content>
</tag>

</taglib>

3.custom.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="my" uri="WEB-INF/Message.tld" %>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hi custom tag</title>
</head>
<body>
<my:MyMsg/>


</body>
</html>


output:

Thứ Năm, 4 tháng 9, 2014

Uploading images into database server using jsp....

Hi guys,,,,,,

in my last tutorial i shown you how to upload images to server using simple java code.This time i will give you the example to upload images using jsp.

First you need to create a database table to store your image,let the table name be uploadImage

create table uploadImage(id int(500),image longblob);

The above query creates a table in your database.

Now I will write code to upload image using jsp.

let me first create a page that asks the user to browse an image from local machine

content.html
==============
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Content</title>
</head>
<body>

<form  method=""  action="upload.jsp">

<h3>Upload your Image </h3>
<input type="text" name="id" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="file" name="imageData" />

<input type="submit" value="submit" >

</form>
</body>
</html>


now,we have to write code for upload.jsp(see the action method  in form )

uploadjsp.jsp
------------------------
<%@ page language="java" import="java.sql.*,java.io.*,javax.sql.*" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Data Uploading</title>
</head>
<body>
<%!
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
String sql="insert into uploadImage values(?,?)";
File f=null;
FileInputStream fin=null;
%>
<%
try
{
String path="C:/wamp/";
String content=request.getParameter("imageData");
int identifier=Integer.parseInt(request.getParameter("id"));
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shasheikumar","root","shashei");
pst=con.prepareStatement(sql);
pst.setInt(1,identifier);
f=new File(path+content);
fin=new FileInputStream(f);
pst.setBinaryStream(2,(InputStream)fin,(int)f.length());
int res=pst.executeUpdate();
if(res>0)
{
    response.sendRedirect("success.html");
}
else
{
    response.sendRedirect("failure.html");
}
}
catch(Exception e)
{
    out.print(e.getLocalizedMessage());
}


%>
</body>
</html>


success.html
------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Your image loaded successfully</h3>

</body>
</html>


failure.html
--------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Oooops there is an error occured during processing</h3>
</body>
</html>



output
-------------------------------------------

now ,,if the image uploaded successfully you will get


 Finally you can check your uploaded image by moving into your database
type:

select * from uploadImage;





Thứ Ba, 2 tháng 9, 2014

Uploading images to server using simple java code.

Before starting your java code create table in your local database server

CREATE TABLE `uploadimage` (   `id` int(11) DEFAULT NULL,   `image` longblob );

Now write java code to upload your image

java code:
-----------
import java.sql.*;
import javax.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class uploadServlet {
    public static void main(String []arg)
    {
    Connection con=null;
    PreparedStatement pst=null;
    ResultSet rs=null;
    String sql="insert into uploadImage values(?,?)";
    File f=null;
    FileInputStream fin=null;
        try
        {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shasheikumar","root","shashei");
        pst=con.prepareStatement(sql);
        pst.setInt(1,2);
        f=new File("C:/wamp/1507517_561872823910921_8191424257028198921_o.jpg");
        fin=new FileInputStream(f);
        pst.setBinaryStream(2,(InputStream)fin,(int)f.length());
        int res=pst.executeUpdate();
            if(res>0)
            {
                System.out.print("your data uploaded");
            }
            else
                System.out.print("an error in uploading data");
        }
       
        catch(Exception e) {
            // TODO: handle exception
            System.out.print(e.getLocalizedMessage());
        }
       
                  

    }
   
}
output:

--------------

your data uploaded


checking weather my data uploaded to server or not

open your server command prompt.type

select * from uploadImage;

Now Right click on BLOB in the bottom you will get



Returning Pointer to pointer from a function...

Actually this question asked in TCS technical round interview.We can return a pointer to  pointer from a function .

am giving a sample code for it to demonstrate process..

sample code
----------------------------
#include<stdio.h>
#include<conio.h>
int** datavalue();
int main()
{
clrscr();
int **ptr;
ptr=datavalue();
printf("%d",++**ptr+3);
return 0;
}
int** datavalue()
{
    int *p,**ptr;
    int arr[]={1,2,3,4,5,6,7};
    p=arr;
    ptr=&p;
    return ptr;

}

output
=============
5

Explanatition:
ptr is a pointer to pointer so function must return double pointer(so am taken a **ptr ).
**ptr points to first value in array ,if we says like **ptr+3 it points to the 4th element (arry indices starts from 0),if e say like ++**ptr+3 it increase the value of (**ptr+3) i'e ++4 ,now ans becomes 5.
 

 


Thứ Hai, 1 tháng 9, 2014

Printing pascal triangle in c.

Here  is a pattern of pascal triangle..






It looks tough to code by seeing above pattern ,but it follows a specific logic called triangular array of the binomial coefficients..

lets see how it looks ..

Now its looking easy to code..we have to give spaces and calculate binomial coefficients using factorial method.

Solution :
-----------------------
#include<stdio.h>
#include<conio.h>
int factorial(int);
int main()
{
    int length,space,index,res,printvalue;
    printf("Enetr th length of your triangle");
    scanf("%d",&length);
    for(index=0;index<length;index++)
    {
    //give spaces first
        for(space=0;space<=(length-index-1);space++)
           printf(" ");
    //print fact value
        for(printvalue=0;printvalue<=index;printvalue++)
        {
            res=factorial(index)/(factorial(index-printvalue)*factorial(printvalue));
            printf("%d ",res);
        }
    //move to next line
        printf("\n");
    }

return 0;
}
int factorial(int num)
{
    int fact=1,index;
    for(index=1;index<=num;index++)
    fact=fact*index;
    return fact;

}

output:
---------------------------------
    
                  

Sample pattern program in "C"

Hi...

                     we have to print the below pattern using c.
 
pattern.

Due to complexity in our program am dividing my code into two parts.one for design upper part of pattern ,another for design lower part of my pattern.


Here is the code:

#include<stdio.h>
#include<conio.h>
void forward(int);
void backword(int);
int main()
{
int len;
clrscr();
printf("Enter pattern length");
scanf("%d",&len);
forward(len);
backword(len);
return 0;
}
void forward(int num)
{
    int space,index;
    for(index=1;index<=num;index++)
    {
    for(space=num-index;space>=1;space--)
        printf(" ");
        printf("%d",index);
    for(space=index*2;space>1;space--)
        printf(" ");
    printf("%d",index);
        printf("\n");
    }
}
void backword(int num)
{
    int space,index,currentvalue;
    for(index=1,currentvalue=num-1;index<num;index++,currentvalue--)
    {
        for(space=index;space>=1;space--)
        printf(" ");
        printf("%d",currentvalue);
        for(space=currentvalue*2;space>1;space--)
        printf(" ");
        printf("%d",currentvalue);
        printf("\n");
    }

}


output:
------------------------------






















Thứ Bảy, 30 tháng 8, 2014

An intoduction to AJAX technology.

Before we go deep into the technology lets have a refresh with traditional web-processing,Ajax web-processing

Traditional web-processing:
----------------------------------
With traditional web pages and applications, every time a user clicks on something, the browser sends a request to the server, and the server responds  with a whole new page.

 Now ,lets see the Ajax web-processing

Using Ajax, your pages and applications only ask the server for what they really need—just the parts of a page that need to change, and just the parts that the server has to provide.


now,lets write a simple Ajax program that gives current time and date of your machine.(In order to work with Ajax you need to have a basic knowledge on javascript,hrml,any one scripting language(php/jsp/asp...etc).

Html code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax Data base</title>
<script type="text/javascript">
var x;
function demo()
{
    if(window.XMLHttpRequest)
        {
        x=new XMLHttpRequest();
        }
    else
        {
        x=new ActiveXObject("Microsoft.XMLHTTP");
        }
    x.onreadystatechange=function()
    {
        if(x.readyState==4 && x.status==200)
            {
            document.getElementById("dat").innerHTML=x.responseText;
            }
    }
    x.open("GET","database.jsp", true);
    x.send();
}
</script>

</head>
<body>
<center>
<h5>THis is a demo on database
</h5></center>
<button type="button" onclick="demo()">GetDate</button>

<div id="dat"></div>
</body>
</html>


This looks like new to every one,but it is simple to understand.

1.An AJAX code is written inside a javascript function.
2.In order to connect this page to the server we need a request object,you will get this by using var x=new XMLHttpRequest();  but the problem is ,this will work only for browsers like mozilla ,netscape,safari...etc [doesn't work with internet explorer].
3.to work with internet explorer we need an ActiveXobject as show in program.
4.Now we have an object of request so,if there is any changes occured(user clicks on something) send that changes by using request object.
5.finally we have to specify to which page of server request will go? we do this by send("GET","database.jsp",null) method.

 database,jsp 

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%
out.print(new Date());
%>





output:


on clicking get data you will get(observe that your page will not loaded at this moment )



Thứ Sáu, 29 tháng 8, 2014

Checking weather two strings are anagrams or not? in c++

Hi Guys,

Anagrams: An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once
preconditions:
1.both strings must have same length
2.each character in string is unique(no character must be repeated).

For instance   string1="sir", string2="sri"   these two strings are anagrams.
Solution:
#include<iostream.h>
#include<string.h>
#include<conio.h>
int main()
{
clrscr();
char arr[]="sri";
char arr1[]="sir";
int i,j,c=0;
int len1=strlen(arr);
int len2=strlen(arr1);
if(len1!=len2)
cout<<"Both Strings are not an anagram";
for(i=0;i<len1;i++)
{
 for(j=0;j<len2;j++)
 {
    if(arr[i]==arr1[j])
    {
    c++;
    }
 }
}
if(c==len1 && c==len2)
cout<<"given strings are anagrams";
else
cout<<"given strings are not anagrams";
return 0;
}


output:
-----------------------------




Converting a String to int with out using parseInt() in java

Hi Guys ,welcome

         You might have performed converting a string to an int when you are reading data from standard inputstreams(because it treats input data as string format).

for example see the below snippet

Scanner sc=new Scanner(System.in);//sc is pointing to inputstream as in string format.
int data=sc.nextInt();

if you are readed data using BufferedReader,then code snippet will be like

InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br new BufferedReader(in);
int data=Integer.parseInt(br.readLine());

Now our aim is to perform same convertion with out using above methods.

preconditions are :
1.check if number is positive or negitive (do this by using charAt() method).
2.if number is negitive return negitive number

logic:
         number="12345"; //is a string number
         if(number.chatAt(0)=='-')//it is a negitive number so return negitive number
         return =number;

Solution:

                package logics;

public class check {
    public static void main(String []args)
    {

        String data="12345";
        System.out.println("String data before converting to int "+data);
        int res=toInt(data);
        System.out.println("in integer format \t"+res);
       
    }
    public static int toInt(String data)
    {
        int index,start=1,len=data.length(),intdata=1;
        boolean isnegitive=false;
        if(data.charAt(0)=='-')
        {
            isnegitive=true;
        }
        while(start<len)
        {
            intdata*=10;
            intdata+=(data.charAt(start++)-'0');
           
        }
        if(isnegitive)
            intdata=-intdata;
        return intdata;
       

    }
}


output:

------------------------------------------
String data before converting to int 12345
in integer format     12345
 


Thứ Ba, 26 tháng 8, 2014

String Chain program in Java

Hi Guys ,Welcome

Am giving you an intresting program here called "String Chain" .Before that we need to know what is string chaining???well,
 it's a process of chaining Strings baced on some specific characters arrangement.

for example:

let we have strings like  "shashi","shankar","rock","kiran","tail".Here chaining is done if and only if

last character of first string is equal to the first character of next string in an array.

now apply chain rule for above strings it becomes:

shankar-->rock--->kiran-->null (here null means there is no further names to place in this chain).

I hope you would  understand the concept..................lets move to code.

solution:


package logics;
import java.util.*;

public class StringChain {
    public static void main(String []args)
    {
        String []data={"shashi","shankar","rock","kiran","tail"};
        int index=0;
        int length1=data.length;
        ArrayList<String>list=new ArrayList<String>();
        String []res=new String[20];
        for(int i=0;i<length1;i++)
        {
            int endlength=data[i].length()-1;
       
            char end=data[i].charAt(endlength);
       
            for(int j=i+1;j<length1;j++)
            {
   
                char start=data[j].charAt(0);

           
                if(end==start)
                {
                   
                    res[index++]=data[i];
                   
                    res[index++]=data[j];

                }
               
            }
           
        }
        for(String str:res)
        {
            if(list.contains(str))
            {
            }
            else
            {
                list.add(str);
            }
        }
        Iterator<String> ite=list.iterator();
        while(ite.hasNext())
        {
            System.out.print(ite.next()+"-->");
        }
    }

}


output:

===============================
shankar-->rock-->kiran-->null-->