/** * Problems: *
* 1) Print all the positive integers less than 100 * that are divisible by 3. * * 1B) Then print those numbers only 5 per line. ** * Uncomment each solution to test it. * * @author Zach Tomaszewski * @version 10 Oct 2008 */ public class DivisibleByThree { public static void main(String[] args) { // // 1) Print all the positive integers less than 100 // that are divisible by 3. // /* // // 1a) Go through the numbers 1 to 100, // printing each one only if it's divisible by 3 // for (int i = 1; i < 100; i++) { if (i % 3 == 0) { System.out.println(i); } } */ /* // // 1b) Go through only the numbers we know we'll have to print. // That is, start at 3 and print every 3rd number from there // for (int i = 3; i < 100; i += 3) { System.out.println(i); } */ /* // // 1c) Who said we need to start at the bottom? // This is as 1a, but prints in reverse. // for (int i = 100; i > 0; i--) { if (i % 3 == 0) { System.out.println(i); } } */ /* // //1d) An interesting student-suggested approach, // this for loop effectively goes from 1 to 33 (looping through // the factors that we are multiplying by 3) // for (int i = 1; (i * 3) < 100; i++) { System.out.println(i * 3); } */ // // 1B) As above, but print 5 numbers per line. // /* // // 1Ba) One way to do this is just print a newline (println()) after // each number that is divisible by 5 (or by 15). (Of course, // doing this depends on somewhat on the nature of our data--the fact // that only every 5th number that we print will be divisible by 5.) // for (int i = 1; i <= 100; i++) { if (i % 3 == 0) { System.out.print("\t" + i); if (i % 5 == 0) { System.out.println(); } } } //Bug: What happens if we don't nest the ifs, but have them one after // the other? Why does this change produce the output that is does? */ /* // // 1Bb) Here's a solution that doesn't depend on the nature of // the numbers/data that are being printed: we'll separately track the // number of time's we've printed a number on each line. // int printedThisLine = 0; //how many numbers I've printed on this line for (int i = 1; i <= 100; i++) { if (i % 3 == 0) { System.out.print(i + "\t"); printedThisLine++; } if (printedThisLine == 5) { //end the line and reset the counter System.out.println(); printedThisLine = 0; } } System.out.println(); */ } }