Home > DeveloperSection > Forums > nested for loop in java for a triangle
john rob

Total Post:108

Points:756
Posted on    May-10-2013 2:26 AM

 C# C# 
Ratings:


 1 Reply(s)
 1235  View(s)
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! 


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-10-2013 9:14 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick