Sunday, January 29, 2012

JAVA Programming : Factorial

JAVA Factorial 


Factorial is a mathematical operation Factorial of a positive number n is denoted by n! and defined as the product of all numbers from 1 to the n. The syntax of factorial of number n is:


  n! = n*(n-1)*(n-2)*(n-3)......2*1  


For Example:-


       7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040       



Note:- Factorial of zero is 1 (i.e. 0! = 1).

import java.util.Scanner;
public class Factorial {
  public int fact(int n){
    int fact =1;
    for (int i =; i <= n; i++) {
      fact=fact*i;
    }
    return fact;
  }

  public static void main(String[] args) {
    Factorial f = new Factorial();
    System.out.println("Enter a Nu4mber");
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    int result = f.fact(num);
    System.out.println("Facotial of "+num+" is "+result);
  }
}

Output of Program:-

Friday, January 27, 2012

JAVA Programming : Pyramids 2

JAVA Pyramids 2


In the previous post we have discussed about different pyramids examples and we will continue to do some more examples. In this tutorial I will post the code of some more complex pyramid examples.

         *
        ***
       *****
      *******
     *********      

Code for this program:-

import java.util.Scanner;
public class Pyramid {  
  public static void main(String[] args) {
    System.out.println("Enter the length of pyramid");  
    Scanner scan = new Scanner(System.in);
    int rows = scan.nextInt();
    System.out.println("-------Output------");
    for (int i = 1; i <= rows; i++) {
      for (int j = rows-1; j >= i; j--) {
        System.out.print(" ");
      }
      for (int k = 1; k <= i; k++) {
        System.out.print("*");
      }
      for (int l = 2; l <= i; l++) {
        System.out.print("*");
      }
      System.out.println();
    }
    System.out.println("-------------------");
  }
}

Output of Program:-


      ************     
      *****  *****
      ****    ****
      ***      ***
      **        **
      *          *

Code for this Program:-

import java.util.Scanner;
public class Pyramid {  
  public static void main(String[] args) {
    System.out.println("Enter the length of pyramid");  
    Scanner scan = new Scanner(System.in);
    int rows = scan.nextInt();
    System.out.println("-------Output------");
    for (int i = 1; i <= rows; i++) {
      for (int j = rows; j >= i; j--) {
        System.out.print("*");
      }
      for (int k = 2; k <= i; k++) {
        System.out.print("  ");
      }
      for (int l = rows; l >= i; l--) {
        System.out.print("*");
      }
      System.out.println();
    }
    System.out.println("-------------------");
  }
}

Output of Program:-


     ************     
     *****  *****
     ****    ****
     ***      ***
     **        **
     *          *
     *          *
     **        **
     ***      ***
     ****    ****
     *****  *****
     ************

Code for this Program:-


Thursday, January 26, 2012

JAVA Programming : Pyramids

JAVA Pyramids


In the last few tutorials we have discussed some basic concepts of programming and in next few posts we will be using them to make some simple programs.
Pyramids are very common examples that I think every programmer had made at the time of start learning programming. Pyramids are very useful in teaching the use of loops. There are numerous types of pyramids example. Lets start with an basic example.

       *
       **
       ***
       ****
       *****      

Creating the Pyramid Program:- We will make an simple program that will take an integer input from user and print the asterisks pyramid with that much number of rows.

import java.util.Scanner;
public class Pyramid {  
  public static void main(String[] args) {
    System.out.println("Enter the length of pyramid")
    Scanner scan = new Scanner(System.in);
    int rows = scan.nextInt();
    System.out.println("-------Output------");
    for (int i = 1; i <= rows; i++) {
      for (int j = 1; j <= i; j++) {
        System.out.print("*");
      }
      System.out.println();
    }
    System.out.println("-------------------");
  }
}

In this program, first we take an integer input form user using Scanner class and than nested for loop is declared (i.e. a loop inside another loop). In this the outer for loop will run the same number of times as enter by user(from 1 to the enter number) and after every iteration it will print a new row and increment the loop control variable by 1. Inside the outer loop a new inner for loop is declared which will print the same number of asterisk as the current iteration value of outer loop control variable. 

Output of Program:- 

Reverse Pyramid: The next program we will be making is to print a reverse pyramid. The reverse pyramid will look like:-
      *****    
      ****
      ***
      **
      *   

The code for printing a reverse pyramid is not very different from the previous one. Infact we can actually do it just by changing one line. Take a look at the code below.

import java.util.Scanner;
public class Pyramid {  
  public static void main(String[] args) {
    System.out.println("Enter the length of pyramid");  
    Scanner scan = new Scanner(System.in);
    int rows = scan.nextInt();
    System.out.println("-------Output------");
    for (int i = rows; i >= 1; i--) {
      for (int j = 1; j <= i; j++) {
        System.out.print("*");
      }
      System.out.println();
    }
    System.out.println("-------------------");
  }
}

If you look at the code above, we have just made a slight change in the declaration of outer loop.  This it the outer loop will start from the entered number and end at 1. After every iteration we decrease the value by one.

Output of Program:-


Some more examples of different Pyramids:-

       *       
       **       
       ***       
       ****       
       *****       
If you look at this example, it can look a bit confusing, but it is not as much difficult as you might think. Lets take a look below.
      ----*
      ---**      
      --***
      -****
      *****      
Now its easy to understand the logic for this program. For this program we have to need to an extra for loop in our previous code of pyramid. Here is the code :

import java.util.Scanner;
public class Pyramid {  
  public static void main(String[] args) {
    System.out.println("Enter the length of pyramid");  
    Scanner scan = new Scanner(System.in);
    int rows = scan.nextInt();
    System.out.println("-------Output------");
    for (int i = 1; i <= rows; i++) {
      for (int j = rows-1; j >= i; j--) {
        System.out.print(" ");
      }
      for (int k = 1; k <= i; k++) {
        System.out.print("*");
      }
      System.out.println();
    }
    System.out.println("-------------------");
  }
}

Output of Program:-

For more pyramid examples go to : JAVA Pyramids 2 

Sunday, January 22, 2012

JAVA Programming : Break, Continue And Return

JAVA Break, Continue And Return


Java has three type of branching control keywords: break, continue and return. These keywords are used to change the normal flow of execution of program.

Break keyword :
The break keyword is used to stop the execution of the loops. In many situations we need to get out of the loop before the loop execution is complete. Whenever a break keyword is encountered inside a loop the execution gets out of loop and start executing the next line of code after the loop. The break statement is of two types: labeled and unlabeled.

Unlabeled break statement:
Unlabeled break statement is used to get out of a single loop. If unlabeled break is used inside the nested loops it will exit only from the loop in which break is used. Lets see the example below:

public class UnlabeledBreak {
  public static void main(String[] args) {
    int i = 1;
    while (i < 10) {
      if (i == 5) {
        break;
      }
      System.out.println("i = " + i);
      i++;
    }
  }
}

Output of Program:

Labeled Break Statement: 
Labeled breaks statement is used when we need to break the nested loops. Lets understand the difference between Labeled and Unlabeled break statement with an example.
In this example we need to traverse a 2D array and print the elements of array until a particular element is found. To do this we have to use nested loops. Now to break and get out of the nested loops we need to use labeled break.

public class LabeledBreak {
  public static void main(String[] args) {
    int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
    OuterLoop:
    for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a[0].length; j++) {
        System.out.println(a[i][j]);
        if(a[i][j]==6){
          break OuterLoop;
        }
      }
    }
    System.out.println("Program Ends");
  }
}

Output of Program:-


Continue Keyword:- Continue statement statement is used to skip a single iteration of a loop. Whenever a continue keyword is encountered inside a loop, the current iteration of loop ends just like a normal end of any iteration without executing the statement written after the continue statement inside the loop. Just like break statement continue statement is also of two types: labeled and unlabeled.

Unlabeled Continue Statement:

public class UnlabeledContinue {
  public static void main(String[] args) {
    int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    System.out.println("Numbers divisible by 3 or 5");  
    for (int i = 0; i < a.length; i++) {
      if(a[i]%3!=&& a[i]%5!=0){
        continue;
      }
      System.out.println(a[i]);
    }
  }
}

Output of Program:

Labeled Continue Statement:

public class ContinueLabel {
  public static void main(String args[]) {
    outer: 

    for (int i = 1; i < 10; i++) {
      for (int j = 1; j < 10; j++) {
        if (j > i) {
          System.out.println();
          continue outer;
        }
        System.out.print((i)+" ");
      }
    }
    System.out.println();
  }
}

Output of Program:-

Return Keyword:- Return statement is a bit different form break and continue as break and continue changes the normal control flow of loops but return statement works on the control flow of the method. Return statement stops execution of the method and transfer the control back to the caller of the method. The return statement can be used in two ways,  return statement that returns a value and another that does not return a value. Return statement must return the same type of value as defined in the declaration of method. If the method is defined as void than return statement will not return any value.

public class ReturnStatement {

  public static void main(String[] args) {
    ReturnStatement rs = new ReturnStatement();
    System.out.println("Largest Number is: " + rs.largestNumber(51015));
  }

  public int largestNumber(int num1, int num2, int num3) {
    int largest = 0;
    if ((num1 > num2&& (num1 > num3)){
      largest = num1;

    }
    else if ((num2 > num3&& (num2 > num1)){
      largest = num2;

    }
    else{
      largest = num3;

    }
    return largest;
  }
}

The use of return statement will be more clear in upcoming tutorials and we will be using it more and more now.


Tuesday, January 10, 2012

JAVA Programming : For Each Loop

JAVA For Each Loop


For each loop or Enhance For loop is a extended version of basic for loop which was introduced in Java 5. For each loop is designed to make iteration over arrays and collections much easier. For each loop also makes the code more readable. In this post we will learn about basics of For each loop using  Arrays. We will discuses more about For Each loop when we learn about Collections and Iterator.

Syntax of For Each Loop:-

        for (type var : arr) {  
        //body-of-loop  
    }

Example of For Each Loop:- This is a very simple example in which we will traverse an array using For Each loop and print all the elements of the array.


public class ForLoop {
  public static void main(String[] args) {
    char[] charArr = {'a','b','c','d','e'};    
    for (char c : charArr) {
      System.out.println(c);
    }
  }
}



To understand the difference between Basic For loop and For Each Loop, here is the same program using For Loop.


public class ForLoop {
  public static void main(String[] args) {
    char[] charArr = {'a','b','c','d','e'};    
    for (int i = 0; i < charArr.length; i++) {
      System.out.println(charArr[i]);
    }
  }
}



Advantages of For Each Loop:-
  • Less number of variables are used
  • Less chance of errors
  • Improve Readability 
Limitation of For Each Loop:- 
  • Cannot traverse multiple collection at once.
  • Iterates only forward by single steps.