Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Position and Alternatives of Naming Java loop control variable in `for(){}` loops

Loop Control Variable Naming and Assignment Options (header vs. assignment in body of loop)

In short, a) is the control variable (i.e., ‘counter’) in a for loop usually named i out of convention and/or syntax, b) and is it advisable that one change the name inside the loop header or should one rather make an assignment inside the loop body? To make this question clear, I have presented two simple code blocks below for illustration, one with i and the other without. N.B., the assignment within the loop body of the first block.

// maintain use of i
class Coffee {
  
  public static void main(String[] args) {
    
    int cupsOfCoffee = 1;
    

    for (int i = 1; i <= 100; i++) {
      i = cupsOfCoffee;
      cupsOfCoffee++;
      System.out.println("Molly drinks cup of coffee #" + i);
    }   
  }
}

Or this one, eliminating i:

// use cupsOfCoffee as control variable
class Coffee {
  
  public static void main(String[] args) {
    
  
    for (int cupsOfCoffee = 1; cupsOfCoffee <= 100; cupsOfCoffee++) {
      
      System.out.println("Molly drinks cup of coffee #" + cupsOfCoffee);
      
    }    
  }
}

Expansion of Question

Traditionally we use i as the control variable in initialization, the boolean expression, and increments in the header of loop (for (int i = 1; i <= 100; i++)). Suppose, I am counting the cups of coffee (cupsOfCoffee) that Molly drinks. Is the first code block, leaving i in the loop header and declaring i = cupsOfCoffee preferred syntactically and/or by convention, or is the second method acceptable? The goal of this question is to make sure my code is stylistically, conventionally, and syntactically correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In my opinion, it is perfectly acceptable to use variables other than i or j in loops. Programming is about writing understandable code, so a variable called ´cupsOfCoffee´ is very self-explanatory. It could thus also be useful for developers, working on the project you are working on.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading