Wednesday, February 23, 2011

Basic logics behind pattern printing in BlueJ - Chapter II

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'.

5 comments:

  1. plz hel me with this pattern
    a
    ab
    abc
    abcd
    abcde

    ReplyDelete
    Replies
    1. public class gh
      {
      public void main()
      {
      String s="abcde";
      int len=s.length();
      char ch=' ';

      for (int i=0; i<len; i++)
      {

      for (int j=0; j<=i; j++)
      {
      ch=s.charAt(j);
      System.out.print(ch);
      }
      System.out.println();
      }
      }
      }

      Delete
  2. plz help me with this pattern
    1
    3 1
    5 3 1
    7 5 3 1

    ReplyDelete
  3. b___b
    _l__l_
    __u__
    _e__e_
    j____j

    __indicates space

    ReplyDelete
  4. ABCDE
    ABCD
    ABC
    AB
    A

    PLease print this pattren using while loop

    ReplyDelete