Reputation:
I just wrote a program to increase the value of arrays by 1. But, when i used an enhanced for loop I could not add get the same result....... USING FOR LOOP
class array{
public static void main(String args[]){
int rajath[]={11,22,33,44};
change(rajath);
for(int x:rajath){
System.out.println(x);
}
}
public static void change (int x[]){
for(int i=0;i<x.length;i++){
x[i]++;
}
}
}
ENHANCED FOR LOOP
class array{
public static void main(String args[]){
int rajath[]={11,22,33,44};
change(rajath);
for(int x:rajath){
System.out.println(x);
}
}
public static void change (int x[]){
for(int i:x ){
i++;
}
}
}
Upvotes: 2
Views: 52
Reputation: 12817
In Enhanced for loop you're incrementing the block variable i
In For loop you're incrementing the element in the array
Upvotes: 1
Reputation: 394146
Your enhanced for loop is equivalent to :
for(int i=0;i<x.length;i++){
int k = x[i];
k++;
}
which is not the same as your regular for loop.
Your regular for loop increments the elements of the array, while your enhanced for loop increments copies of those elements.
Upvotes: 4