go to previous page   go to home page   go to next page

Answer:

Yes — the several uses of j are all within the for statement and its loop body.


Same Name used in Several Loops

Several for statements in sequence can use the same identifier (the same name) for their loop control variable, but each of these is a different variable which can be seen only inside its own loop. Here is an example:


class SameName
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;

    for ( int j = 0;  j < 8; j=j+2 )      // a variable named "j"
        sumEven = sumEven + j;
    System.out.println( "The sum of evens is: " + sumEven ); 

    for ( int j = 1;  j < 8; j=j+2 )      // a different variable named "j"
        sumOdd  = sumOdd + j;
    System.out.println( "The sum of odds is: " + sumOdd );
  } 
}

The two loops work correctly, and don't interfere with each other, even though each one has its own variable named j.


QUESTION 4:

Is the following code correct?


class SameName
{
  public static void main ( String[] args )
  {
    int sumEven = 0;
    int sumOdd  = 0;

    for ( int 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 )      // Notice the change in this line
        sumOdd  = sumOdd + j;                     

    System.out.println( "The sum of odds is: " + sumOdd );
  } 
}