Keep things local
Here is another version of the program,
which is syntactically correct,
but is not nicely done.
class foolishTypist
{
public static void main ( String[] args )
{
int sumEven = 0;
int sumOdd = 0;
int j; // Same "j" used for both loops.
for ( j = 0; j < 8; j=j+2 )
sumEven = sumEven + j;
System.out.println( "The sum of evens is: " + sumEven );
for ( j = 1; j < 8; j=j+2 )
sumOdd = sumOdd + j;
System.out.println( "The sum of odds is: " + sumOdd );
}
}
|
It is best to keep sections of code self-contained.
With this (foolish) version,
both loops depend on something distant from themselves.
Although this program is clear enough,
in a much longer program will make the program harder to
understand.
Here, for instance, is a typical hard to understand program:
class foolishTypist
{
public static void main ( String[] args )
{
int sumEven = 0;
int sumOdd = 0;
int j = 0;
int i = 1;
for ( j = 0; j < 8; j=j+2 )
sumEven = sumEven + j;
System.out.println( "The sum of evens is: " + sumEven );
for ( i = 1; i < 8; i=i+2 )
sumOdd = sumOdd + j;
System.out.println( "The sum of odds is: " + sumOdd );
}
}
|
|