Thursday, September 18, 2014

Pattern In BlueJ using Nested And Single Loop



In this program we will display the pattern as follows:

1 2
3
4 5

7 8
9
10 11

This pattern can be displayed using nested loop and a single loop. The following program is using a single loop.


import java.io.*;

class P
{


 int i,n,x=1;

 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

 void show() throws Exception
 {
         System.out.print("\nEnter the Last Number of the series:");
        n=Integer.parseInt(br.readLine());
        
         for(i=1;i<=n;i++)
         {
            
            x++;
            System.out.print(i+" ");
            if(x==3)
            {
                x=0;
            System.out.println();
        }
        else if(x==1)
        {
            x=1;
            System.out.println();
        }
        }
    }
         
    public static void main(String args[])throws Exception
    {
         P ob=new P();
         ob.show();
        }
    }
    
Read Also: Computer Teacher in Burdwan
    Sample Output:
    Enter the Last Number of the series:11
1 2 

4 5 

7 8 

10 11 


Same pattern using nested loop


import java.io.*;

class P1
{


 int i=1,j,n,x=1;

 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 void show() throws Exception
 {
         System.out.print("\nEnter the Last Number of the series:");
        n=Integer.parseInt(br.readLine());
     
         for(;;)
         {
         
            for(j=0;j<=i;j++)
            {
            System.out.print(x+" ");
            x++;
        }
            if(i==1)
            i=0;
            else
            i=1;
            if(x>n)
            break;
         
            System.out.println();
        }
        }
       
    public static void main(String args[])throws Exception
    {
        P1 ob=new P1();
         ob.show();
        }

    }

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner