Defining a variable inside for loop

I want to make some basics clear :slight_smile:

Now In insertion sort we use 2 for loops and inside the for loop we keep track of key element which is to be inserted

CODE

    for(int i = 0 ; i < n ; i++) 
`                  `int key = a[i]
                    int j = i-1
                    while j >= 0 && a[i] < a[j]:
                               a[j+1] = a[j]
                               j--
                    a[j+1] = a[i]

What difference it will make when we write code like this(predefining variables)

 int i,key,j;
    for(i = 0 ; i < n ; i++) 
    `                  `key = a[i]
                        j = i-1
                        while j >= 0 && a[i] < a[j]:
                                   a[j+1] = a[j]
                                   j--
                        a[j+1] = a[i]
1 Like

Performance wise there will be no difference, the 1st approach is just a clear representation that the variables are only used inside the loop and have no function outside the loop…!!!

Anything related to memory???

I also had the same doubt during my +2… I have seen a link explaining this clearly :slight_smile:

1 Like

everything I wanted :slight_smile: Thank you soo much :slight_smile:

Remember JAVA is an OOP Language so defining the variables inside the for loop kinda saves time and its representation is more easily readable.

1 Like

Explained in the link provided by @prasu_newbie Anyway thanx :slight_smile:

//