Friday, 30 June 2017

How to swap two numbers without using temporary variable?


Description:
Write a program to swap or exchange two numbers. You should
not use any temporary or third variable to swap.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.govindsblog.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);
    }
}

Output:
Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10

Thursday, 29 June 2017

Write a program to print fibonacci series.


Description:
In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. Below example shows how to create fibonacci series.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.govindsblog.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] + " ");
         }
    }
}

Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377