Thursday, 30 April 2015

Looping

Programming languages provide various control structures that allow for more complicated execution paths.There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:
As we mentioned earlier, the programming you are doing now is sequential programming. This means that flow is downward, from top to bottom, with every line of code being executed, unless you tell Java otherwise.
You saw in the last section that one way to "tell" Java not to execute every line is by using IF Statement to section off areas of code.
Another way to interrupt the flow from top to bottom is by using loops. A programming loop is one that forces the programme to go back up again. If it is forced back up again you can execute lines of code repeatedly.
As an example, suppose you wanted to add up the numbers 1 to 10. You could do it quite easily in Java like this:
int addition = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
But you wouldn't really want to use that method if you needed to add up the numbers 1 to a 1000. Instead, you can use a loop to go over a line of code repeatedly until you've reached 1000. Then you can exit the loop and continue on your way.
Java Tutorial

Java programming language provides the following types of loop to handle looping requirements. Click the following links to check their detail.
Loop TypeDescription
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loop
Like a while statement, except that it tests the condition at the end of the loop body
In today's article we will understand how to work with loop in Java programming. We will talk about the topics below:
  • For Loop in Java Programming
  • While Loop in Java Programming
  • Do while Loop in Java Programming
  • Use of continue in Java Programming
  • Use of break in Java Programming
These topics are very important to understand, when you are using the loops in your applications. Because sometimes we need to break or continue any iteration in loops. As you know we use the loops in any programming language just for the iterations.
Loop :
There are three types of looping concepts in Java Programming as we used in C++. These are used for different purpose, and we can use them to run same iteration and result will be same too. But their aim is change lets check the syntax in listing 1:
Listing 1: Syntax:
For(intial condition; final condition; increment/decrement)
{
//Statements here we will use the statements or conditions also
}
While(Condition)
{
//Statements here we will use the statements or conditions also
}
Do{
// Statements here we will use the statements or conditions also
}while(condition);

For Loop :

We use for loop, when we know how much it should be repeat the iteration. It is very useful at that time when we fully agree about its limit. Because sometimes we want to repeat an iteration to given conditions, as we want to write a line just 1000 times. So the for loop is very useful for it to write it from 1 till 1000. Let’s check it in listing 2 for details how we can use it, in java Programming.
Listing 2: Use of For loop in Java Programming
public class ForLoop{
  public static void main(String args[])
  {
    //printing in ascending order
    //from 1 to 10
    //using increment operator
    for(int i=1; i<=10; i++)
    {
      System.out.print(i+" ");
    }
    System.out.println();
    //printing in descending order
    //from 10 to 1
    //using decrement operator
    for(int i=10; i>=1; i--)
    {
      System.out.print(i+" ");
    }
  }
}
In this listing 2 example there is a simple program. I gave the class name as ForLoop and in the main method I used for loop to times. In the first loop, it is increasing the iteration from 1 to 10 and in the second loop it is decreasing the iteration from 10 to 1. As I told you in the syntax we can use increment and decrement operators in for loop.

While Loop :

We use while loop in Java Programming to certain number of iterations. And it will not work like for loop. Let’s check it in listing 3 for details, but in the listing 3 we use the same program which we did in listing 2. But we will change for loop in while.
Listing 3: Use of While Loop in Java Programming
public class WhileLoop{
  public static void main(String args[])
  {
    //printing in ascending order
    //from 1 to 10
    //using increment operator
    int i = 1;
    while(i <= 10)
    {
      System.out.print(i+" ");
    i++;
    }
    System.out.println();
    //printing in descending order
    //from 10 to 1
    //using decrement operator
      i = 10;
    while (i >= 1)
    {
      System.out.print(i+" ");
      i--;
    }
  }
}
Do while Loop :
The do while loop is good to use, because it will run or execute once at any cost. It is similar like while loop. For more details about the do while loop. Let’s we check the listing 4.
Listing 4: Use of Do While Loop in Java Program
public class DoWhileLoop{
  public static void main(String args[])
  {
    //printing in ascending order
    //from 1 to 10
    //using increment operator
    int i = 1;
    do
    {
      System.out.print(i+" ");
    i++;
    }while(i <= 10);
    System.out.println();
    //printing in descending order
    //from 10 to 1
    //using decrement operator
      i = 10;
    do
    {
      System.out.print(i+" ");
      i--;
    }while (i >= 1);
  }
}
In the listings 2, 3, & 4 we use the for loop, while loop and do while loop. In these examples there are fully simple and easy examples. Which are defining the correct use of all three loops. These loops sometimes do something different, because during the programming we create complex algorithms so we become confuse. Which control statements should be use now, for example we are creating an application and we are giving options to the user to choose the options and use the application. At that time we commonly we use the while or do while loop. Because using for loop becomes so difficult that type of algorithms. Let’s check the listing 5 for details.
Listing 5: Using Control statement in Java Programming
import java.util.Scanner;

public class ControlStatment{
  public void Display(){
    System.out.println("Welcome to Mr.bool");
  }
  public void ForLoopSytax(){
  String syntx = "for(initial;final;incre/decre){statment}";
  System.out.println(syntx);
  }
  public void WhileLoopSytax(){
  String syntx = "while(condition){statment}";
  System.out.println(syntx);
  }
  public void DoWhileLoopSytax(){
  String syntx = "do{statment}while(condition);";
  System.out.println(syntx);
  }
  public void Application(){
     Scanner input = new Scanner(System.in);
     char letter;
     letter = (char)input.nextInt();
   do
    {
      Display();
      System.out.println("Please Choose Any Option");
      System.out.println("Press [F] For For Loop Syntax..");
      if(letter == 'F' || letter == 'f')
      {
        ForLoopSytax();
      }
      System.out.println("Press [D] For Do While Loop Syntax..");
      if(letter == 'D' || letter == 'd')
      {
        DoWhileLoopSytax();
      }
      System.out.println("Press [W] For While Loop Syntax..");
      if(letter == 'W' || letter == 'w')
      {
        WhileLoopSytax();
      }
      System.out.println("Press [N/n] For Exit From The Application");
    } while(letter != 'N' || letter != 'n');
  }
  public static void main(String args[]){
    ControlStatment CS = new ControlStatment();
    CS.Application();
  }
}
In the listing 5, the program will be stop when the user will input N or n letter. If the user input any other as mentioned in the program so it will call the methods according to the letter. We can use the loops for any purpose in our programs. We use the loops to control the situations or control the iterations in the programming.
Now we will use some keywords with loops iterations. These keywords are being used to make more powerful execution of the iterations in loops. These keywords are continue and break.

Keyword Continue :

The keyword continue is used in the control statements with condition statements. Control statements mean that we use continue commonly in loops when we are using the conditional statements in loops. The continue statement will continue the iteration when the conditional statement is true.
Keyword Break :
The keyword break is used to stop the iterations in control statements. Sometimes we need to stop the loops at a specific point. We also use the conditional statements in this case, when the conditional statement is true then iteration will be stop.
NOTE: We can use continue and break keywords in a single loop iterations when we are using the conditional statements. It depends on us when conditional statement is true or false what it should to do? Let’s check the listing 6 for details about the break and continue keywords.
Listing 6: Break Keywords
public class Keyword{
  public static void main(String args[]){
    for(int i=1; i<=10; i++)
    {
      if(i == 5)
      {
        System.out.println("Loop stopped at 5th iteration");
        break;
      }
    }
  }
}
As you can see in the listing 6, when the iteration reached at the 5 from 1. The iteration stopped due to break keyword. Now lets we use the continue keyword in listing 7
Listing 7: Continue Keyword
public class Keyword{
  public static void main(String args[]){
    for(int i=1; i<=10; i++)
    {
      if(i % 2 == 0)
      {
        System.out.printf("\nLoop is at %dth iteration..",i);
        continue;
        
      }
      else if(i == 5)
      {
        System.out.printf("\nLoop stoped at %dth iteration",i);
        break;
        
      }
    }
  }
} 
In this listing 7, I used both keywords continue and break. When if condition is true so the iteration will be stop at 5th iteration, otherwise the else will be true and the iteration will be continue.

List of Looping Program Example
List of Looping Optimize Solution Program Example

Tuesday, 28 April 2015

For loop

We use for loop, when we know how much it should be repeat the iteration. It is very useful at that time when we fully agree about its limit. Because sometimes we want to repeat an iteration to given conditions, as we want to write a line just 1000 times. So the for loop is very useful for it to write it from 1 till 1000. Let’s check it in listing 2 for details how we can use it, in java Programming.
Listing 2: Use of For loop in Java Programming

 public class ForLoop{
  public static void main(String args[]){
   //printing in ascending order
   //from 1 to 10
   //using increment operator
   for(int i=1; i<=10; i++){
    System.out.print(i+" ");
   }
   System.out.println();
   //printing in descending order
   //from 10 to 1
   //using decrement operator
   for(int i=10; i>=1; i--){
    System.out.print(i+" ");
   }
  }
 }
In this listing 2 example there is a simple program. I gave the class name as ForLoop and in the main method I used for loop to times. In the first loop, it is increasing the iteration from 1 to 10 and in the second loop it is decreasing the iteration from 10 to 1. As I told you in the syntax we can use increment and decrement operators in for loop.

Monday, 27 April 2015

while loop


We use while loop in Java Programming to certain number of iterations. And it will not work like for loop. Let’s check it in listing 3 for details, but in the listing 3 we use the same program which we did in listing 2. But we will change for loop in while.
Listing 3: Use of While Loop in Java Programming
public class WhileLoop{
public static void main(String args[])
{
//printing in ascending order
//from 1 to 10
//using increment operator
int i = 1;
while(i <= 10)
{
System.out.print(i+" ");
i++;
}
System.out.println();
//printing in descending order
//from 10 to 1
//using decrement operator
i = 10;
while (i >= 1)
{
System.out.print(i+" ");
i--;
}
}
}

Saturday, 25 April 2015

Write a Program for Signed right shift operator

a>>n or -a>>n
import java.io.*;
class MyFirst
{
public static void main(String args[])
{
int i=31,x=1,sum=0,j;
int bin[] = new int[32];
int bin1[] = new int[32];
Console con = System.console();
System.out.print("Enter a Value");
int num = Integer.parseInt(con.readLine());
System.out.print("Enter a Shift");
int b = Integer.parseInt(con.readLine());
if(num>0)
{
// convert decimal to binary and print
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// right signed shift and print blank bit automatic fill by 0

for(i=31-b,j=31;i>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// convert binary to decimal

for(i=31;i>=0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
System.out.println("Number after Shift"+sum);
}
else
{
// convert binary to decimal and print

num=num*(-1);
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// 1's and 2's compliment and print

for(i=31;i>=0;i--)
{
if(bin[i]==0)
bin[i]=1;
else
bin[i]=0;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();
for(i=31;i>=0;i--)
{
if(bin[i]==1)
bin[i]=0;
else
{
bin[i]=1;
break;
}
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// right signed shift and blank bit fill by 1 or print

for(i=31-b,j=31;i>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();
for(;j>=0;j--)
{
bin1[j]=1;
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// 1's and 2's compliment and print

for(i=31;i>0;i--)
{
if(bin1[i]==0)
bin1[i]=1;
else
bin1[i]=0;
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();
i=31;
while(i>=0)
{
if(bin1[i]==1)
bin1[i]=0;
else
{
bin1[i]=1;
break;
}
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// binary to decimal convert

for(i=31;i>0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
sum=sum*(-1);
System.out.println("Number after Shift"+sum);
}
}
}

Thursday, 23 April 2015

Write a Program for Unsigned right shift operator

a>>>n or -a>>>n
import java.io.*;
class MyFirst
{
public static void main(String args[])
{
int i=31,x=1,sum=0,j;
int bin[] = new int[32];
int bin1[] = new int[32];
Console con = System.console();
System.out.print("Enter a Value");
int num = Integer.parseInt(con.readLine());
System.out.print("Enter a Shift");
int b = Integer.parseInt(con.readLine());
if(num>0)
{
// convert decimal to binary and print
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// right unsigned shift and print

for(i=31-b,j=31;i>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// convert binary to decimal

for(i=31;i>=0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
System.out.println("Number after Shift"+sum);
}
else
{
// convert binary to decimal and print

num=num*(-1);
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// 1's and 2's compliment and print

for(i=31;i>=0;i--)
{
if(bin[i]==0)
bin[i]=1;
else
bin[i]=0;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();
for(i=31;i>=0;i--)
{
if(bin[i]==1)
bin[i]=0;
else
{
bin[i]=1;
break;
}
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// right unsigned shift and print

for(i=31-b,j=31;i>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// binary to decimal convert

for(i=31;i>0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
System.out.println("Number after Shift"+sum);
}
}
}

Wednesday, 8 April 2015

Write a Program for left shift operator

a<< n or -a<<n
import java.io.*;
class MyFirstProg
{
public static void main(String args[])
{
int i=31,x=1,sum=0,j;
int bin[] = new int[32];
int bin1[] = new int[32];
Console con = System.console();
System.out.print("Enter a Value");
int num = Integer.parseInt(con.readLine());
System.out.print("Enter a Shift");
int b = Integer.parseInt(con.readLine());
if(num>0)
{
// convert decimal to binary and print
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// left shift and print

for(i=31,j=31-b;j>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// convert binary to decimal

for(i=31;i>=0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
System.out.println("Number after Shift"+sum);
}
else
{
// convert binary to decimal and print

num=num*(-1);
while(num!=0)
{
bin[i]=num%2;
num=num/2;
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// 1's and 2's compliment and print

for(i=31;i>=0;i--)
{
if(bin[i]==0)
bin[i]=1;
else
bin[i]=0;
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();
for(i=31;i>=0;i--)
{
if(bin[i]==1)
bin[i]=0;
else
{
bin[i]=1;
break;
}
}
for(i=31;i>=0;i--)
{
System.out.print(bin[i]);
}
System.out.println();

// left shift and print

for(i=31,j=31-b;j>=0;i--,j--)
{
bin1[j]=bin[i];
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// 1's and 2's compliment and print

for(i=31;i>0;i--)
{
if(bin1[i]==0)
bin1[i]=1;
else
bin1[i]=0;
}
i=31;
while(i>=0)
{
if(bin1[i]==1)
bin1[i]=0;
else
{
bin1[i]=1;
break;
}
i--;
}
for(i=31;i>=0;i--)
{
System.out.print(bin1[i]);
}
System.out.println();

// binary to decimal convert

for(i=31;i>0;i--)
{
sum=sum+x*bin1[i];
x=x*2;
}
sum=sum*(-1);
System.out.println("Number after Shift"+sum);
}
}
}

Friday, 3 April 2015

Bitwise and Bit Shift Operators


The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);
}
}