Monday, December 20, 2010

Basic Logics Behind Pattern Printing In BlueJ - Chapter II

Lets take another simple pattern like:

A
AA
AAA
AAAA

As I have discssed in my previous post that firstly we have to count the number of rows. Here the row numbers are 4, so the outer loop will execute four times. The number of columns in all the rows are not same but there is a sequence in which they are increased. In each iteration the number of columns increases by 1. The outer loop will execute for 4 times and there is no doubt about it. But the problem is with the inner loop.

We will set such a variable in the conditional statement of the inner loop that increases by 1 after each full course iteration of the inner loop. It is the outer loop control variable which increases by 1 after each of it's iteration. So, the problem is solved. Place the outer loop control variable in the conditional statement of the inner loop.

Using for loop the program on pattern printingwill be like:

class PatternDisplay
{
int i,j;
public void show()
{
for(i=0;i< 4; i++)
{
for( j=0; j< =i;j++)
{
System.out.print("A");
}
System.out.println();
}
}
public static void main(String args[])
{
PatternDisplay ob=new PatternDisplay();
ob.show();
}
}


Again the same program on printing pattern can be done using nested do while loop.

class PatternDisplay
{
int i,j;
public void show()
{
i=0;
do
{
j=0;
do
{
System.out.print("A");
j++;
}while(j<=i);
System.out.println();
i++;
} while(i<4);
}
public static void main(String args[])
{
PatternDisplay ob=new PatternDisplay();
ob.show();
}
}

Here in this above program using do while loop, the outer loop prints the rows and the inner loop prints the pattern.
Loop control variable of the outer do while loop is 'i' while that of the inner do while loop is 'j'.

Related PostBlueJ Programs On Pattern

2 comments:

  1. pls explaing using void main and excluding


    public static void main(String args[])
    {
    PatternDisplay ob=new PatternDisplay();
    ob.show();

    ReplyDelete
    Replies
    1. Are you looking for this one?



      class PatternDisplay
      {
      int i,j;
      public void main()
      {
      i=0;
      do
      {
      j=0;
      do
      {
      System.out.print("A");
      j++;
      }while(j<=i);
      System.out.println();
      i++;
      } while(i<4);
      }
      }

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner