Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Trying to get a for-statement to work correctly

The program I'm trying to write takes a positive integer N from the user and then calculates and displays the sum of the first N odd integers. So for example, if N is 3, the program should display the number 9 which is 1 + 3 + 5.

I recognize that I could write the program so that it just squared N, but I'm specifically writing the program to help me get a better handle on conditional statements.

This is what my code looks like so far:

public void run(){

int N = readInt("Which number do you choose? ");

for (int i = 1; i<=N; i+=2){

println(i + "+");

}

}

My SPECIFIC question in regards to this code is: how should I change the test condition to get the program to function correctly? Right now it produces numbers but stops when the last number produced is <= to N. I need the test condition to signal to stop when the number of times the for statement has REPEATED is <= to N. Any suggestions?

Thank you!

1 Answer

you need to count up to 2*N then test for oddness with the modulo (%) operator. so for N of 3, your loop would start at 1 and go up to 2*N. then in the loop body, test for oddness and only print if odd. for N=3 this will print 1, 3, 5.

Thank you!