Search code examples
javaclassdata-structuresprintinginteger

How to print a loop of integers 0-9 with n (the parameter) added to it?


So I have an assignment that is to print integers 0-9, but it takes an integer parameter that adds it to each integer. If it were to be printCount(5), it would print: 5, 6, 7, 8, 9, 10, 11, 12, 13, 14. However, another modification was instructed such that if the number n is being added to is DIVISIBLE BY 2, then the output is 1/2 the number PLUS n. If it is divisible by 3, then the output is 0. The intended output if it were printCount(5) now would be: 5, 1, 6, 0, 7, 5, 8, 7, 9, 0. I was instructed to make a for loop AND and while loop in 2 different methods. The for loop looks like:

public static void printCount(int n) {
        System.out.println("For Loop Output:");
        for (int i = 0; i < 9; i++) {
            if (i % 2 == 0) {
                System.out.print((i%2) + n);
            }
            else if (i % 3 == 0) {
                System.out.print(0);
            }
            else {
                System.out.print(i);
            }
        }
        System.out.println();
    }

This prints: 515055575, but it is not correct. The while loop looks like:

public static void printCountWhile(int n) {
        int i = 0;
        System.out.println("While Loop Output:");
        while (i < 9) {
            if (i % 2 == 0) {
                System.out.print(i+n);
                i++;
            }
            else if (i % 3 == 0) {
                System.out.print(0);
                i++;
            }
            System.out.print(i);
            i++;
        }
    }

This also prints out wrong, printing: 517395117139. How can I fix both of these? Thank you so much for the help.


Solution

  • This would be the answer for the for loop the assignemnt for the while I did not understand. You mistook % modulo for division /

    public static void printCount(int n) {
            System.out.println("For Loop Output:");
            for (int i = 0; i < 9; i++) {
                if (i % 2 == 0) {
                    System.out.print((i/2) + n);
                }
                else if (i % 3 == 0) {
                    System.out.print(0);
                }
                else {
                    System.out.print(i);
                }
            }
            System.out.println();
        }