Q:

Java code not working properly-- working on odd summation

I am very new to Computer Science. I am trying to learn Java on my own for fun. I found some practice problems online and have gotten stuck. I am trying to write a simple loop to determine odd numbers. I want the loop to add one odd number at a time and then to sum the total. For example I want the program to display the numbers like A1 = {1}, A2 = {1, 3}, A3 = {1, 3, 5}, A4 = {1, 3, 5, 7}... where each A# adds on an additional odd number each time through the loop and then I also want to determine the total sum of all the list from A1 to A20. The sum should be as such. {1)+{1,3},+{1,3,5}=14 
public class MyClass {
    public static void main(String args[]) {
        int limit = 20;
        int sum = 0;
        for (int i = 1; i <= limit; i++) {

            // if the number is not divisible by 2 then it is odd
            if (i % 2 != 0) {
                System.out.print(i + " ");

            }
        }
    }
}

The code above displays odd numbers all together not the way I am hoping for. It also does not sum up the odd numbers. 
Any help would be appreciated, thank you. 

A:

Think about what you need to do: You have one loop that goes up to a limit, and every time you are executing a loop, you want to print all of the odd numbers up to your loop counter(in your case, i).
To determine all the odd numbers up to i, an easy way is to add another loop like so:
for (int j = 1; j<=i; j+=2) {...}. In this loop, you would both print that number, and add it to your sum counter (sum += j).
For console clarity, make sure to print an empty line after that loop. Hope that helps without giving it away completely

