Reputation: 19
What is the meaning of this type of syntax in the for-loop?
public class ReverseNumber {
public static void main(String[] args) {
int num = 1234567, reversed = 0;
for (; num != 0; num /= 10) { // <-- meaning of the first ; ?
int digit = num % 10;
reversed = reversed * 10 + digit;
}
System.out.println("Reversed Number: " + reversed);
}
}
Upvotes: 0
Views: 71
Reputation: 624
if you are using ; in the beginning of the loop that means , you don't have already initialized its value in the below exapmle:
int num = 1234567, reversed = 0;
for(;num != 0; num /= 10) {
int digit = num % 10;
reversed = reversed * 10 + digit;
}
it is already picking the value of "num"
In case if you comment the num value you will get an error.
Upvotes: 0
Reputation: 2850
A for
statement is composed of 3 parts for(statement A; statement B; statement C)
:
All of them are optional. Here some examples of for loop:
for(;;) {
// infinite loop
}
for(int i = 0; i < 10; i++) {
// Loop 10 times and increment i each time
}
int b = i; // impossible. i does not exist anymore
// this for is equivalent to :
int i = 0;
for(; i < 10; i++) {
// Almost the same. The difference here is that I can be accessed after the for loop
}
int b = i; // possible, because i is still visible.
for(int a = 0;; a++) {
// Infinite loop (because no stop condition) to increment variable a
System.out.println(a);
}
for(int constant = 0;;) {
// Infinite loop (no stop condition) and you can use constant variable (but will always be 0)
System.out.println(constant);
}
Upvotes: 2