Reputation: 603
I was wondering the following, given that I want to perform the same simple task but once using a while loop and once a for loop as follows:
for(int i = 1; i <= 5; ++i){
sum += i;
}
I do not see any possibility to print out the (counting) variable i
of the for
loop while that would be no problem with a while
loop:
int j = 0;
int sum2 = 0;
while (j <= 6) {
sum2 += j;
++j;
}
System.out.print(j);
Or is this possible using for
loop too, somehow?
Upvotes: 2
Views: 103
Reputation: 1198
It's actually in some ways even easier for the for loop.
int i = 0;
for(;i <= 5; i++){
sum += i;
}
Since you already declared the int i = 0
you can skip the first entry in the for loop.
Upvotes: 1
Reputation: 172458
Yes thats possible. You just need to declare the variable i
before the for
loop. Try like this:-
int i;
for (i=0; i<=5;i++)
{
sum += i;
}
Upvotes: 1
Reputation: 3775
Yes. Just declare the loop variable outside the for loop:
int i;
for (i=0; i<=5;i++) {
sum += i;
}
Upvotes: 5