Is the following code fragment correct?
int sum = 0;
for ( int j = 0; j < 8; j++ )
sum = sum + j;
System.out.println( "The sum is: " + sum );
Yes. The variable sum is declared outside of the for
statement and can be used inside and outside of the loop body.
The variable j is declared inside of the for
statement and can be used only in the body of the loop.
The scope of a variable is the span of statements where it can be used.
The scope of a variable declared as part of a for statement is
that statement and its loop body.
Another way to say this is:
A loop control variable declared as part of aforstatement can only be "seen" by theforstatement and the statements of that loop body.
Is the following code correct?
class bigScope
{
public static void main ( String[] args )
{
int sum = 0;
for ( int j = 0; j < 80; j++ )
{
if ( j % 7 != 0 )
sum = sum + j;
else
System.out.println( "Not added to sum: " + j );
}
System.out.println( "The final sum is: " + sum );
}
}