Vedant Chandra
Vedant Chandra

Reputation: 382

Logic fault with nested loops pattern

I wrote a class to print a pattern:

1
2   4
3   5   7
4   6   8   10
5   7   9   11  13

I used this code:

public class pat3
{
    public void method()
    {
        int row;
        int val;

        for(row=1;row<=5;row++)
        {
            for(val=1;val<=row;val++)
            {
                System.out.print(val + 2 + "\t");
            }

            System.out.println();
        }
    }
}

I have used two nested loops, the outer one controls rows in the pattern, and the inner one controls columns. Cross-referencing this with previous pattern problems, my logic seems okay.

However, I am getting an incorrect output when I run this class:

3   4   
3   4   5   
3   4   5   6   
3   4   5   6   7   

I have tried changing the variables around and re-wording the for loops, but my output always varies randomly with no correlation, so I cannot find the cause of the problem. Can anybody help me out?

P.S. I'm new to coding, so no smart-alecky mathematical answers please, I'd just like a straightforward answer as to the problem in the code.

Upvotes: 0

Views: 706

Answers (5)

T-Bull
T-Bull

Reputation: 2146

Make the inner loop like this:

        for(val=0;val<row;val++)
        {
            System.out.print((row + 2*val) + "\t");
        }

Ideone

Upvotes: 1

NeplatnyUdaj
NeplatnyUdaj

Reputation: 6242

Minimal modification to your code:

System.out.print(row + (val - 1)*2 + "\t");

Upvotes: 0

Luka Klarić
Luka Klarić

Reputation: 333

Try this as your for loop:

for(int row=0;row<5;row++)
    {
        for(int val=0;val<=row;val++)
        {
            System.out.print(row+ 1 + val * 2 + "\t");
        }

        System.out.println();
    }

Upvotes: 1

Mengjun
Mengjun

Reputation: 3197

Change the code to the following one:

public void method()
{
    int row;
    int val;

    for(row=1;row<=5;row++)
    {
        for(val=1;val<=row;val++)
        {
            System.out.printf("%2d ", row + (val-1)*2);
        }

        System.out.println();
    }
}

Output in console as follows:

 1 
 2  4 
 3  5  7 
 4  6  8 10 
 5  7  9 11 13 

Upvotes: 0

SpiderShlong
SpiderShlong

Reputation: 224

public void method()
{
    int row;
    int val;

    for(row=1;row<=5;row++)
    {
        for(val=0;val<row; val++)
        {
            System.out.print((2*val) + row);
        }

        System.out.println();
    }
}

Upvotes: 0

Related Questions