NESTED FOR LOOP IN JAVA FOR A TRIANGLE

john rob

Total Post:108

Points:756
Posted by  john rob
C# 
C#
 1612  View(s)
Ratings:
Rate this:
Hi Expert

I have been trying to create a triangle in this sequence:

1
21
321
4321
54321

(without the gaps in between )

even though my syntax is correct, I have been going through logical errors with non-terminating loops.
this is the program which I'm trying to fix:
for(i=1;i>=1;i++)
    {
        for(j=i;j<=i;j=j-1)
        {
            System.out.print(j);        
        }
        System.out.println(); 
    }
help would really be appreciated for this.

Thanks in advance! 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: nested for loop in java for a triangle

    Hi John!


    You get non-terminating loop because of this

    for(i=1;i>=1;i++)

    The code means, you want to loop the body if i greater or equal than 1 (i>=1), and this i value are always incremented by 1 (i++) for each loop, so it always have value greater than 1 and this condition is always correct for the loop code. So you must correct the loop statement.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!