adding only odd numbers
- by Jessica M.
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);
}
}
}
}