Thursday, March 12, 2009

Write a program in java to get in output as follows.

Question :Write a program in java to get in output as follows.
1
1 2
1 2 3
1 2 3 4.
Write the program in java to get in output as follows.
1
2 3
4 5 6
7 8 9 10
Provide a solution (CoreJava)

Answer :Below is the sample programme that gives you this output.
public class A
{
public static void main(String args[]) throws Exception
{
/**
* outputs the following format
* 1
* 2 3
* 3 4 5
* 4 5 6 7
*/
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < i; j++) {
System.out.print(i + j +" ");
}
System.out.println("");
}
System.out.println("*****************");
/**
* outputs the following format
* 1
* 1 2
* 1 2 3
* 1 2 3 4
*/
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j +" ");
}
System.out.println("");
}
System.out.println("*****************");
/**
* outputs the following format
* 1
* 2 3
* 4 5 6
* 7 8 9 10
*/
int k=1;
int y = 1;
for (int i = 1; i <= 4; i++) {
for (int j = 0; j < k; j++) {
System.out.print(y++ +" ");
}
k++;
System.out.println("");
}
}
}

No comments: