Ali Ahmed
Ali Ahmed

Reputation: 19

debugging(eclipse) using for loop cannot get an expected answer

I am beginner in java and trying to teach myself before going to college.So here is my simple program,

public class Lesson_16_1 {
public static void main(String[] args) {

    int counter;

    for(counter = 5; counter <= 20; counter=counter+2);
    System.out.println("the counter is at "  + counter);
    }
}

The expected variables should be 5,7,9,11,13,15,17,19.

Instead what i get the output is " the counter is at 21"

I do not understand why the value come 21 although i clearly state the condition <=20.Please reply me as soon as possible.Thanks million.

Upvotes: 0

Views: 41

Answers (3)

M Alok
M Alok

Reputation: 1081

you have used a semicolon at the end of for statement , here :

for(counter = 5; counter <= 20; counter=counter+2);

the syntax to write the for loop is as follows ,

for(initialization ; condition ; step ){

//repeatable task here 
}

here step can be like incrementing the loop variable (which in your case is counter) or decrementing. if your repeatable task is a single statement (which is your case) then you can write for loop without curly braces , as follows ,

for(counter = 5; counter <= 20; counter=counter+2)
    System.out.println("the counter is at "  + counter);

but as i mentioned it is only for single statement .

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35597

your for loop doesn't have a body (nothing to execute while iterating)

for(counter = 5; counter <= 20; counter=counter+2); // it is ending here

You need to change your code to following to get what you are expecting

 for(counter = 5; counter <= 20; counter=counter+2){
    System.out.println("the counter is at "  + counter);
 }

Upvotes: 1

libik
libik

Reputation: 23049

You have semicolon which "stops" for-cycle to do anything else

So change this

 for(counter = 5; counter <= 20; counter=counter+2);

to this

 for(counter = 5; counter <= 20; counter=counter+2)

Also good advice - ALWAYS use braces, it does not hurt and the code is more readable :

public static void main(String[] args) {
    int counter;

    for(counter = 5; counter <= 20; counter=counter+2){
        System.out.println("the counter is at "  + counter);
    }
}

Upvotes: 1

Related Questions