TestGuest
TestGuest

Reputation: 603

Scope of Variable in While vs. For Loop

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

Answers (3)

rfoo
rfoo

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

Rahul Tripathi
Rahul Tripathi

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

Martin Serrano
Martin Serrano

Reputation: 3775

Yes. Just declare the loop variable outside the for loop:

  int i;
  for (i=0; i<=5;i++) {
    sum += i;
  }

Upvotes: 5

Related Questions