Reputation: 1459
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);
}
}
}
}
Upvotes: 2
Views: 19257
Reputation: 70929
Maybe you know how to compute the sum of all numbers up to a given number n
? The formula is quite simple: (n * (n+1))/2
. Now getting the sum of only the odd numbers is a bit trickier but - no worries you can make use only of the previous formula for that. First notice that the sum of all even numbers up to a given number n is:
(((n/2)* (n/2+1))/2) * 2
if N is even(i.e. the sum of all numbers up to n/2 times two that is because you have 2+4+6+8+...N = 2*(1+2+3+...n/2)
)((((n-1)/2)* ((n-1)/2+1))/2) * 2
if N is oddIn fact if you have integer division the formula is always: (((n/2)* (n/2+1))/2) * 2 = (n/2)* (n/2+1)
So to compute the sum of all the odd numbers up to n you simply subtract the sum of the even numbers from the sum of the all numbers:
(n * (n+1))/2 - (n/2)*(n/2+1)
In fact if you observe closely you will notice that the sum 1+3+...(2*n-1)
always equals to n^2
.
This answer should help you solve your problem in all languages and I am leaving the code to you. It is literally one line.
Upvotes: 1
Reputation: 2475
int oddSum = 0;
for (int i = 0; i < n; i++){
oddSum = oddSum + (i*2) + 1;
}
Upvotes: 0
Reputation: 533492
I would use a loop for the odd numbers as well.
for (int i = 0, j = 1; i < n; i++, j += 2) {
println(j);
total += j;
}
println(total);
Upvotes: 0
Reputation: 121357
This will give you the odd number sum.
if (n>0)
{
total=0;
for (int i = 1; i < n; i ++){
if (i%2 == 1)
total+=i;
}
}
If you want to inclusive of n, then change the condition to i<=n
.
Upvotes: 1
Reputation: 8771
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);
total += (i * 2) + 1;
}
}
println("total : " + total);
}
}
Upvotes: 2