Google+

Saturday, December 28, 2013

Program for displaying EVEN / ODD , FIBONACCI numbers and to SWAP without using Temp.

 Java is used in a wide variety of computing platforms from embedded devices and mobile phones on the low end, to enterprise servers and supercomputers on the high end.

1) This program is used to display EVEN /ODD numbers within a range you specify.

EXAMPLE :

EVEN numbers : 0 2 4 6 8 10 12 14 16 18 20 ....
ODD numbers  : 1 3 5 7 9 11 13 15 17 19...

PROGRAM :

package Blog;
import java.util.Scanner;
/**
 * @author Arun
 */
public class evenodd {
    public static void main(String args[])
    {
        System.out.println("Enter the range till which EVEN and ODD number to be printed :");
        Scanner scn = new Scanner(System.in);
        int numb = scn.nextInt();
        System.out.println("EVEN numbers within range is :");
        for(int i=0;i<=numb;i+=2)
        {
            System.out.print(i+" ");
        }
        System.out.println();
        System.out.println("ODD numbers within range is :");
        for(int i=1;i<=numb;i+=2)
        {
            System.out.print(i+" ");
        }
    }    

}

2) This program is used to display FIBONACCI numbers within a range you specify.

EXAMPLE:

Fibonacci numbers : 0 1 1 2 3 5 8 13 ...

PROGRAM:

package Blog;
import java.util.Scanner;
/**
 * @author Arun
 */
public class fibonacci {
    public static void main(String [] args)
    {
        int i=0,temp,currval;
        Scanner scn = new Scanner(System.in);
        System.out.println("Enter the range till which fibonacci number to be displayed :");
        int fib = scn.nextInt();
        System.out.print(i+" ");
        temp=i;
        i++;
        currval=i;
        while(i<fib)
        {
         System.out.print(currval+" "); 
         currval = i + temp;
         temp = i;
         i = currval;                             
        }        
    }    
}

3) This program is used to SWAP two numbers WITHOUT use of TEMPORARY variable :

EXAMPLE :

Before Swapping : a = -10 , b = -20
After Swapping : a = -20,b=-10

PROGRAM :

package Blog;
import java.util.Scanner;
/**
 * @author Arun
 */
public class swap {
    public static void main(String args[])
    {
        Scanner scn = new Scanner(System.in);
        System.out.println("Enter number A :");
        int a = scn.nextInt();
        System.out.println("Enter number B :");
        int b= scn.nextInt();
        a=a+b;
        b=(a-b);
        a=(a-b);
        System.out.println("Value in A :"+a);
        System.out.println("Value in B :"+b);
    }
    
}
Please don't forgot to give your valuable comments..


No comments:

Post a Comment