Home Need of declaration of a variable in a for loop
Reply: 0

Need of declaration of a variable in a for loop

user1962
1#
user1962 Published in May 24, 2018, 4:00 pm

This question already has an answer here:

  • Scope of variable declared in for loop 6 answers

I am newbie but cannot find the answer to this question after looking thoroughly in other questions.

Why is there a need sometimes to declare a variable and sometimes not? I give you two examples:

Example 1: here, we don't have to declare i before the for loop.

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }

Example 2: Here we need to declare i before the loop.

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

        int[][] arrayOfInts = { 
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }

I will appreciate if you could also tell me why do I have also to initialize the variable j = 0 if within the for loop I am already assigning the value 0.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.335305 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO