adding only odd numbers

Posted by Jessica M. on Stack Overflow See other posts from Stack Overflow or by Jessica M.
Published on 2012-11-15T10:47:02Z Indexed on 2012/11/15 11:00 UTC
Read the original article Hit count: 473

Filed under:

So the question I'm trying to solve the user is supposed to enter any positive number. Then I'm trying to write a program that adds only the odd numbers up to the number the user enters and displays the total. So for example if the user enters 4 my program should add four odd numbers. 1 + 3 + 5 + 7 = 16.
The only tools I have available are for statement, if, if/else if,while loop and println.

I can only figure out how to print out the odd numbers. I know I want to create a variable named total to store the value of adding up all the odd numbers but I don't know how that fits into the program.

import acm.program.*;

public class AddingOddNumbers extends ConsoleProgram {
    public void run() {
        int n = readInt("enter a positive nunber: ");
        int total = 0;
        for (int i = 0; i < n; i++) {
            if (n == 1) {
                println(1);
            } else {
                println((i * 2) + 1);
            }
        }
    }
}

© Stack Overflow or respective owner

Related posts about java