0

I'm trying to make my for loop print ODD numbers and print their sum and average.
Here's my code:

public class Loop_For2 {
    public static void main (String[] args) { 
        double sum = 0f; 
        int ctr = 1, ctr2 = 0; 
        for (;ctr<=10; ctr++, ctr2++) {
            System.out.println(ctr); 
            sum += ctr; 
        }
        double ave = (double) sum/ctr2;
        System.out.println ("The sum is: " +sum);
        System.out.println ("The average is: " +ave); 
    }
} 

OH, and I'm not supposed to use 'if'. Thanks again!

Edited by mike_2000_17: Fixed formatting

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by tong1
0

Take a look at my response to your previous post regarding loops. The structure of the for loop is:

for (initialization; termination; increment) {
    //do something
}

Nobody said the that the initialization and increment parts need to be only by 1 each iteration. One can, for example increment as he/she see fits:

for (int i = 0; i < 5; ++i) {
    //do something
}

for (int i = 500; i < 5000; i += 100) {
    //do something
}

for (int i = 100; i > 90; --i) {
    //do something
}

for (int i = 50; i < 100; i *= 2) {
    //do something
}
0

One should write the following line of code to update the control variable ctr (the ODD numbers less than 10):

for (;ctr<=10; ctr+=2, ctr2++) {

Edited by tong1: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.