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:
------------------------------