Hi, I'm having a difficult time printing the product of the odd integers from 1 - 15. When I run it the program prints "1 2 2 2 2 2 etc." I don't see what I'm missing or why it won't print what I want. Did I add something I shouldn't have?

package javaapplication11;
/**
 *
 * @author Day
 */
public class test {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int p = 1;

        for (int i = 1;  i <= 15; i++)
        {
           if(p % 2 == 1)
           {
             p = p * i;
           }
           System.out.printf("%5d",p);
        }
    }
}

thanks.

What do you expect the print out to look like?
To print each number on a new line you need to add a new line character to the String being printed.
Add \n at the end of the String being printed.

Member Avatar for coil

What is the variable p supposed to do?

the assignment: Write a program that calculates the product of the odd integers from 1 - 15.

Adding a new line will display it vertically.

I'm initializing p to the value of 1. It's checks if the number is odd or even.

What do you expect the print out to look like?

You need to take a piece of paper and play computer with your code. Do each step in the code, write down the values of the variables as they change.
You will see your logic error when you do that.

Ok I'm not going to tell you what to do, but here's what's happening with the code you provided:

You start off with p set to 1. p % 2 does equal 1, so the first time thru, p = p * i, where i is 1. p = 1 * 1, so p is set to 1. Then p is printed, so 1 is printed.

The next time through p is still 1. p % 2 does equal 1, so the second time thru, p = p * i, where i is 2. p = 1 * 2, so p is set to 2. Then p is printed, so 2 is printed.

The third time through (and this is where your code gets "stuck on 2"), p starts as 2. Therefore, p % 2 does NOT equal 1, so the if-statement is never entered and p is never reset. Then p is printed. And this loops over and over with p never changing because the loop is never entered because p % 2 is never 1.

Good luck with solving the problem!

Thank you guys :] I figured it out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.