Variable declaration reset: Difference between revisions

Added Java
m (→‎{{header|C}}: Seem to have lost a semi-colon.)
(Added Java)
Line 145:
}
prev = curr
}
}</lang>
 
{{out}}
<pre>
2
5
</pre>
 
=={{header|Java}}==
Note firstly that variables declared in methods must be assigned a value before they can be used in Java and so here we give '(g)prev' an initial value of 0 which won't clash with the values in the array.
<lang java>public class VariableDeclarationReset {
public static void main(String[] args) {
int[] s = {1, 2, 2, 3, 4, 4, 5};
 
// There is no output as 'prev' is created anew each time
// around the loop and set to zero.
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
int prev = 0;
if (i > 0 && curr == prev) System.out.println(i);
prev = curr;
}
 
int gprev = 0;
 
// Now 'gprev' is used and reassigned
// each time around the loop producing the desired output.
for (int i = 0; i < s.length; ++i) {
int curr = s[i];
if (i > 0 && curr == gprev) System.out.println(i);
gprev = curr;
}
}
}</lang>
9,476

edits