Monday, November 3, 2014

Java array



Write a program to find common elements between two arrays

package com.java2novice.algos;
public class CommonElementsInArray
{
public static void main(String a[])
{
        int[] arr1 = {4,7,3,9,2};
        int[] arr2 = {3,2,12,9,40,32,4};
        for(int i=0;i
       {
            for(int j=0;j
            {
                if(arr1[i]==arr2[j])
               {
                    System.out.println(arr1[i]);
                }
            }
        }
    }
}

How to swap two numbers without using temporary variable

package com.java2novice.algos;
public class MySwapingTwoNumbers
{
public static void main(String a[])
{
        int x = 10;
        int y = 20;
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        x = x+y;
        y=x-y;
        x=x-y;
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
    }
}

Write a program to print fibonacci series

package com.java2novice.algos;
public class MyFibonacci
{
public static void main(String a[])
{
         int febCount = 15;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
for(int i=2; i < febCount; i++)
 {
             feb[i] = feb[i-1] + feb[i-2];
 }
for(int i=0; i< febCount; i++)
 {
                 System.out.print(feb[i] + " ");
         }
    }
}

Write a program to find sum of each digit in the given number using recursion

package com.java2novice.algos;
public class MyNumberSumRec
{
int sum = 0;
public int getNumberSum(int number)
{
         if(number == 0)
         {
            return sum;
         }
         else
       {
            sum += (number%10);
            getNumberSum(number/10);
        }
        return sum;
    }
    public static void main(String a[])
   {
        MyNumberSumRec mns = new MyNumberSumRec();
        System.out.println("Sum is: "+mns.getNumberSum(223));
    }
}

Write a program to check the given number is a prime number or not

package com.java2novice.algos;
public class MyPrimeNumCheck
{
public boolean isPrimeNumber(int number)
{
         
        for(int i=2; i<=number/2; i++)
        {
            if(number % i == 0)
           {
                return false;
            }
        }
        return true;
    }
    public static void main(String a[])
   {
        MyPrimeNumCheck mpc = new MyPrimeNumCheck();
        System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17));
        System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19));
        System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15));
    }
}

No comments:

Post a Comment