Showing posts with label Looping Statements. Show all posts
Showing posts with label Looping Statements. Show all posts

Saturday, August 20, 2011

While Loop in java


class While
{
 public static void main(String arg[ ])
 {
  int sum=0,n=1;
  while(n<=15)
  {
    sum=sum+n;
    n=n+1;
   }
  System.out.println("Sum of first 15 nembers: "+sum);
  }
}

Do While Loop in Java


class DoWhile
{
 public static void main(String arg[ ])
 {
  int sum=0,n=1;
  do
  {
    sum=sum+n;
    n=n+1;
   }while(n<=20);
  System.out.println("Sum of first 20 nembers: "+sum);
  }
}

Find Sum using For Loop in java


class For
{
 public static void main(String arg[ ])
 {
  int sum=0;
  for(int n=1;n<=40;n++)
  {
    sum=sum+n;
   }
  System.out.println("Sum of first 40 nembers: "+sum);
  }
}

Show concept of Labelled Continue Break in java

//Show concept of Labelled Continue Break in java
class LabelledContinueBreak
{
 public static void main(String arg[])
  {
   loop:
    for(int i=1;i<100;i++)
     {
        System.out.println();
        if(i>=10)
        {
          break;
        }
       for(int j=1;j<100;j++)
        {
         System.out.print("  *");
            if(j==i)
            {
             continue loop;
            }
        }
      }
     System.out.print("Termination by BREAK");
  }
}

Print the pattern


Print 1
         2 2
         3 3 3
import java.io.*;
class Pattren
{
  public static void main(String arg[ ])
  {
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    int n;
    try
    { 
       System.out.println("Enter the number of lines you want in your ouput: ");
       n=Integer.parseInt(in.readLine());
       for(int i=1;i<=n;i++)
         {
          for(int j=1;j<=i;j++)
           {
             System.out.print("  "+i);
           }
           System.out.println();
       }
     }
     catch(Exception e){ }
   }
}

Next Home
Twitter Delicious Facebook Favorites More