thinker - 1 year ago 42

Java Question

I'm new to Java.

I can't seem to understand why these two codes produce different outputs.

Please explain this to me.

What is the difference of y<=x; and y<=5;. As you can see the x is = 5 too, I don't understand why I get different outputs.

`for(int x=0; x<5; x++){`

for(int y=1; y<=x; y++){

System.out.print("x");

}

for (int g=4; g>=x; g--){

System.out.print("*");

}

System.out.println();

}

output:

x****

xx***

xxx**

xxxx*

`for(int x=0; x<5; x++){`

for(int y=1; y<=5; y++){

System.out.print("x");

}

for (int g=4; g>=x; g--){

System.out.print("*");

}

System.out.println();

}

output:

xxxxx*****

xxxxx****

xxxxx***

xxxxx**

xxxxx*

Answer Source

Basically the main difference is this line:

```
for(int y=1; y<=x; y++)
```

resp.

```
for(int y=1; y<=5; y++)
```

The number of times the loop is executed is different. Namely in the first case it is variable (so the number of 'x' increases), in the second case it is fixed (5 'x' printed each time).

(edit: typo)