Program to output as below formate:
1
2 3
4 5 6
7 8 9 10

Answer Posted / debashree

In the above example one never knows how many lines are required to be print. So, to keep the program generic , we can implement it the following way:

public class FormattedOutput2 {

/**
* @param args
*/
public static void main(String[] args) {
printOutput(Integer.parseInt(args[0]), 1, 0);
}

private static void printOutput(int lastNum, int i, int num) {
int count = 0;
while(num < lastNum){
StringBuffer formatString = new StringBuffer();
while(count < i && num < lastNum){
formatString.append(++num + " ");
count++;
}
System.out.println(formatString);
i++;
count = 0;
}

}

}


Output for : 10
1
2 3
4 5 6
7 8 9 10

Output for: 102
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102

Is This Answer Correct ?    2 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is empty string literal in java?

559


How to convert string to byte array and vice versa?

582


What is the difference between preemptive scheduling and time slicing in java programming?

532


Can vector have duplicates in java?

505


I am a fresher and know core java, c languge, html, css etc if I am illegible for any job then send it on my email tatranakshay276@gmail.com

1074






What is integer valueof?

639


what is the use of bean managed and container managed with example?

1493


What are keywords in java?

573


What are void methods?

568


Why is it called boolean?

521


Why do we need strings in java?

521


What is slash r?

539


What is fail first in java?

567


Why are data types important?

535


What are benefits of java?

554