Hello, I need help with writing the sum of the odd numbers in this specific form
ID: 641736 • Letter: H
Question
Hello,
I need help with writing the sum of the odd numbers in this specific format:
1 + 3 + 5 + 7 + 9 + 11 = 36
36 = 11 + 9 + 7 + 5 + 3 + 1
So far I have:
public static void main(String[] args) {
int a = 0;
int original;
int b;
if (a <= 0){
TextIO.putln("Max?");
a = TextIO.getlnInt();
original = a;
}
if (a%2 == 0){
a = a-1;
}
int counter = 0;
int sum = 0;
while (a > 1){
sum = sum + a;
System.out.print(a + " + ");
a = a - 2;
if(a == 1){
System.out.print(a);
sum = sum + 1;
}
}
System.out.print(" = " + sum );
} // end of main method
} // end of class
When i do this i get (with 11) 11+9+7+5+3+1 = 36
Explanation / Answer
import java.util.Scanner;
public class SwitchTest {
public static void main(String[] args) {
int a = 0;
int original;
int b;
if (a <= 0){
TextIO.putln("Max?");
a = TextIO.getlnInt();
original = a;
}
if (a%2 == 0){
a = a-1;
}
int counter = 0;
int sum = 0;
while (a > 1){
sum = sum + a;
System.out.print(a + " + ");
a = a - 2;
if(a == 1){
System.out.print(a);
sum = sum + 1;
}
}
System.out.print(" = " + sum );
System.out.print(sum + " = ");
int i = original;
while (i > 0) {
if (i % 2 == 1) {
if (i == a) {
System.out.print(i);
} else {
System.out.print(i + " + ");
}
}
i--;
}
} // end of main method
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.