Programs asked in interviews

Find out square root of a given number without using any built-in functions

    public static void findSquareRoot(double number)
    {
        boolean isPositiveNumber = true;
        double g1;
        //if the number given is a 0
        if(number==0)
        {
            System.out.println("Square root of "+number+" = "+0);
        }
        //If the number given is a -ve number
        else if(number<0)
        {
            number=-number;
            isPositiveNumber = false;
        }
        //Proceeding to find out square root of the number
        double squareRoot = number/2;
        do
        {
            g1=squareRoot;
            squareRoot = (g1 + (number/g1))/2;
        }
        while((g1-squareRoot)!=0);
        //Displays square root in the case of a positive number
        if(isPositiveNumber)
        {
            System.out.println("Square roots of "+number+" are ");
            System.out.println("+"+squareRoot);
            System.out.println("-"+squareRoot);
        }
        //Displays square root in the case of a -ve number
        else
        {
            System.out.println("Square roots of -"+number+" are ");
            System.out.println("+"+squareRoot+" i");
            System.out.println("-"+squareRoot+" i");
        }
    }

Find out if a year is LEAP Year

//Flag to store the test result

        boolean isLeapYear = false;
        if(year % 400 == 0)
        {
            isLeapYear = true; //400 -> TRUE
        }
        else if (year % 100 == 0)
        {
            isLeapYear = false; //100 -> FALSE
        }
        else if(year % 4 == 0)
        {
            isLeapYear = true; //4 -> TRUE
        }
        else
        {
            isLeapYear = false;
        }

Find out 2^n

            int power = 1;
            int i = 0;
            System.out.println("Powers of 2 that are less than 2^"+n);
            while (i <= n)
            {
                System.out.println("2^"+i+" = " + power);
                power = power * 2;
                i++;
            }
        }

 Generate Fibonacci series

        //Assigning the first two elements
        long[] FibonacciSeries = new long[limit];
        FibonacciSeries[0] = 0;
        FibonacciSeries[1] = 1;
        //Generates the Fibonacci series and store it in the array FibonacciSeries
        for(int i=2; i < limit; i++)
        {
            FibonacciSeries[i] = FibonacciSeries[i-1] + FibonacciSeries[i-2];
        }

 

0 comments: