Printing a nested for-loop pattern in java
-
22-09-2019 - |
Question
Goal:
1234
2345
3456
4567
5678
i have the pattern down but it doesnt println after length(4):
int i;
int a;
for (i = 1; i <= 5; i++)
{
for (a = i;a<=i+3;a++)
{
System.out.print(a);
}
}
My output is: 12342345345645675678
Solution
Just add it after the second loop:
int i;
int a;
for (i = 1; i <= 5; i++) {
for (a = i;a<=i+3;a++) {
System.out.print(a);
}
System.out.println();
}
OTHER TIPS
int i;
int a;
for (i = 1; i <= 5; i++)
{
for (a = i;a<=i+3;a++)
{
System.out.print(a);
}
System.out.println(); // add this code
{
No need to have two for loops, try :
for (i = 1; i <= 5; i++) {
int j = i;
System.out.println(j++ + "" + j++ + "" + j++ + "" + j);
}
EDIT : I know this will limit the flexibility, but this is just a toy problem.
int i;
int a;
for (i = 1; i <= 5; i++)
{
for (a = i;a<=i+3;a++)
{
System.out.print(a);
}
System.out.println();
}
Add System.out.println()
after the inner loop.
Try:
int i;
int a;
for (i = 1; i <= 5; i++) {
for (a = i;a<=i+3;a++) {
System.out.print(a);
}
System.out.println(); // this will print a new line.
}
Add System.out.Println()
after the inner loop. This will move the cursor to next line
Java Solution
int f, g, h,T;
f = 12345;
h = 11111;
for (g = 1; g <= 5; g++)
{
T = f + ((g - 1) * h);
System.out.print( T + "\n")
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow