Thursday, 20 August 2015

How to find prime no.

 import java.io.*
 public class PrimeNo {
  public static void main(String args[]) {
   Console con = System.console();
   int num = Integer.parseInt(con.readLine());
   for(int i=2;i<=num/2;i++) {
    temp=num%i;
    if(temp==0) {
     isPrime=false;
     break;
    }
   }
   //If isPrime is true then the number is prime else not
   if(isPrime)
    System.out.println(num + " is Prime Number");
   else
    System.out.println(num + " is not Prime Number");
  }
 }

Thursday, 13 August 2015

To check if a number is Armstrong number using java

public class ArmstrongNumber {

    public static void main(String args[]) {
        int n = 0, temp = 0, r = 0, s = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number ");
        if (in.hasNextInt()) {
            n = in.nextInt(); // if there is another number
        } else {
            n = 0;
        }
        temp = n;
        while (n != 0) {
            r = n % 10;
            s = s + (r * r * r);
            n = n / 10;
        }

        if (temp == s) {
            System.out.println(n + " is an Armstrong Number");
        } else {
            System.out.println(n + " is not an Armstrong Number");
        }
    }
}

Wednesday, 5 August 2015

Write a program for print Fibonacci series

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] + " ");
         }
    }
}

Sunday, 2 August 2015

How to swap two numbers without using temporary variable?

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);
    }
}