Monday, December 28, 2015

Factorial Using Recursion In Java

Factorials are very simple things. They're just products, indicated by an exclamation mark. For instance, "four factorial" is written as "4!" and means 1×2×3×4 = 24. In general, n! ("enn factorial") means the product of all the whole numbers from 1 to n; that is, n! = 1×2×3×...×n.

The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion
public static int factorial(int N) { 
   if (N == 1) return 1; 
else
   return N * factorial(N-1); 
} 


public class FactorialRecursion {

public static void main(String[] args) {

int n=5;
System.out.println(fact(n));


}
public static int fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);

}

}

Thursday, December 3, 2015

Custome Sorting Of Array Without Using Sort Method

Sorting of an array without using sort method in java is most popular in interview. so here is the solution. 
first i am taking an int type array a now for each loop is to printing the array
(you can skip this loop its not important.). 
now take an int temp which will store the value for temprary. 
now for loop wil be start from index 0 to length-1 inside this for loop another
loop will be start from 0 to length of array-2 . 
now in the if condition it will check if (a[j]<a[j+1] ) if this condition will be true than 
in temp value of a[j] will be store and a[j] will store value ofa[j+1].
in this step no. will swap according to value .

public class CustomSorting {

public static void main(String[] args) {

int [] a={7,45,36,64,77,34,72,95};
for(int no:a)
{
System.out.println("before sorting  "+no);
}

//temp store value temprary

int temp;
for(int i=0; i<=a.length-1;i++)
{
for( int j=0; j<=a.length-2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("  ..........   ");
for(int no:a)
  {
           System.out.println(" after sorting  "+no);
   }
}
}

}