Write a program in JAVA to print :
1
12
123
1234
12345
Answers
class pattern_1
{
public void main()
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
The pattern is printed according to the above logic .
The i-loop is used for the rows .
The j-loop is used for the columns .
The statement "println" helps to print the line gap .
The statement "print" has no such gap .
The printing is done by the j-loop and after the 'j' gets printed , I have added a space so that the program looks nice .
first thought about an iterative solution to this.
//Iterative Solution
public static String bar(final int n){
final StringBuilder builder = new StringBuilder();
for (int i = 1; i <= n ; i++) {
for (int j = 1; j <= i ; j++) {
builder.append(j);
}
builder.append(" ");
}
return builder.toString();
}
The fact that this relies on 2 nested loops suggests to me that it is not possible to produce a recursive solution using only a single method and no loops. So I've had to include a loop to build up the individual sections within the recursion.
//Recursive Solution (with some iteration too)
public static String foo(final int n) {
if( n == 1 ) {
return 1 + " ";
}
String s = "";
for (int i = 1; i <= n; i++) {
s += i;
}
return foo(n-1) + s + " ";
}
Both of these produce the same output when called with 4, so my main method:
public static void main(final String args[]){
System.out.println(bar(4));
System.out.println(foo(4));
}
Produces this output:
1 12 123 1234
1 12 123 1234