thenewbie
thenewbie

Reputation: 27

printing a pattern using for loop by accepting a string

Sample input string:

bluej

Output:

b***b
*l*l*
**u**
*e*e*
j***j

(where '*' indicates a blank space)

I have done this much so far:

int n = s.length() - 1;
int i, j;
for (i = 0; i <= n; i++) {
    for (j = 0; j <= (n + 1); j++) {
        if (i == j || i == n - (j - 1))
            System.out.print(s.charAt(i));
        else {
            System.out.print("*");
        }
    }
    System.out.println();
}

But output is:

b****b
*l**l*
**uu**
**ee**
*j**j*

Upvotes: 0

Views: 96

Answers (4)

Ankur Mahajan
Ankur Mahajan

Reputation: 3596

Just replace i == n-(j-1) with i == n - j and second for loops for (j = 0; j <= n+1; j++) to for (j = 0; j <= n; j++) :

int n = s.length() - 1;
int i, j;
for (i = 0; i <= n; i++) {
    for (j = 0; j <= n; j++) {
        if (i == j || i == n - j)
            System.out.print(s.charAt(i));
        else {
            System.out.print("*");
        }
    }
    System.out.println();
}

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76444

Step 1: Look at the number of characters. You are displaying 6 characters, while the expected output displays 5 characters. You need to change the end of the inner for, like this:

for(j=0;j<=(n);j++)

Step 2: You are expecting to have n+1 as the last index for j, but it was changed to n. You need to apply it:

if(i== j || i == n-(j))

Examples:

  • i = 0, then the condition is true for j = 0 and j = 4
  • i = 1, then the condition is true for j = 1 and j = 3
  • i = 2, then the condition is true for j = 2
  • i = 3, then the condition is true for j = 3 and j = 1
  • i = 4, then the condition is true for j = 4 and j = 0

Upvotes: 2

MrYo
MrYo

Reputation: 1817

It Works:

    String s = "bluej";
    int n = s.length() - 1;
    int i, j;
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= (n); j++) {
            if (i == j || i == n - (j))
                System.out.print(s.charAt(i));
            else {
                System.out.print("*");
            }
        }
        System.out.println();
    }
}

Upvotes: 1

Anonymous Coward
Anonymous Coward

Reputation: 3200

2nd loop termination condition should be j<=n.
if condition should be (i == j || i == n - j)

Testing your code in a debugger while checking the values of the involved variables would likely let you solve it yourself.

Upvotes: 2

Related Questions